path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
app/javascript/mastodon/components/display_name.js
salvadorpla/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; export default class DisplayName extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, others: ImmutablePropTypes.list, localDomain: PropTypes.string, }; render () { const { others, localDomain } = this.props; let displayName, suffix, account; if (others && others.size > 1) { displayName = others.take(2).map(a => <bdi key={a.get('id')}><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: a.get('display_name_html') }} /></bdi>).reduce((prev, cur) => [prev, ', ', cur]); if (others.size - 2 > 0) { suffix = `+${others.size - 2}`; } } else { if (others && others.size > 0) { account = others.first(); } else { account = this.props.account; } let acct = account.get('acct'); if (acct.indexOf('@') === -1 && localDomain) { acct = `${acct}@${localDomain}`; } displayName = <bdi><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: account.get('display_name_html') }} /></bdi>; suffix = <span className='display-name__account'>@{acct}</span>; } return ( <span className='display-name'> {displayName} {suffix} </span> ); } }
src/components/DeveloperMenu.js
jacktuck/registr
import React from 'react'; import {View} from 'react-native'; // For tests const DeveloperMenu = () => <View/>; export default DeveloperMenu;
src/svg-icons/device/battery-20.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery20 = (props) => ( <SvgIcon {...props}> <path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z"/><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z"/> </SvgIcon> ); DeviceBattery20 = pure(DeviceBattery20); DeviceBattery20.displayName = 'DeviceBattery20'; export default DeviceBattery20;
svg-icons/file/create-new-folder.js
janmarsicek/material-ui
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FileCreateNewFolder = function FileCreateNewFolder(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z' }) ); }; FileCreateNewFolder = (0, _pure2.default)(FileCreateNewFolder); FileCreateNewFolder.displayName = 'FileCreateNewFolder'; FileCreateNewFolder.muiName = 'SvgIcon'; exports.default = FileCreateNewFolder;
ajax/libs/rxjs/2.2.21/rx.lite.extras.js
x112358/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx', 'exports'], function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, noop = helpers.noop, observableFromPromise = Observable.fromPromise, slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var argumentOutOfRange = 'Argument out of range'; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * 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 = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); return Rx; }));
ajax/libs/yui/3.10.0/datatable-core/datatable-core-coverage.js
Dervisevic/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/datatable-core/datatable-core.js']) { __coverage__['build/datatable-core/datatable-core.js'] = {"path":"build/datatable-core/datatable-core.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,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":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,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,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,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0,0],"53":[0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0,0],"60":[0,0],"61":[0,0,0],"62":[0,0],"63":[0,0,0],"64":[0,0],"65":[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,"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},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":38,"loc":{"start":{"line":38,"column":40},"end":{"line":38,"column":52}}},"3":{"name":"(anonymous_3)","line":231,"loc":{"start":{"line":231,"column":15},"end":{"line":231,"column":31}}},"4":{"name":"(anonymous_4)","line":278,"loc":{"start":{"line":278,"column":15},"end":{"line":278,"column":31}}},"5":{"name":"(anonymous_5)","line":344,"loc":{"start":{"line":344,"column":25},"end":{"line":344,"column":38}}},"6":{"name":"(anonymous_6)","line":357,"loc":{"start":{"line":357,"column":22},"end":{"line":357,"column":35}}},"7":{"name":"(anonymous_7)","line":377,"loc":{"start":{"line":377,"column":28},"end":{"line":377,"column":41}}},"8":{"name":"(anonymous_8)","line":406,"loc":{"start":{"line":406,"column":24},"end":{"line":406,"column":41}}},"9":{"name":"(anonymous_9)","line":429,"loc":{"start":{"line":429,"column":16},"end":{"line":429,"column":28}}},"10":{"name":"(anonymous_10)","line":445,"loc":{"start":{"line":445,"column":17},"end":{"line":445,"column":42}}},"11":{"name":"(anonymous_11)","line":468,"loc":{"start":{"line":468,"column":19},"end":{"line":468,"column":38}}},"12":{"name":"(anonymous_12)","line":480,"loc":{"start":{"line":480,"column":20},"end":{"line":480,"column":35}}},"13":{"name":"(anonymous_13)","line":500,"loc":{"start":{"line":500,"column":18},"end":{"line":500,"column":30}}},"14":{"name":"(anonymous_14)","line":526,"loc":{"start":{"line":526,"column":21},"end":{"line":526,"column":33}}},"15":{"name":"(anonymous_15)","line":544,"loc":{"start":{"line":544,"column":15},"end":{"line":544,"column":27}}},"16":{"name":"(anonymous_16)","line":569,"loc":{"start":{"line":569,"column":23},"end":{"line":569,"column":39}}},"17":{"name":"(anonymous_17)","line":607,"loc":{"start":{"line":607,"column":17},"end":{"line":607,"column":35}}},"18":{"name":"(anonymous_18)","line":653,"loc":{"start":{"line":653,"column":19},"end":{"line":653,"column":38}}},"19":{"name":"process","line":656,"loc":{"start":{"line":656,"column":8},"end":{"line":656,"column":31}}},"20":{"name":"(anonymous_20)","line":704,"loc":{"start":{"line":704,"column":17},"end":{"line":704,"column":32}}},"21":{"name":"copyObj","line":710,"loc":{"start":{"line":710,"column":8},"end":{"line":710,"column":28}}},"22":{"name":"genId","line":736,"loc":{"start":{"line":736,"column":8},"end":{"line":736,"column":29}}},"23":{"name":"process","line":750,"loc":{"start":{"line":750,"column":8},"end":{"line":750,"column":39}}},"24":{"name":"(anonymous_24)","line":806,"loc":{"start":{"line":806,"column":19},"end":{"line":806,"column":34}}},"25":{"name":"(anonymous_25)","line":829,"loc":{"start":{"line":829,"column":14},"end":{"line":829,"column":29}}},"26":{"name":"(anonymous_26)","line":867,"loc":{"start":{"line":867,"column":19},"end":{"line":867,"column":34}}},"27":{"name":"(anonymous_27)","line":872,"loc":{"start":{"line":872,"column":21},"end":{"line":872,"column":39}}},"28":{"name":"(anonymous_28)","line":899,"loc":{"start":{"line":899,"column":20},"end":{"line":899,"column":35}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":915,"column":79}},"2":{"start":{"line":11,"column":0},"end":{"line":24,"column":10}},"3":{"start":{"line":38,"column":0},"end":{"line":38,"column":55}},"4":{"start":{"line":40,"column":0},"end":{"line":199,"column":2}},"5":{"start":{"line":201,"column":0},"end":{"line":912,"column":3}},"6":{"start":{"line":232,"column":8},"end":{"line":232,"column":39}},"7":{"start":{"line":234,"column":8},"end":{"line":242,"column":9}},"8":{"start":{"line":239,"column":12},"end":{"line":239,"column":23}},"9":{"start":{"line":241,"column":12},"end":{"line":241,"column":46}},"10":{"start":{"line":244,"column":8},"end":{"line":246,"column":9}},"11":{"start":{"line":245,"column":12},"end":{"line":245,"column":23}},"12":{"start":{"line":248,"column":8},"end":{"line":248,"column":38}},"13":{"start":{"line":250,"column":8},"end":{"line":259,"column":9}},"14":{"start":{"line":251,"column":12},"end":{"line":251,"column":33}},"15":{"start":{"line":252,"column":12},"end":{"line":252,"column":27}},"16":{"start":{"line":254,"column":12},"end":{"line":256,"column":13}},"17":{"start":{"line":255,"column":16},"end":{"line":255,"column":63}},"18":{"start":{"line":258,"column":12},"end":{"line":258,"column":51}},"19":{"start":{"line":261,"column":8},"end":{"line":261,"column":20}},"20":{"start":{"line":279,"column":8},"end":{"line":279,"column":78}},"21":{"start":{"line":281,"column":8},"end":{"line":290,"column":9}},"22":{"start":{"line":282,"column":12},"end":{"line":284,"column":13}},"23":{"start":{"line":283,"column":16},"end":{"line":283,"column":46}},"24":{"start":{"line":287,"column":12},"end":{"line":289,"column":13}},"25":{"start":{"line":288,"column":16},"end":{"line":288,"column":73}},"26":{"start":{"line":292,"column":8},"end":{"line":292,"column":30}},"27":{"start":{"line":345,"column":8},"end":{"line":345,"column":37}},"28":{"start":{"line":358,"column":8},"end":{"line":358,"column":33}},"29":{"start":{"line":360,"column":8},"end":{"line":360,"column":29}},"30":{"start":{"line":362,"column":8},"end":{"line":366,"column":9}},"31":{"start":{"line":365,"column":12},"end":{"line":365,"column":32}},"32":{"start":{"line":378,"column":8},"end":{"line":378,"column":38}},"33":{"start":{"line":380,"column":8},"end":{"line":380,"column":35}},"34":{"start":{"line":382,"column":8},"end":{"line":382,"column":30}},"35":{"start":{"line":384,"column":8},"end":{"line":390,"column":9}},"36":{"start":{"line":385,"column":12},"end":{"line":389,"column":13}},"37":{"start":{"line":386,"column":16},"end":{"line":386,"column":36}},"38":{"start":{"line":388,"column":16},"end":{"line":388,"column":58}},"39":{"start":{"line":407,"column":8},"end":{"line":407,"column":26}},"40":{"start":{"line":409,"column":8},"end":{"line":417,"column":9}},"41":{"start":{"line":410,"column":12},"end":{"line":410,"column":23}},"42":{"start":{"line":412,"column":12},"end":{"line":414,"column":13}},"43":{"start":{"line":413,"column":16},"end":{"line":413,"column":37}},"44":{"start":{"line":415,"column":15},"end":{"line":417,"column":9}},"45":{"start":{"line":416,"column":12},"end":{"line":416,"column":26}},"46":{"start":{"line":419,"column":8},"end":{"line":419,"column":76}},"47":{"start":{"line":430,"column":8},"end":{"line":430,"column":72}},"48":{"start":{"line":449,"column":8},"end":{"line":449,"column":59}},"49":{"start":{"line":469,"column":8},"end":{"line":469,"column":63}},"50":{"start":{"line":487,"column":8},"end":{"line":487,"column":53}},"51":{"start":{"line":501,"column":8},"end":{"line":502,"column":17}},"52":{"start":{"line":505,"column":8},"end":{"line":514,"column":9}},"53":{"start":{"line":507,"column":12},"end":{"line":507,"column":37}},"54":{"start":{"line":509,"column":12},"end":{"line":511,"column":13}},"55":{"start":{"line":510,"column":16},"end":{"line":510,"column":37}},"56":{"start":{"line":513,"column":12},"end":{"line":513,"column":44}},"57":{"start":{"line":516,"column":8},"end":{"line":516,"column":36}},"58":{"start":{"line":527,"column":8},"end":{"line":531,"column":11}},"59":{"start":{"line":545,"column":8},"end":{"line":547,"column":42}},"60":{"start":{"line":549,"column":8},"end":{"line":551,"column":9}},"61":{"start":{"line":550,"column":12},"end":{"line":550,"column":41}},"62":{"start":{"line":553,"column":8},"end":{"line":553,"column":25}},"63":{"start":{"line":570,"column":8},"end":{"line":570,"column":23}},"64":{"start":{"line":572,"column":8},"end":{"line":596,"column":9}},"65":{"start":{"line":573,"column":12},"end":{"line":573,"column":48}},"66":{"start":{"line":575,"column":12},"end":{"line":589,"column":13}},"67":{"start":{"line":576,"column":16},"end":{"line":576,"column":33}},"68":{"start":{"line":578,"column":16},"end":{"line":580,"column":17}},"69":{"start":{"line":579,"column":20},"end":{"line":579,"column":49}},"70":{"start":{"line":584,"column":16},"end":{"line":584,"column":46}},"71":{"start":{"line":586,"column":16},"end":{"line":588,"column":17}},"72":{"start":{"line":587,"column":20},"end":{"line":587,"column":49}},"73":{"start":{"line":595,"column":12},"end":{"line":595,"column":38}},"74":{"start":{"line":608,"column":8},"end":{"line":610,"column":23}},"75":{"start":{"line":614,"column":8},"end":{"line":614,"column":37}},"76":{"start":{"line":620,"column":8},"end":{"line":633,"column":9}},"77":{"start":{"line":621,"column":12},"end":{"line":622,"column":51}},"78":{"start":{"line":624,"column":12},"end":{"line":628,"column":13}},"79":{"start":{"line":625,"column":16},"end":{"line":625,"column":49}},"80":{"start":{"line":626,"column":19},"end":{"line":628,"column":13}},"81":{"start":{"line":627,"column":16},"end":{"line":627,"column":40}},"82":{"start":{"line":630,"column":12},"end":{"line":632,"column":13}},"83":{"start":{"line":631,"column":16},"end":{"line":631,"column":45}},"84":{"start":{"line":635,"column":8},"end":{"line":635,"column":28}},"85":{"start":{"line":637,"column":8},"end":{"line":637,"column":32}},"86":{"start":{"line":639,"column":8},"end":{"line":639,"column":31}},"87":{"start":{"line":654,"column":8},"end":{"line":654,"column":21}},"88":{"start":{"line":656,"column":8},"end":{"line":679,"column":9}},"89":{"start":{"line":657,"column":12},"end":{"line":657,"column":33}},"90":{"start":{"line":659,"column":12},"end":{"line":678,"column":13}},"91":{"start":{"line":660,"column":16},"end":{"line":660,"column":30}},"92":{"start":{"line":661,"column":16},"end":{"line":661,"column":30}},"93":{"start":{"line":668,"column":16},"end":{"line":670,"column":17}},"94":{"start":{"line":669,"column":20},"end":{"line":669,"column":35}},"95":{"start":{"line":673,"column":16},"end":{"line":673,"column":35}},"96":{"start":{"line":675,"column":16},"end":{"line":677,"column":17}},"97":{"start":{"line":676,"column":20},"end":{"line":676,"column":42}},"98":{"start":{"line":681,"column":8},"end":{"line":681,"column":25}},"99":{"start":{"line":683,"column":8},"end":{"line":683,"column":30}},"100":{"start":{"line":705,"column":8},"end":{"line":708,"column":41}},"101":{"start":{"line":710,"column":8},"end":{"line":734,"column":9}},"102":{"start":{"line":711,"column":12},"end":{"line":712,"column":28}},"103":{"start":{"line":714,"column":12},"end":{"line":714,"column":26}},"104":{"start":{"line":715,"column":12},"end":{"line":715,"column":35}},"105":{"start":{"line":717,"column":12},"end":{"line":731,"column":13}},"106":{"start":{"line":718,"column":16},"end":{"line":730,"column":17}},"107":{"start":{"line":719,"column":20},"end":{"line":719,"column":33}},"108":{"start":{"line":721,"column":20},"end":{"line":729,"column":21}},"109":{"start":{"line":722,"column":24},"end":{"line":722,"column":48}},"110":{"start":{"line":723,"column":27},"end":{"line":729,"column":21}},"111":{"start":{"line":724,"column":24},"end":{"line":724,"column":51}},"112":{"start":{"line":726,"column":24},"end":{"line":726,"column":77}},"113":{"start":{"line":728,"column":24},"end":{"line":728,"column":43}},"114":{"start":{"line":733,"column":12},"end":{"line":733,"column":24}},"115":{"start":{"line":736,"column":8},"end":{"line":748,"column":9}},"116":{"start":{"line":739,"column":12},"end":{"line":739,"column":44}},"117":{"start":{"line":741,"column":12},"end":{"line":745,"column":13}},"118":{"start":{"line":742,"column":16},"end":{"line":742,"column":39}},"119":{"start":{"line":744,"column":16},"end":{"line":744,"column":31}},"120":{"start":{"line":747,"column":12},"end":{"line":747,"column":24}},"121":{"start":{"line":750,"column":8},"end":{"line":789,"column":9}},"122":{"start":{"line":751,"column":12},"end":{"line":752,"column":34}},"123":{"start":{"line":754,"column":12},"end":{"line":786,"column":13}},"124":{"start":{"line":755,"column":16},"end":{"line":756,"column":78}},"125":{"start":{"line":758,"column":16},"end":{"line":758,"column":36}},"126":{"start":{"line":761,"column":16},"end":{"line":765,"column":17}},"127":{"start":{"line":764,"column":20},"end":{"line":764,"column":34}},"128":{"start":{"line":766,"column":16},"end":{"line":770,"column":17}},"129":{"start":{"line":769,"column":20},"end":{"line":769,"column":41}},"130":{"start":{"line":772,"column":16},"end":{"line":776,"column":17}},"131":{"start":{"line":773,"column":20},"end":{"line":773,"column":41}},"132":{"start":{"line":775,"column":20},"end":{"line":775,"column":39}},"133":{"start":{"line":781,"column":16},"end":{"line":781,"column":63}},"134":{"start":{"line":783,"column":16},"end":{"line":785,"column":17}},"135":{"start":{"line":784,"column":20},"end":{"line":784,"column":62}},"136":{"start":{"line":788,"column":12},"end":{"line":788,"column":27}},"137":{"start":{"line":791,"column":8},"end":{"line":791,"column":35}},"138":{"start":{"line":807,"column":8},"end":{"line":807,"column":33}},"139":{"start":{"line":809,"column":8},"end":{"line":809,"column":44}},"140":{"start":{"line":830,"column":8},"end":{"line":832,"column":9}},"141":{"start":{"line":831,"column":12},"end":{"line":831,"column":21}},"142":{"start":{"line":834,"column":8},"end":{"line":850,"column":9}},"143":{"start":{"line":835,"column":12},"end":{"line":835,"column":37}},"144":{"start":{"line":841,"column":12},"end":{"line":841,"column":51}},"145":{"start":{"line":846,"column":12},"end":{"line":846,"column":28}},"146":{"start":{"line":847,"column":15},"end":{"line":850,"column":9}},"147":{"start":{"line":849,"column":12},"end":{"line":849,"column":26}},"148":{"start":{"line":852,"column":8},"end":{"line":852,"column":19}},"149":{"start":{"line":868,"column":8},"end":{"line":868,"column":17}},"150":{"start":{"line":870,"column":8},"end":{"line":876,"column":9}},"151":{"start":{"line":871,"column":12},"end":{"line":871,"column":22}},"152":{"start":{"line":872,"column":12},"end":{"line":874,"column":15}},"153":{"start":{"line":873,"column":16},"end":{"line":873,"column":46}},"154":{"start":{"line":875,"column":12},"end":{"line":875,"column":23}},"155":{"start":{"line":878,"column":8},"end":{"line":878,"column":30}},"156":{"start":{"line":880,"column":8},"end":{"line":880,"column":19}},"157":{"start":{"line":900,"column":8},"end":{"line":900,"column":23}},"158":{"start":{"line":903,"column":8},"end":{"line":907,"column":9}},"159":{"start":{"line":904,"column":12},"end":{"line":904,"column":29}},"160":{"start":{"line":905,"column":15},"end":{"line":907,"column":9}},"161":{"start":{"line":906,"column":12},"end":{"line":906,"column":54}},"162":{"start":{"line":909,"column":8},"end":{"line":909,"column":37}}},"branchMap":{"1":{"line":234,"type":"if","locations":[{"start":{"line":234,"column":8},"end":{"line":234,"column":8}},{"start":{"line":234,"column":8},"end":{"line":234,"column":8}}]},"2":{"line":234,"type":"binary-expr","locations":[{"start":{"line":234,"column":12},"end":{"line":234,"column":26}},{"start":{"line":234,"column":30},"end":{"line":234,"column":44}}]},"3":{"line":244,"type":"if","locations":[{"start":{"line":244,"column":8},"end":{"line":244,"column":8}},{"start":{"line":244,"column":8},"end":{"line":244,"column":8}}]},"4":{"line":250,"type":"if","locations":[{"start":{"line":250,"column":8},"end":{"line":250,"column":8}},{"start":{"line":250,"column":8},"end":{"line":250,"column":8}}]},"5":{"line":250,"type":"binary-expr","locations":[{"start":{"line":250,"column":12},"end":{"line":250,"column":26}},{"start":{"line":250,"column":30},"end":{"line":250,"column":43}}]},"6":{"line":254,"type":"binary-expr","locations":[{"start":{"line":254,"column":47},"end":{"line":254,"column":51}},{"start":{"line":254,"column":55},"end":{"line":254,"column":62}}]},"7":{"line":255,"type":"binary-expr","locations":[{"start":{"line":255,"column":23},"end":{"line":255,"column":36}},{"start":{"line":255,"column":40},"end":{"line":255,"column":62}}]},"8":{"line":258,"type":"binary-expr","locations":[{"start":{"line":258,"column":20},"end":{"line":258,"column":24}},{"start":{"line":258,"column":28},"end":{"line":258,"column":41}},{"start":{"line":258,"column":46},"end":{"line":258,"column":50}}]},"9":{"line":279,"type":"binary-expr","locations":[{"start":{"line":279,"column":21},"end":{"line":279,"column":44}},{"start":{"line":279,"column":48},"end":{"line":279,"column":77}}]},"10":{"line":281,"type":"if","locations":[{"start":{"line":281,"column":8},"end":{"line":281,"column":8}},{"start":{"line":281,"column":8},"end":{"line":281,"column":8}}]},"11":{"line":282,"type":"if","locations":[{"start":{"line":282,"column":12},"end":{"line":282,"column":12}},{"start":{"line":282,"column":12},"end":{"line":282,"column":12}}]},"12":{"line":287,"type":"if","locations":[{"start":{"line":287,"column":12},"end":{"line":287,"column":12}},{"start":{"line":287,"column":12},"end":{"line":287,"column":12}}]},"13":{"line":287,"type":"binary-expr","locations":[{"start":{"line":287,"column":16},"end":{"line":287,"column":23}},{"start":{"line":287,"column":27},"end":{"line":287,"column":36}},{"start":{"line":287,"column":40},"end":{"line":287,"column":59}}]},"14":{"line":292,"type":"binary-expr","locations":[{"start":{"line":292,"column":15},"end":{"line":292,"column":21}},{"start":{"line":292,"column":25},"end":{"line":292,"column":29}}]},"15":{"line":362,"type":"if","locations":[{"start":{"line":362,"column":8},"end":{"line":362,"column":8}},{"start":{"line":362,"column":8},"end":{"line":362,"column":8}}]},"16":{"line":362,"type":"binary-expr","locations":[{"start":{"line":362,"column":12},"end":{"line":362,"column":32}},{"start":{"line":362,"column":36},"end":{"line":362,"column":52}}]},"17":{"line":384,"type":"if","locations":[{"start":{"line":384,"column":8},"end":{"line":384,"column":8}},{"start":{"line":384,"column":8},"end":{"line":384,"column":8}}]},"18":{"line":384,"type":"binary-expr","locations":[{"start":{"line":384,"column":12},"end":{"line":384,"column":32}},{"start":{"line":384,"column":36},"end":{"line":384,"column":40}}]},"19":{"line":385,"type":"if","locations":[{"start":{"line":385,"column":12},"end":{"line":385,"column":12}},{"start":{"line":385,"column":12},"end":{"line":385,"column":12}}]},"20":{"line":409,"type":"if","locations":[{"start":{"line":409,"column":8},"end":{"line":409,"column":8}},{"start":{"line":409,"column":8},"end":{"line":409,"column":8}}]},"21":{"line":415,"type":"if","locations":[{"start":{"line":415,"column":15},"end":{"line":415,"column":15}},{"start":{"line":415,"column":15},"end":{"line":415,"column":15}}]},"22":{"line":449,"type":"cond-expr","locations":[{"start":{"line":449,"column":33},"end":{"line":449,"column":48}},{"start":{"line":449,"column":51},"end":{"line":449,"column":58}}]},"23":{"line":487,"type":"binary-expr","locations":[{"start":{"line":487,"column":15},"end":{"line":487,"column":18}},{"start":{"line":487,"column":23},"end":{"line":487,"column":32}},{"start":{"line":487,"column":36},"end":{"line":487,"column":51}}]},"24":{"line":501,"type":"binary-expr","locations":[{"start":{"line":501,"column":22},"end":{"line":501,"column":41}},{"start":{"line":501,"column":45},"end":{"line":501,"column":47}}]},"25":{"line":505,"type":"if","locations":[{"start":{"line":505,"column":8},"end":{"line":505,"column":8}},{"start":{"line":505,"column":8},"end":{"line":505,"column":8}}]},"26":{"line":505,"type":"binary-expr","locations":[{"start":{"line":505,"column":12},"end":{"line":505,"column":27}},{"start":{"line":505,"column":31},"end":{"line":505,"column":47}}]},"27":{"line":509,"type":"if","locations":[{"start":{"line":509,"column":12},"end":{"line":509,"column":12}},{"start":{"line":509,"column":12},"end":{"line":509,"column":12}}]},"28":{"line":549,"type":"if","locations":[{"start":{"line":549,"column":8},"end":{"line":549,"column":8}},{"start":{"line":549,"column":8},"end":{"line":549,"column":8}}]},"29":{"line":572,"type":"if","locations":[{"start":{"line":572,"column":8},"end":{"line":572,"column":8}},{"start":{"line":572,"column":8},"end":{"line":572,"column":8}}]},"30":{"line":575,"type":"if","locations":[{"start":{"line":575,"column":12},"end":{"line":575,"column":12}},{"start":{"line":575,"column":12},"end":{"line":575,"column":12}}]},"31":{"line":575,"type":"binary-expr","locations":[{"start":{"line":575,"column":16},"end":{"line":575,"column":20}},{"start":{"line":575,"column":24},"end":{"line":575,"column":33}},{"start":{"line":575,"column":37},"end":{"line":575,"column":48}}]},"32":{"line":578,"type":"if","locations":[{"start":{"line":578,"column":16},"end":{"line":578,"column":16}},{"start":{"line":578,"column":16},"end":{"line":578,"column":16}}]},"33":{"line":586,"type":"if","locations":[{"start":{"line":586,"column":16},"end":{"line":586,"column":16}},{"start":{"line":586,"column":16},"end":{"line":586,"column":16}}]},"34":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"35":{"line":621,"type":"binary-expr","locations":[{"start":{"line":621,"column":26},"end":{"line":621,"column":43}},{"start":{"line":621,"column":47},"end":{"line":621,"column":72}},{"start":{"line":622,"column":28},"end":{"line":622,"column":50}}]},"36":{"line":624,"type":"if","locations":[{"start":{"line":624,"column":12},"end":{"line":624,"column":12}},{"start":{"line":624,"column":12},"end":{"line":624,"column":12}}]},"37":{"line":626,"type":"if","locations":[{"start":{"line":626,"column":19},"end":{"line":626,"column":19}},{"start":{"line":626,"column":19},"end":{"line":626,"column":19}}]},"38":{"line":626,"type":"binary-expr","locations":[{"start":{"line":626,"column":23},"end":{"line":626,"column":36}},{"start":{"line":626,"column":40},"end":{"line":626,"column":51}}]},"39":{"line":630,"type":"if","locations":[{"start":{"line":630,"column":12},"end":{"line":630,"column":12}},{"start":{"line":630,"column":12},"end":{"line":630,"column":12}}]},"40":{"line":668,"type":"if","locations":[{"start":{"line":668,"column":16},"end":{"line":668,"column":16}},{"start":{"line":668,"column":16},"end":{"line":668,"column":16}}]},"41":{"line":668,"type":"binary-expr","locations":[{"start":{"line":668,"column":20},"end":{"line":668,"column":23}},{"start":{"line":668,"column":27},"end":{"line":668,"column":36}}]},"42":{"line":675,"type":"if","locations":[{"start":{"line":675,"column":16},"end":{"line":675,"column":16}},{"start":{"line":675,"column":16},"end":{"line":675,"column":16}}]},"43":{"line":718,"type":"if","locations":[{"start":{"line":718,"column":16},"end":{"line":718,"column":16}},{"start":{"line":718,"column":16},"end":{"line":718,"column":16}}]},"44":{"line":721,"type":"if","locations":[{"start":{"line":721,"column":20},"end":{"line":721,"column":20}},{"start":{"line":721,"column":20},"end":{"line":721,"column":20}}]},"45":{"line":723,"type":"if","locations":[{"start":{"line":723,"column":27},"end":{"line":723,"column":27}},{"start":{"line":723,"column":27},"end":{"line":723,"column":27}}]},"46":{"line":726,"type":"cond-expr","locations":[{"start":{"line":726,"column":47},"end":{"line":726,"column":59}},{"start":{"line":726,"column":62},"end":{"line":726,"column":76}}]},"47":{"line":741,"type":"if","locations":[{"start":{"line":741,"column":12},"end":{"line":741,"column":12}},{"start":{"line":741,"column":12},"end":{"line":741,"column":12}}]},"48":{"line":756,"type":"cond-expr","locations":[{"start":{"line":756,"column":42},"end":{"line":756,"column":58}},{"start":{"line":756,"column":61},"end":{"line":756,"column":77}}]},"49":{"line":761,"type":"if","locations":[{"start":{"line":761,"column":16},"end":{"line":761,"column":16}},{"start":{"line":761,"column":16},"end":{"line":761,"column":16}}]},"50":{"line":766,"type":"if","locations":[{"start":{"line":766,"column":16},"end":{"line":766,"column":16}},{"start":{"line":766,"column":16},"end":{"line":766,"column":16}}]},"51":{"line":772,"type":"if","locations":[{"start":{"line":772,"column":16},"end":{"line":772,"column":16}},{"start":{"line":772,"column":16},"end":{"line":772,"column":16}}]},"52":{"line":781,"type":"binary-expr","locations":[{"start":{"line":781,"column":32},"end":{"line":781,"column":40}},{"start":{"line":781,"column":44},"end":{"line":781,"column":51}},{"start":{"line":781,"column":55},"end":{"line":781,"column":61}}]},"53":{"line":783,"type":"if","locations":[{"start":{"line":783,"column":16},"end":{"line":783,"column":16}},{"start":{"line":783,"column":16},"end":{"line":783,"column":16}}]},"54":{"line":791,"type":"binary-expr","locations":[{"start":{"line":791,"column":15},"end":{"line":791,"column":18}},{"start":{"line":791,"column":22},"end":{"line":791,"column":34}}]},"55":{"line":809,"type":"cond-expr","locations":[{"start":{"line":809,"column":30},"end":{"line":809,"column":33}},{"start":{"line":809,"column":36},"end":{"line":809,"column":43}}]},"56":{"line":830,"type":"if","locations":[{"start":{"line":830,"column":8},"end":{"line":830,"column":8}},{"start":{"line":830,"column":8},"end":{"line":830,"column":8}}]},"57":{"line":834,"type":"if","locations":[{"start":{"line":834,"column":8},"end":{"line":834,"column":8}},{"start":{"line":834,"column":8},"end":{"line":834,"column":8}}]},"58":{"line":847,"type":"if","locations":[{"start":{"line":847,"column":15},"end":{"line":847,"column":15}},{"start":{"line":847,"column":15},"end":{"line":847,"column":15}}]},"59":{"line":847,"type":"binary-expr","locations":[{"start":{"line":847,"column":19},"end":{"line":847,"column":23}},{"start":{"line":847,"column":27},"end":{"line":847,"column":36}},{"start":{"line":847,"column":40},"end":{"line":847,"column":51}}]},"60":{"line":870,"type":"if","locations":[{"start":{"line":870,"column":8},"end":{"line":870,"column":8}},{"start":{"line":870,"column":8},"end":{"line":870,"column":8}}]},"61":{"line":870,"type":"binary-expr","locations":[{"start":{"line":870,"column":12},"end":{"line":870,"column":15}},{"start":{"line":870,"column":19},"end":{"line":870,"column":30}},{"start":{"line":870,"column":34},"end":{"line":870,"column":60}}]},"62":{"line":903,"type":"if","locations":[{"start":{"line":903,"column":8},"end":{"line":903,"column":8}},{"start":{"line":903,"column":8},"end":{"line":903,"column":8}}]},"63":{"line":903,"type":"binary-expr","locations":[{"start":{"line":903,"column":12},"end":{"line":903,"column":27}},{"start":{"line":903,"column":31},"end":{"line":903,"column":51}},{"start":{"line":903,"column":55},"end":{"line":903,"column":77}}]},"64":{"line":905,"type":"if","locations":[{"start":{"line":905,"column":15},"end":{"line":905,"column":15}},{"start":{"line":905,"column":15},"end":{"line":905,"column":15}}]},"65":{"line":909,"type":"binary-expr","locations":[{"start":{"line":909,"column":15},"end":{"line":909,"column":25}},{"start":{"line":909,"column":29},"end":{"line":909,"column":36}}]}},"code":["(function () { YUI.add('datatable-core', function (Y, NAME) {","","/**","The core implementation of the `DataTable` and `DataTable.Base` Widgets.","","@module datatable","@submodule datatable-core","@since 3.5.0","**/","","var INVALID = Y.Attribute.INVALID_VALUE,",""," Lang = Y.Lang,"," isFunction = Lang.isFunction,"," isObject = Lang.isObject,"," isArray = Lang.isArray,"," isString = Lang.isString,"," isNumber = Lang.isNumber,",""," toArray = Y.Array,",""," keys = Y.Object.keys,",""," Table;"," ","/**","_API docs for this extension are included in the DataTable class._","","Class extension providing the core API and structure for the DataTable Widget.","","Use this class extension with Widget or another Base-based superclass to create","the basic DataTable model API and composing class structure.","","@class DataTable.Core","@for DataTable","@since 3.5.0","**/","Table = Y.namespace('DataTable').Core = function () {};","","Table.ATTRS = {"," /**"," Columns to include in the rendered table."," "," If omitted, the attributes on the configured `recordType` or the first item"," in the `data` collection will be used as a source.",""," This attribute takes an array of strings or objects (mixing the two is"," fine). Each string or object is considered a column to be rendered."," Strings are converted to objects, so `columns: ['first', 'last']` becomes"," `columns: [{ key: 'first' }, { key: 'last' }]`.",""," DataTable.Core only concerns itself with a few properties of columns."," These properties are:",""," * `key` - Used to identify the record field/attribute containing content for"," this column. Also used to create a default Model if no `recordType` or"," `data` are provided during construction. If `name` is not specified, this"," is assigned to the `_id` property (with added incrementer if the key is"," used by multiple columns)."," * `children` - Traversed to initialize nested column objects"," * `name` - Used in place of, or in addition to, the `key`. Useful for"," columns that aren't bound to a field/attribute in the record data. This"," is assigned to the `_id` property."," * `id` - For backward compatibility. Implementers can specify the id of"," the header cell. This should be avoided, if possible, to avoid the"," potential for creating DOM elements with duplicate IDs."," * `field` - For backward compatibility. Implementers should use `name`."," * `_id` - Assigned unique-within-this-instance id for a column. By order"," of preference, assumes the value of `name`, `key`, `id`, or `_yuid`."," This is used by the rendering views as well as feature module"," as a means to identify a specific column without ambiguity (such as"," multiple columns using the same `key`."," * `_yuid` - Guid stamp assigned to the column object."," * `_parent` - Assigned to all child columns, referencing their parent"," column.",""," @attribute columns"," @type {Object[]|String[]}"," @default (from `recordType` ATTRS or first item in the `data`)"," @since 3.5.0"," **/"," columns: {"," // TODO: change to setter to clone input array/objects"," validator: isArray,"," setter: '_setColumns',"," getter: '_getColumns'"," },",""," /**"," Model subclass to use as the `model` for the ModelList stored in the `data`"," attribute.",""," If not provided, it will try really hard to figure out what to use. The"," following attempts will be made to set a default value:"," "," 1. If the `data` attribute is set with a ModelList instance and its `model`"," property is set, that will be used."," 2. If the `data` attribute is set with a ModelList instance, and its"," `model` property is unset, but it is populated, the `ATTRS` of the"," `constructor of the first item will be used."," 3. If the `data` attribute is set with a non-empty array, a Model subclass"," will be generated using the keys of the first item as its `ATTRS` (see"," the `_createRecordClass` method)."," 4. If the `columns` attribute is set, a Model subclass will be generated"," using the columns defined with a `key`. This is least desirable because"," columns can be duplicated or nested in a way that's not parsable."," 5. If neither `data` nor `columns` is set or populated, a change event"," subscriber will listen for the first to be changed and try all over"," again.",""," @attribute recordType"," @type {Function}"," @default (see description)"," @since 3.5.0"," **/"," recordType: {"," getter: '_getRecordType',"," setter: '_setRecordType'"," },",""," /**"," The collection of data records to display. This attribute is a pass"," through to a `data` property, which is a ModelList instance.",""," If this attribute is passed a ModelList or subclass, it will be assigned to"," the property directly. If an array of objects is passed, a new ModelList"," will be created using the configured `recordType` as its `model` property"," and seeded with the array.",""," Retrieving this attribute will return the ModelList stored in the `data`"," property.",""," @attribute data"," @type {ModelList|Object[]}"," @default `new ModelList()`"," @since 3.5.0"," **/"," data: {"," valueFn: '_initData',"," setter : '_setData',"," lazyAdd: false"," },",""," /**"," Content for the `<table summary=\"ATTRIBUTE VALUE HERE\">`. Values assigned"," to this attribute will be HTML escaped for security.",""," @attribute summary"," @type {String}"," @default '' (empty string)"," @since 3.5.0"," **/"," //summary: {},",""," /**"," HTML content of an optional `<caption>` element to appear above the table."," Leave this config unset or set to a falsy value to remove the caption.",""," @attribute caption"," @type HTML"," @default '' (empty string)"," @since 3.5.0"," **/"," //caption: {},",""," /**"," Deprecated as of 3.5.0. Passes through to the `data` attribute.",""," WARNING: `get('recordset')` will NOT return a Recordset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute recordset"," @type {Object[]|Recordset}"," @deprecated Use the `data` attribute"," @since 3.5.0"," **/"," recordset: {"," setter: '_setRecordset',"," getter: '_getRecordset',"," lazyAdd: false"," },",""," /**"," Deprecated as of 3.5.0. Passes through to the `columns` attribute.",""," WARNING: `get('columnset')` will NOT return a Columnset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute columnset"," @type {Object[]}"," @deprecated Use the `columns` attribute"," @since 3.5.0"," **/"," columnset: {"," setter: '_setColumnset',"," getter: '_getColumnset',"," lazyAdd: false"," }","};","","Y.mix(Table.prototype, {"," // -- Instance properties -------------------------------------------------"," /**"," The ModelList that manages the table's data.",""," @property data"," @type {ModelList}"," @default undefined (initially unset)"," @since 3.5.0"," **/"," //data: null,",""," // -- Public methods ------------------------------------------------------",""," /**"," Gets the column configuration object for the given key, name, or index. For"," nested columns, `name` can be an array of indexes, each identifying the index"," of that column in the respective parent's \"children\" array.",""," If you pass a column object, it will be returned.",""," For columns with keys, you can also fetch the column with"," `instance.get('columns.foo')`.",""," @method getColumn"," @param {String|Number|Number[]} name Key, \"name\", index, or index array to"," identify the column"," @return {Object} the column configuration object"," @since 3.5.0"," **/"," getColumn: function (name) {"," var col, columns, i, len, cols;",""," if (isObject(name) && !isArray(name)) {"," // TODO: support getting a column from a DOM node - this will cross"," // the line into the View logic, so it should be relayed",""," // Assume an object passed in is already a column def"," col = name;"," } else {"," col = this.get('columns.' + name);"," }",""," if (col) {"," return col;"," }",""," columns = this.get('columns');",""," if (isNumber(name) || isArray(name)) {"," name = toArray(name);"," cols = columns;",""," for (i = 0, len = name.length - 1; cols && i < len; ++i) {"," cols = cols[name[i]] && cols[name[i]].children;"," }",""," return (cols && cols[name[i]]) || null;"," }",""," return null;"," },",""," /**"," Returns the Model associated to the record `id`, `clientId`, or index (not"," row index). If none of those yield a Model from the `data` ModelList, the"," arguments will be passed to the `view` instance's `getRecord` method"," if it has one.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or"," identifier for a row or child element"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var record = this.data.getById(seed) || this.data.getByClientId(seed);",""," if (!record) {"," if (isNumber(seed)) {"," record = this.data.item(seed);"," }"," "," // TODO: this should be split out to base somehow"," if (!record && this.view && this.view.getRecord) {"," record = this.view.getRecord.apply(this.view, arguments);"," }"," }",""," return record || null;"," },",""," // -- Protected and private properties and methods ------------------------",""," /**"," This tells `Y.Base` that it should create ad-hoc attributes for config"," properties passed to DataTable's constructor. This is useful for setting"," configurations on the DataTable that are intended for the rendering View(s).",""," @property _allowAdHocAttrs"," @type Boolean"," @default true"," @protected"," @since 3.6.0"," **/"," _allowAdHocAttrs: true,",""," /**"," A map of column key to column configuration objects parsed from the"," `columns` attribute.",""," @property _columnMap"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_columnMap: null,",""," /**"," The Node instance of the table containing the data rows. This is set when"," the table is rendered. It may also be set by progressive enhancement,"," though this extension does not provide the logic to parse from source.",""," @property _tableNode"," @type {Node}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_tableNode: null,",""," /**"," Updates the `_columnMap` property in response to changes in the `columns`"," attribute.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," _afterColumnsChange: function (e) {"," this._setColumnMap(e.newVal);"," },",""," /**"," Updates the `modelList` attributes of the rendered views in response to the"," `data` attribute being assigned a new ModelList.",""," @method _afterDataChange"," @param {EventFacade} e the `dataChange` event"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," var modelList = e.newVal;",""," this.data = e.newVal;",""," if (!this.get('columns') && modelList.size()) {"," // TODO: this will cause a re-render twice because the Views are"," // subscribed to columnsChange"," this._initColumns();"," }"," },",""," /**"," Assigns to the new recordType as the model for the data ModelList",""," @method _afterRecordTypeChange"," @param {EventFacade} e recordTypeChange event"," @protected"," @since 3.6.0"," **/"," _afterRecordTypeChange: function (e) {"," var data = this.data.toJSON();",""," this.data.model = e.newVal;",""," this.data.reset(data);",""," if (!this.get('columns') && data) {"," if (data.length) {"," this._initColumns();"," } else {"," this.set('columns', keys(e.newVal.ATTRS));"," }"," }"," },",""," /**"," Creates a Model subclass from an array of attribute names or an object of"," attribute definitions. This is used to generate a class suitable to"," represent the data passed to the `data` attribute if no `recordType` is"," set.",""," @method _createRecordClass"," @param {String[]|Object} attrs Names assigned to the Model subclass's"," `ATTRS` or its entire `ATTRS` definition object"," @return {Model}"," @protected"," @since 3.5.0"," **/"," _createRecordClass: function (attrs) {"," var ATTRS, i, len;",""," if (isArray(attrs)) {"," ATTRS = {};",""," for (i = 0, len = attrs.length; i < len; ++i) {"," ATTRS[attrs[i]] = {};"," }"," } else if (isObject(attrs)) {"," ATTRS = attrs;"," }",""," return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });"," },",""," /**"," Tears down the instance.",""," @method destructor"," @protected"," @since 3.6.0"," **/"," destructor: function () {"," new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();"," },",""," /**"," The getter for the `columns` attribute. Returns the array of column"," configuration objects if `instance.get('columns')` is called, or the"," specific column object if `instance.get('columns.columnKey')` is called.",""," @method _getColumns"," @param {Object[]} columns The full array of column objects"," @param {String} name The attribute name requested"," (e.g. 'columns' or 'columns.foo');"," @protected"," @since 3.5.0"," **/"," _getColumns: function (columns, name) {"," // Workaround for an attribute oddity (ticket #2529254)"," // getter is expected to return an object if get('columns.foo') is called."," // Note 'columns.' is 8 characters"," return name.length > 8 ? this._columnMap : columns;"," },",""," /**"," Relays the `get()` request for the deprecated `columnset` attribute to the"," `columns` attribute.",""," THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will"," expect a Columnset instance returned from `get('columnset')`.",""," @method _getColumnset"," @param {Object} ignored The current value stored in the `columnset` state"," @param {String} name The attribute name requested"," (e.g. 'columnset' or 'columnset.foo');"," @deprecated This will be removed with the `columnset` attribute in a future"," version."," @protected"," @since 3.5.0"," **/"," _getColumnset: function (_, name) {"," return this.get(name.replace(/^columnset/, 'columns'));"," },",""," /**"," Returns the Model class of the instance's `data` attribute ModelList. If"," not set, returns the explicitly configured value.",""," @method _getRecordType"," @param {Model} val The currently configured value"," @return {Model}"," **/"," _getRecordType: function (val) {"," // Prefer the value stored in the attribute because the attribute"," // change event defaultFn sets e.newVal = this.get('recordType')"," // before notifying the after() subs. But if this getter returns"," // this.data.model, then after() subs would get e.newVal === previous"," // model before _afterRecordTypeChange can set"," // this.data.model = e.newVal"," return val || (this.data && this.data.model);"," },",""," /**"," Initializes the `_columnMap` property from the configured `columns`"," attribute. If `columns` is not set, but there are records in the `data`"," ModelList, use"," `ATTRS` of that class.",""," @method _initColumns"," @protected"," @since 3.5.0"," **/"," _initColumns: function () {"," var columns = this.get('columns') || [],"," item;"," "," // Default column definition from the configured recordType"," if (!columns.length && this.data.size()) {"," // TODO: merge superclass attributes up to Model?"," item = this.data.item(0);",""," if (item.toJSON) {"," item = item.toJSON();"," }",""," this.set('columns', keys(item));"," }",""," this._setColumnMap(columns);"," },",""," /**"," Sets up the change event subscriptions to maintain internal state.",""," @method _initCoreEvents"," @protected"," @since 3.6.0"," **/"," _initCoreEvents: function () {"," this._eventHandles.coreAttrChanges = this.after({"," columnsChange : Y.bind('_afterColumnsChange', this),"," recordTypeChange: Y.bind('_afterRecordTypeChange', this),"," dataChange : Y.bind('_afterDataChange', this)"," });"," },",""," /**"," Defaults the `data` attribute to an empty ModelList if not set during"," construction. Uses the configured `recordType` for the ModelList's `model`"," proeprty if set.",""," @method _initData"," @protected"," @return {ModelList}"," @since 3.6.0"," **/"," _initData: function () {"," var recordType = this.get('recordType'),"," // TODO: LazyModelList if recordType doesn't have complex ATTRS"," modelList = new Y.ModelList();",""," if (recordType) {"," modelList.model = recordType;"," }",""," return modelList;"," },",""," /**"," Initializes the instance's `data` property from the value of the `data`"," attribute. If the attribute value is a ModelList, it is assigned directly"," to `this.data`. If it is an array, a ModelList is created, its `model`"," property is set to the configured `recordType` class, and it is seeded with"," the array data. This ModelList is then assigned to `this.data`.",""," @method _initDataProperty"," @param {Array|ModelList|ArrayList} data Collection of data to populate the"," DataTable"," @protected"," @since 3.6.0"," **/"," _initDataProperty: function (data) {"," var recordType;",""," if (!this.data) {"," recordType = this.get('recordType');",""," if (data && data.each && data.toJSON) {"," this.data = data;",""," if (recordType) {"," this.data.model = recordType;"," }"," } else {"," // TODO: customize the ModelList or read the ModelList class"," // from a configuration option?"," this.data = new Y.ModelList();"," "," if (recordType) {"," this.data.model = recordType;"," }"," }",""," // TODO: Replace this with an event relay for specific events."," // Using bubbling causes subscription conflicts with the models'"," // aggregated change event and 'change' events from DOM elements"," // inside the table (via Widget UI event)."," this.data.addTarget(this);"," }"," },",""," /**"," Initializes the columns, `recordType` and data ModelList.",""," @method initializer"," @param {Object} config Configuration object passed to constructor"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," var data = config.data,"," columns = config.columns,"," recordType;",""," // Referencing config.data to allow _setData to be more stringent"," // about its behavior"," this._initDataProperty(data);",""," // Default columns from recordType ATTRS if recordType is supplied at"," // construction. If no recordType is supplied, but the data is"," // supplied as a non-empty array, use the keys of the first item"," // as the columns."," if (!columns) {"," recordType = (config.recordType || config.data === this.data) &&"," this.get('recordType');",""," if (recordType) {"," columns = keys(recordType.ATTRS);"," } else if (isArray(data) && data.length) {"," columns = keys(data[0]);"," }",""," if (columns) {"," this.set('columns', columns);"," }"," }",""," this._initColumns();",""," this._eventHandles = {};",""," this._initCoreEvents();"," },",""," /**"," Iterates the array of column configurations to capture all columns with a"," `key` property. An map is built with column keys as the property name and"," the corresponding column object as the associated value. This map is then"," assigned to the instance's `_columnMap` property.",""," @method _setColumnMap"," @param {Object[]|String[]} columns The array of column config objects"," @protected"," @since 3.6.0"," **/"," _setColumnMap: function (columns) {"," var map = {};"," "," function process(cols) {"," var i, len, col, key;",""," for (i = 0, len = cols.length; i < len; ++i) {"," col = cols[i];"," key = col.key;",""," // First in wins for multiple columns with the same key"," // because the first call to genId (in _setColumns) will"," // return the same key, which will then be overwritten by the"," // subsequent same-keyed column. So table.getColumn(key) would"," // return the last same-keyed column."," if (key && !map[key]) {"," map[key] = col;"," }",""," //TODO: named columns can conflict with keyed columns"," map[col._id] = col;",""," if (col.children) {"," process(col.children);"," }"," }"," }",""," process(columns);",""," this._columnMap = map;"," },",""," /**"," Translates string columns into objects with that string as the value of its"," `key` property.",""," All columns are assigned a `_yuid` stamp and `_id` property corresponding"," to the column's configured `name` or `key` property with any spaces"," replaced with dashes. If the same `name` or `key` appears in multiple"," columns, subsequent appearances will have their `_id` appended with an"," incrementing number (e.g. if column \"foo\" is included in the `columns`"," attribute twice, the first will get `_id` of \"foo\", and the second an `_id`"," of \"foo1\"). Columns that are children of other columns will have the"," `_parent` property added, assigned the column object to which they belong.",""," @method _setColumns"," @param {null|Object[]|String[]} val Array of config objects or strings"," @return {null|Object[]}"," @protected"," **/"," _setColumns: function (val) {"," var keys = {},"," known = [],"," knownCopies = [],"," arrayIndex = Y.Array.indexOf;"," "," function copyObj(o) {"," var copy = {},"," key, val, i;",""," known.push(o);"," knownCopies.push(copy);",""," for (key in o) {"," if (o.hasOwnProperty(key)) {"," val = o[key];",""," if (isArray(val)) {"," copy[key] = val.slice();"," } else if (isObject(val, true)) {"," i = arrayIndex(val, known);",""," copy[key] = i === -1 ? copyObj(val) : knownCopies[i];"," } else {"," copy[key] = o[key];"," }"," }"," }",""," return copy;"," }",""," function genId(name) {"," // Sanitize the name for use in generated CSS classes."," // TODO: is there more to do for other uses of _id?"," name = name.replace(/\\s+/, '-');",""," if (keys[name]) {"," name += (keys[name]++);"," } else {"," keys[name] = 1;"," }",""," return name;"," }",""," function process(cols, parent) {"," var columns = [],"," i, len, col, yuid;",""," for (i = 0, len = cols.length; i < len; ++i) {"," columns[i] = // chained assignment"," col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);",""," yuid = Y.stamp(col);",""," // For backward compatibility"," if (!col.id) {"," // Implementers can shoot themselves in the foot by setting"," // this config property to a non-unique value"," col.id = yuid;"," }"," if (col.field) {"," // Field is now known as \"name\" to avoid confusion with data"," // fields or schema.resultFields"," col.name = col.field;"," }",""," if (parent) {"," col._parent = parent;"," } else {"," delete col._parent;"," }",""," // Unique id based on the column's configured name or key,"," // falling back to the yuid. Duplicates will have a counter"," // added to the end."," col._id = genId(col.name || col.key || col.id);",""," if (isArray(col.children)) {"," col.children = process(col.children, col);"," }"," }",""," return columns;"," }",""," return val && process(val);"," },",""," /**"," Relays attribute assignments of the deprecated `columnset` attribute to the"," `columns` attribute. If a Columnset is object is passed, its basic object"," structure is mined.",""," @method _setColumnset"," @param {Array|Columnset} val The columnset value to relay"," @deprecated This will be removed with the deprecated `columnset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setColumnset: function (val) {"," this.set('columns', val);",""," return isArray(val) ? val : INVALID;"," },",""," /**"," Accepts an object with `each` and `getAttrs` (preferably a ModelList or"," subclass) or an array of data objects. If an array is passes, it will"," create a ModelList to wrap the data. In doing so, it will set the created"," ModelList's `model` property to the class in the `recordType` attribute,"," which will be defaulted if not yet set.",""," If the `data` property is already set with a ModelList, passing an array as"," the value will call the ModelList's `reset()` method with that array rather"," than replacing the stored ModelList wholesale.",""," Any non-ModelList-ish and non-array value is invalid.",""," @method _setData"," @protected"," @since 3.5.0"," **/"," _setData: function (val) {"," if (val === null) {"," val = [];"," }",""," if (isArray(val)) {"," this._initDataProperty();",""," // silent to prevent subscribers to both reset and dataChange"," // from reacting to the change twice."," // TODO: would it be better to return INVALID to silence the"," // dataChange event, or even allow both events?"," this.data.reset(val, { silent: true });",""," // Return the instance ModelList to avoid storing unprocessed"," // data in the state and their vivified Model representations in"," // the instance's data property. Decreases memory consumption."," val = this.data;"," } else if (!val || !val.each || !val.toJSON) {"," // ModelList/ArrayList duck typing"," val = INVALID;"," }",""," return val;"," },",""," /**"," Relays the value assigned to the deprecated `recordset` attribute to the"," `data` attribute. If a Recordset instance is passed, the raw object data"," will be culled from it.",""," @method _setRecordset"," @param {Object[]|Recordset} val The recordset value to relay"," @deprecated This will be removed with the deprecated `recordset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setRecordset: function (val) {"," var data;",""," if (val && Y.Recordset && val instanceof Y.Recordset) {"," data = [];"," val.each(function (record) {"," data.push(record.get('data'));"," });"," val = data;"," }",""," this.set('data', val);",""," return val;"," },",""," /**"," Accepts a Base subclass (preferably a Model subclass). Alternately, it will"," generate a custom Model subclass from an array of attribute names or an"," object defining attributes and their respective configurations (it is"," assigned as the `ATTRS` of the new class).",""," Any other value is invalid.",""," @method _setRecordType"," @param {Function|String[]|Object} val The Model subclass, array of"," attribute names, or the `ATTRS` definition for a custom model"," subclass"," @return {Function} A Base/Model subclass"," @protected"," @since 3.5.0"," **/"," _setRecordType: function (val) {"," var modelClass;",""," // Duck type based on known/likely consumed APIs"," if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {"," modelClass = val;"," } else if (isObject(val)) {"," modelClass = this._createRecordClass(val);"," }",""," return modelClass || INVALID;"," }","","});","","","}, '@VERSION@', {\"requires\": [\"escape\", \"model-list\", \"node-event-delegate\"]});","","}());"]}; } var __cov_adU3eEuYYFqBLZ6_IZplXQ = __coverage__['build/datatable-core/datatable-core.js']; __cov_adU3eEuYYFqBLZ6_IZplXQ.s['1']++;YUI.add('datatable-core',function(Y,NAME){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['1']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['2']++;var INVALID=Y.Attribute.INVALID_VALUE,Lang=Y.Lang,isFunction=Lang.isFunction,isObject=Lang.isObject,isArray=Lang.isArray,isString=Lang.isString,isNumber=Lang.isNumber,toArray=Y.Array,keys=Y.Object.keys,Table;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['3']++;Table=Y.namespace('DataTable').Core=function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['2']++;};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['4']++;Table.ATTRS={columns:{validator:isArray,setter:'_setColumns',getter:'_getColumns'},recordType:{getter:'_getRecordType',setter:'_setRecordType'},data:{valueFn:'_initData',setter:'_setData',lazyAdd:false},recordset:{setter:'_setRecordset',getter:'_getRecordset',lazyAdd:false},columnset:{setter:'_setColumnset',getter:'_getColumnset',lazyAdd:false}};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['5']++;Y.mix(Table.prototype,{getColumn:function(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['3']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['6']++;var col,columns,i,len,cols;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['7']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][0]++,isObject(name))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][1]++,!isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['8']++;col=name;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['9']++;col=this.get('columns.'+name);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['10']++;if(col){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['11']++;return col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['12']++;columns=this.get('columns');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['13']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][0]++,isNumber(name))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][1]++,isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['14']++;name=toArray(name);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['15']++;cols=columns;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['16']++;for(i=0,len=name.length-1;(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][1]++,i<len);++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['17']++;cols=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][0]++,cols[name[i]])&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][1]++,cols[name[i]].children);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['18']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][1]++,cols[name[i]])||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][2]++,null);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['19']++;return null;},getRecord:function(seed){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['4']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['20']++;var record=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][0]++,this.data.getById(seed))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][1]++,this.data.getByClientId(seed));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['21']++;if(!record){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['22']++;if(isNumber(seed)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['23']++;record=this.data.item(seed);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['24']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][0]++,!record)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][1]++,this.view)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][2]++,this.view.getRecord)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['25']++;record=this.view.getRecord.apply(this.view,arguments);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['26']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][0]++,record)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][1]++,null);},_allowAdHocAttrs:true,_afterColumnsChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['5']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['27']++;this._setColumnMap(e.newVal);},_afterDataChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['6']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['28']++;var modelList=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['29']++;this.data=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['30']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][1]++,modelList.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['31']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][1]++;}},_afterRecordTypeChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['7']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['32']++;var data=this.data.toJSON();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['33']++;this.data.model=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['34']++;this.data.reset(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['35']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][1]++,data)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['36']++;if(data.length){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['37']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['38']++;this.set('columns',keys(e.newVal.ATTRS));}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][1]++;}},_createRecordClass:function(attrs){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['8']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['39']++;var ATTRS,i,len;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['40']++;if(isArray(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['41']++;ATTRS={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['42']++;for(i=0,len=attrs.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['43']++;ATTRS[attrs[i]]={};}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['44']++;if(isObject(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['45']++;ATTRS=attrs;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['46']++;return Y.Base.create('record',Y.Model,[],null,{ATTRS:ATTRS});},destructor:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['9']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['47']++;new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();},_getColumns:function(columns,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['10']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['48']++;return name.length>8?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][0]++,this._columnMap):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][1]++,columns);},_getColumnset:function(_,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['11']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['49']++;return this.get(name.replace(/^columnset/,'columns'));},_getRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['12']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['50']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][0]++,val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][1]++,this.data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][2]++,this.data.model);},_initColumns:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['13']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['51']++;var columns=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][0]++,this.get('columns'))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][1]++,[]),item;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['52']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][0]++,!columns.length)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][1]++,this.data.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['53']++;item=this.data.item(0);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['54']++;if(item.toJSON){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['55']++;item=item.toJSON();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['56']++;this.set('columns',keys(item));}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['57']++;this._setColumnMap(columns);},_initCoreEvents:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['14']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['58']++;this._eventHandles.coreAttrChanges=this.after({columnsChange:Y.bind('_afterColumnsChange',this),recordTypeChange:Y.bind('_afterRecordTypeChange',this),dataChange:Y.bind('_afterDataChange',this)});},_initData:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['15']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['59']++;var recordType=this.get('recordType'),modelList=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['60']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['61']++;modelList.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['62']++;return modelList;},_initDataProperty:function(data){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['16']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['63']++;var recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['64']++;if(!this.data){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['65']++;recordType=this.get('recordType');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['66']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][0]++,data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][1]++,data.each)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][2]++,data.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['67']++;this.data=data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['68']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['69']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['70']++;this.data=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['71']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['72']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['73']++;this.data.addTarget(this);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][1]++;}},initializer:function(config){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['17']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['74']++;var data=config.data,columns=config.columns,recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['75']++;this._initDataProperty(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['76']++;if(!columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['77']++;recordType=((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][0]++,config.recordType)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][1]++,config.data===this.data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][2]++,this.get('recordType'));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['78']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['79']++;columns=keys(recordType.ATTRS);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['80']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][0]++,isArray(data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][1]++,data.length)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['81']++;columns=keys(data[0]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['82']++;if(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['83']++;this.set('columns',columns);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['84']++;this._initColumns();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['85']++;this._eventHandles={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['86']++;this._initCoreEvents();},_setColumnMap:function(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['18']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['87']++;var map={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['88']++;function process(cols){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['19']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['89']++;var i,len,col,key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['90']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['91']++;col=cols[i];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['92']++;key=col.key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['93']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][0]++,key)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][1]++,!map[key])){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['94']++;map[key]=col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['95']++;map[col._id]=col;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['96']++;if(col.children){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['97']++;process(col.children);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][1]++;}}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['98']++;process(columns);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['99']++;this._columnMap=map;},_setColumns:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['20']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['100']++;var keys={},known=[],knownCopies=[],arrayIndex=Y.Array.indexOf;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['101']++;function copyObj(o){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['21']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['102']++;var copy={},key,val,i;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['103']++;known.push(o);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['104']++;knownCopies.push(copy);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['105']++;for(key in o){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['106']++;if(o.hasOwnProperty(key)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['107']++;val=o[key];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['108']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['109']++;copy[key]=val.slice();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['110']++;if(isObject(val,true)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['111']++;i=arrayIndex(val,known);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['112']++;copy[key]=i===-1?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][0]++,copyObj(val)):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][1]++,knownCopies[i]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['113']++;copy[key]=o[key];}}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['114']++;return copy;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['115']++;function genId(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['22']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['116']++;name=name.replace(/\s+/,'-');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['117']++;if(keys[name]){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['118']++;name+=keys[name]++;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['119']++;keys[name]=1;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['120']++;return name;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['121']++;function process(cols,parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['23']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['122']++;var columns=[],i,len,col,yuid;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['123']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['124']++;columns[i]=col=isString(cols[i])?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][0]++,{key:cols[i]}):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][1]++,copyObj(cols[i]));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['125']++;yuid=Y.stamp(col);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['126']++;if(!col.id){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['127']++;col.id=yuid;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['128']++;if(col.field){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['129']++;col.name=col.field;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['130']++;if(parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['131']++;col._parent=parent;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['132']++;delete col._parent;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['133']++;col._id=genId((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][0]++,col.name)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][1]++,col.key)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][2]++,col.id));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['134']++;if(isArray(col.children)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['135']++;col.children=process(col.children,col);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['136']++;return columns;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['137']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][1]++,process(val));},_setColumnset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['24']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['138']++;this.set('columns',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['139']++;return isArray(val)?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][0]++,val):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][1]++,INVALID);},_setData:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['25']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['140']++;if(val===null){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['141']++;val=[];}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['142']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['143']++;this._initDataProperty();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['144']++;this.data.reset(val,{silent:true});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['145']++;val=this.data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['146']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][0]++,!val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][1]++,!val.each)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][2]++,!val.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['147']++;val=INVALID;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['148']++;return val;},_setRecordset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['26']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['149']++;var data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['150']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][1]++,Y.Recordset)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][2]++,val instanceof Y.Recordset)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['151']++;data=[];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['152']++;val.each(function(record){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['27']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['153']++;data.push(record.get('data'));});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['154']++;val=data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['155']++;this.set('data',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['156']++;return val;},_setRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['28']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['157']++;var modelClass;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['158']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][0]++,isFunction(val))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][1]++,val.prototype.toJSON)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][2]++,val.prototype.setAttrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['159']++;modelClass=val;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['160']++;if(isObject(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['161']++;modelClass=this._createRecordClass(val);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['162']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][0]++,modelClass)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][1]++,INVALID);}});},'@VERSION@',{'requires':['escape','model-list','node-event-delegate']});
src/components/DictList/Groups.js
GuramDuka/reorders
//------------------------------------------------------------------------------ import React, { Component } from 'react'; import connect from 'react-redux-connect'; import * as Sui from 'semantic-ui-react'; import disp, { nullLink } from '../../store'; //------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ class Groups extends Component { static mapStateToProps(state, ownProps) { return state.mapIn(ownProps.path); } static mapDispatchToProps(dispatch, ownProps) { const { path } = ownProps; return { toggleGroups : e => disp(state => state.toggleIn(path, 'expanded')) }; } static connectOptions = { withRef: true }; switchGroup = e => { const opt = { name: e.currentTarget.attributes.name.value, link: e.currentTarget.attributes.link.value }; const obj = this; const { listPath } = obj.props; disp(state => state = state.setIn([...listPath, 'view'], 'parent', opt.link, 2) .updateIn(listPath, 'breadcrumb', a => { const i = a.findIndex(v => v.link === opt.link); if( i < 0 ) a.push(opt); else a = a.slice(0, i + 1); return a; }, 0) ); }; clickBackward = e => { const obj = this; const { listPath } = obj.props; disp(state => { const link = state.getIn(listPath, 'breadcrumb').slice(-2).shift().link; return state.setIn([...listPath, 'view'], 'parent', link, 2) .updateIn(listPath, 'breadcrumb', v => { v.pop(); return v; }, 0); }); }; render() { if( process.env.NODE_ENV === 'development' ) console.log('render Groups'); const { props } = this; const { parent, expanded, toggleGroups, data } = props; const list = expanded ? data.map(grp => <Sui.Button style={{marginBottom:1}} compact size="tiny" basic color="blue" key={grp.Ссылка} link={grp.Ссылка} name={grp.Наименование} content={grp.Наименование} onClick={this.switchGroup} />) : null; const switcher = data.length === 0 ? null : expanded ? <Sui.Button compact primary size="tiny" onClick={toggleGroups} icon="compress" /> : <Sui.Button compact primary size="tiny" content={'Группы ' + data.length} onClick={toggleGroups} icon="expand" />; const breadcrumb = <Sui.Breadcrumb style={{padding: 0, margin: 0}}>{parent === nullLink ? null : <Sui.Button compact size="tiny" primary icon="backward" onClick={this.clickBackward} style={{marginBottom:1}} />} {props.breadcrumb.map((v, i, a) => [ <Sui.Breadcrumb.Section key={i*a.length+1} style={{padding: 0, margin: 0}}> <Sui.Button compact basic size="tiny" primary={i + 1 !== a.length} icon onClick={i + 1 !== a.length ? this.switchGroup : null} link={v.link} name={v.name}> {i === 0 ? <Sui.Icon name="home" /> : v.name} </Sui.Button> </Sui.Breadcrumb.Section>, i + 1 === a.length ? null : <Sui.Breadcrumb.Divider key={i*a.length+2} icon="right chevron" />])} {switcher} {list} </Sui.Breadcrumb>; return ( <Sui.Segment style={{padding: 0, margin: 0}}> {breadcrumb} </Sui.Segment>); } } //------------------------------------------------------------------------------ export default connect(Groups); //------------------------------------------------------------------------------
anubis/ui/components/scratchpad/ToolbarComponent.js
KawashiroNitori/Anubis
import React from 'react'; import classNames from 'classnames'; export default function ToolbarComponent(props) { const { className, children, ...rest, } = props; const cn = classNames(className, 'scratchpad__toolbar flex-row flex-cross-center'); return ( <div {...rest} className={cn}>{children}</div> ); } ToolbarComponent.propTypes = { className: React.PropTypes.string, children: React.PropTypes.node, }; export function ToolbarButtonComponent(props) { const { activated, disabled, onClick, className, children, ...rest, } = props; const cn = classNames(className, 'scratchpad__toolbar__item scratchpad__toolbar__button', { activated, disabled, enabled: !disabled, }); return ( <button {...rest} tabIndex="-1" className={cn} onClick={() => !disabled && onClick && onClick()} > <div>{children}</div> </button> ); } ToolbarButtonComponent.propTypes = { activated: React.PropTypes.bool, disabled: React.PropTypes.bool, onClick: React.PropTypes.func, className: React.PropTypes.string, children: React.PropTypes.node, }; ToolbarButtonComponent.defaultProps = { activated: false, disabled: false, }; export function ToolbarSplitComponent(props) { const { className, ...rest, } = props; const cn = classNames(className, 'scratchpad__toolbar__item scratchpad__toolbar__split'); return ( <div {...rest} className={cn} /> ); } ToolbarSplitComponent.propTypes = { className: React.PropTypes.string, }; export function ToolbarItemComponent(props) { const { className, children, ...rest, } = props; const cn = classNames(className, 'scratchpad__toolbar__item'); return ( <div {...rest} className={cn}>{children}</div> ); } ToolbarItemComponent.propTypes = { className: React.PropTypes.string, children: React.PropTypes.node, };
src/pages/Home/Home.js
cdtinney/cdtinney.github.io
import React from 'react'; import PropTypes from 'prop-types'; import DefaultLayout from '../../layouts/DefaultLayout'; import Brand from '../../components/Brand'; import ContactCard from '../../components/ContactCard'; import PageLinks from '../../components/PageLinks'; import classes from './Home.module.css'; export default function Home({ data = {}, }) { const { allMarkdownRemark: { edges = [], } = {}, site: { siteMetadata: { title, } = {}, } = {}, } = data; const pageDescription = 'A personal website'; const pageLinks = [{ to: '/blog', name: 'blog', }, { to: '/projects', name: 'projects', }]; const aboutHtml = edges.length ? edges[0].node.html : null; return ( <DefaultLayout pageTitle={title} pageDescription={pageDescription} > <div className={classes.container}> <header> <Brand className={classes.brand} large /> <div // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: aboutHtml }} /> <PageLinks links={pageLinks} /> </header> <main className={classes.contactCard}> <ContactCard /> </main> </div> </DefaultLayout> ); } Home.propTypes = { data: PropTypes.shape({ allMarkdownRemark: PropTypes.shape({ edges: PropTypes.arrayOf(PropTypes.shape({ node: PropTypes.shape({ html: PropTypes.string.isRequired, }).isRequired, })).isRequired, }).isRequired, site: PropTypes.shape({ siteMetadata: PropTypes.shape({ title: PropTypes.string.isRequired, }).isRequired, }).isRequired, }).isRequired, };
src/Parser/Monk/Windwalker/Modules/Items/T21_4set.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import calculateEffectiveDamage from 'Parser/Core/calculateEffectiveDamage'; import ItemDamageDone from 'Main/ItemDamageDone'; class T21_4set extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; on_initialized() { this.active = this.combatants.selected.hasBuff(SPELLS.WW_TIER21_4PC.id); } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.BLACKOUT_KICK.id && this.combatants.selected.hasBuff(SPELLS.COMBO_BREAKER_BUFF.id, event.timestamp, 1000, 0)) { this.damage += calculateEffectiveDamage(event, 1.75); } } on_byPlayerPet_damage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.BLACKOUT_KICK.id && this.combatants.selected.hasBuff(SPELLS.COMBO_BREAKER_BUFF.id, event.timestamp, 1000, 0)) { this.damage += calculateEffectiveDamage(event, 1.75); } } item() { return { id: `spell-${SPELLS.WW_TIER21_4PC.id}`, icon: <SpellIcon id={SPELLS.WW_TIER21_4PC.id} />, title: <SpellLink id={SPELLS.WW_TIER21_4PC.id} />, result: <ItemDamageDone amount={this.damage} />, }; } } export default T21_4set;
src/daypicker/DayPicker.js
buildo/react-semantic-datepicker
import React from 'react'; import t from 'tcomb'; import { props } from 'tcomb-react'; import View from 'react-flexview'; import { pure, skinnable } from '../utils'; import { Value, Mode, MomentDate } from '../utils/model'; import DayPickerTop from './DayPickerTop'; import DayPickerBody from './DayPickerBody'; @pure @skinnable() @props({ changeMonth: t.Function, visibleDate: MomentDate, date: t.maybe(Value), minDate: t.maybe(Value), maxDate: t.maybe(Value), onSelectDate: t.Function, onChangeMode: t.Function, mode: Mode, fixedMode: t.maybe(t.Boolean), prevIconClassName: t.String, nextIconClassName: t.String }) export default class DayPicker extends React.Component { getLocals({ date, visibleDate, onSelectDate, minDate, maxDate, changeMonth, onChangeMode, mode, fixedMode, prevIconClassName, nextIconClassName }) { return { dayPickerTopProps: { visibleDate, changeMonth, onChangeMode, fixedMode, prevIconClassName, nextIconClassName }, dayPickerBodyProps: { date, visibleDate, minDate, maxDate, onSelectDate, mode } }; } template({ dayPickerTopProps, dayPickerBodyProps }) { return ( <View column className='react-datepicker-container day'> <DayPickerTop {...dayPickerTopProps} /> <DayPickerBody {...dayPickerBodyProps} /> </View> ); } }
src/svg-icons/action/record-voice-over.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRecordVoiceOver = (props) => ( <SvgIcon {...props}> <circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/> </SvgIcon> ); ActionRecordVoiceOver = pure(ActionRecordVoiceOver); ActionRecordVoiceOver.displayName = 'ActionRecordVoiceOver'; ActionRecordVoiceOver.muiName = 'SvgIcon'; export default ActionRecordVoiceOver;
ajax/libs/angular.js/0.10.4/angular.js
nolanlawson/cdnjs
/** * @license AngularJS v0.10.4 * (c) 2010-2011 AngularJS http://angularjs.org * License: MIT */ 'use strict'; (function(window, document, undefined){ //////////////////////////////////// if (typeof document.getAttribute == $undefined) document.getAttribute = function() {}; /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){ return isString(string) ? string.toLowerCase() : string; }; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){ return isString(string) ? string.toUpperCase() : string; }; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32); }) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32); }) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) { return String.fromCharCode(code); } var _undefined = undefined, _null = null, $$scope = '$scope', $angular = 'angular', $array = 'array', $boolean = 'boolean', $console = 'console', $date = 'date', $length = 'length', $name = 'name', $noop = 'noop', $null = 'null', $number = 'number', $object = 'object', $string = 'string', $value = 'value', $selected = 'selected', $undefined = 'undefined', NOOP = 'noop', Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, error = window[$console] ? bind(window[$console], window[$console]['error'] || noop) : noop, /** @name angular */ angular = window[$angular] || (window[$angular] = {}), /** @name angular.markup */ angularTextMarkup = extensionMap(angular, 'markup'), /** @name angular.attrMarkup */ angularAttrMarkup = extensionMap(angular, 'attrMarkup'), /** @name angular.directive */ angularDirective = extensionMap(angular, 'directive'), /** @name angular.widget */ angularWidget = extensionMap(angular, 'widget', lowercase), /** @name angular.filter */ angularFilter = extensionMap(angular, 'filter'), /** @name angular.service */ angularInputType = extensionMap(angular, 'inputType', lowercase), /** @name angular.service */ angularService = extensionMap(angular, 'service'), angularCallbacks = extensionMap(angular, 'callbacks'), nodeName_, rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/, uid = ['0', '0', '0'], DATE_ISOSTRING_LN = 24; /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {function()} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) iterator.call(context, obj[key], key); } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj) for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} function valueFn(value) {return function() { return value; };} function extensionMap(angular, name, transform) { var extPoint; return angular[name] || (extPoint = angular[name] = function(name, fn, prop){ name = (transform || identity)(name); if (isDefined(fn)) { extPoint[name] = extend(fn, prop || {}); } return extPoint[name]; }); } /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){ return typeof value == $undefined; } /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){ return typeof value != $undefined; } /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){ return value!=null && typeof value == $object;} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){ return typeof value == $string;} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){ return typeof value == $number;} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return value instanceof Date; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return value instanceof Array; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){ return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isBoolean(value) { return typeof value == $boolean; } function isTextNode(node) { return nodeName_(node) == '#text'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } /** * HTML class which is the only class which can be used in ng:bind to inline HTML for security * reasons. * * @constructor * @param html raw (unsafe) html * @param {string=} option If set to 'usafe', get method will return raw (unsafe/unsanitized) html */ function HTML(html, option) { this.html = html; this.get = lowercase(option) == 'unsafe' ? valueFn(html) : function htmlSanitize() { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function isVisible(element) { var rect = element[0].getBoundingClientRect(), width = (rect.width || (rect.right||0 - rect.left||0)), height = (rect.height || (rect.bottom||0 - rect.top||0)); return width>0 && height>0; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @ngdoc function * @name angular.Object.size * @function * * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. * * @example * <doc:example> * <doc:source> * <script> * function SizeCtrl() { * this.fooStringLength = angular.Object.size('foo'); * } * </script> * <div ng:controller="SizeCtrl"> * Number of items in array: {{ [1,2].$size() }}<br/> * Number of items in object: {{ {a:1, b:2, c:3}.$size() }}<br/> * String length: {{fooStringLength}} * </div> * </doc:source> * <doc:scenario> * it('should print correct sizes for an array and an object', function() { * expect(binding('[1,2].$size()')).toBe('2'); * expect(binding('{a:1, b:2, c:3}.$size()')).toBe('3'); * expect(binding('fooStringLength')).toBe('3'); * }); * </doc:scenario> * </doc:example> */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return true; } return false; } function indexOf(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Alias for {@link angular.Object.copy} */ /** * @ngdoc function * @name angular.Object.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example * <doc:example> * <doc:source> <script> function Ctrl() { this.master = { salutation: 'Hello', name: 'world' }; this.copy = function() { this.form = angular.copy(this.master); } } </script> <div ng:controller="Ctrl"> Salutation: <input type="text" ng:model="master.salutation" ><br/> Name: <input type="text" ng:model="master.name"><br/> <button ng:click="copy()">copy</button> <hr/> The master object is <span ng:hide="master.$equals(form)">NOT</span> equal to the form object. <pre>master={{master}}</pre> <pre>form={{form}}</pre> </div> * </doc:source> * <doc:scenario> it('should print that initialy the form object is NOT equal to master', function() { expect(element('.doc-example-live input[ng\\:model="master.salutation"]').val()).toBe('Hello'); expect(element('.doc-example-live input[ng\\:model="master.name"]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); it('should make form and master equal when the copy button is clicked', function() { element('.doc-example-live button').click(); expect(element('.doc-example-live span').css('display')).toBe('none'); }); * </doc:scenario> * </doc:example> */ function copy(source, destination){ if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * @ngdoc function * @name angular.equals * @function * * @description * Alias for {@link angular.Object.equals} */ /** * @ngdoc function * @name angular.Object.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. * * @example * <doc:example> * <doc:source> <script> function Ctrl() { this.master = { salutation: 'Hello', name: 'world' }; this.greeting = angular.copy(this.master); } </script> <div ng:controller="Ctrl"> Salutation: <input type="text" ng:model="greeting.salutation"><br/> Name: <input type="text" ng:model="greeting.name"><br/> <hr/> The <code>greeting</code> object is <span ng:hide="greeting.$equals(master)">NOT</span> equal to <code>{salutation:'Hello', name:'world'}</code>. <pre>greeting={{greeting}}</pre> </div> * </doc:source> * <doc:scenario> it('should print that initialy greeting is equal to the hardcoded value object', function() { expect(element('.doc-example-live input[ng\\:model="greeting.salutation"]').val()).toBe('Hello'); expect(element('.doc-example-live input[ng\\:model="greeting.name"]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('none'); }); it('should say that the objects are not equal when the form is modified', function() { input('greeting.name').enter('kitty'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); * </doc:scenario> * </doc:example> */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2 && t1 == 'object') { if (o1 instanceof Array) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else { keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } return false; } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** @name angular.compile */ function compile(element) { return new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget) .compile(element); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name angular.directive.ng:autobind * @element script * * @TODO ng:autobind is not a directive!! it should be documented as bootstrap parameter in a * separate bootstrap section. * @TODO rename to ng:autobind to ng:autoboot * * @description * Technically, ng:autobind is not a directive; it is an Angular bootstrap parameter that can act * as a directive. It must exist in the script used to boot Angular and can be used only one time. * For details on bootstrapping Angular, see {@link guide/dev_guide.bootstrap Initializing Angular} * in the Angular Developer Guide. * * `ng:autobind` with no parameters tells Angular to compile and manage the whole page. * * `ng:autobind="[root element ID]"` tells Angular to compile and manage part of the document, * starting at "root element ID". * */ function angularInit(config, document){ var autobind = config.autobind; if (autobind) { var element = isString(autobind) ? document.getElementById(autobind) : document, scope = compile(element)(createScope()), $browser = scope.$service('$browser'); if (config.css) $browser.addCss(config.base_url + config.css); scope.$apply(); } } function angularJsConfig(document) { bindJQuery(); var scripts = document.getElementsByTagName("script"), config = {}, match; for(var j = 0; j < scripts.length; j++) { match = (scripts[j].src || "").match(rngScript); if (match) { config.base_url = match[1]; extend(config, parseKeyValue(match[6])); eachAttribute(jqLite(scripts[j]), function(value, name){ if (/^ng:/.exec(name)) { name = name.substring(3).replace(/-/g, '_'); value = value || true; config[name] = value; } }); } } return config; } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = jqLiteWrap; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { var error = new Error("Argument '" + (name||'?') + "' is " + (reason || "required")); throw error; } return arg; } function assertArgFn(arg, name) { assertArg(isFunction(arg), name, 'not a function, got ' + (typeof arg == 'object' ? arg.constructor.name : typeof arg)); return arg; } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '0.10.4', // all of these placeholder strings will be replaced by rake's major: 0, // compile task minor: 10, dot: 4, codeName: 'human-torch' }; var array = [].constructor; /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : null, []); return buf.join(''); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @param {boolean} [useNative=false] Use native JSON parser, if available. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json, useNative) { if (!isString(json)) return json; var obj; try { if (useNative && window.JSON && window.JSON.parse) { obj = JSON.parse(json); return transformDates(obj); } return parser(json, true).primary()(); } catch (e) { error("fromJson error: ", json, e); throw e; } // TODO make forEach optionally recursive and remove this function function transformDates(obj) { if (isString(obj) && obj.length === DATE_ISOSTRING_LN) { return angularString.toDate(obj); } else if (isArray(obj) || isObject(obj)) { forEach(obj, function(val, name) { obj[name] = transformDates(val); }); } return obj; } } angular.toJson = toJson; angular.fromJson = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angularString.quoteUnicode(obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angularString.quoteUnicode(obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isElement(obj)) { // TODO(misko): maybe in dev mode have a better error reporting? buf.push('DOM_ELEMENT'); } else if (isDate(obj)) { buf.push(angularString.quoteUnicode(angular.Date.toString(obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (k!='this' && k!='$parent' && k.substring(0,2) != '$$' && obj.hasOwnProperty(k) && obj[k] !== undefined) { keys.push(k); } } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (!isFunction(value)) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angularString.quote(key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } } /** * Template provides directions an how to bind to a given element. * It contains a list of init functions which need to be called to * bind to a new instance of elements. It also provides a list * of child paths which contain child templates */ function Template() { this.paths = []; this.children = []; this.linkFns = []; this.newScope = false; } Template.prototype = { link: function(element, scope) { var childScope = scope; if (this.newScope) { childScope = isFunction(this.newScope) ? scope.$new(this.newScope(scope)) : scope.$new(); element.data($$scope, childScope); } forEach(this.linkFns, function(fn) { try { childScope.$service.invoke(childScope, fn, [element]); } catch (e) { childScope.$service('$exceptionHandler')(e); } }); var i, childNodes = element[0].childNodes, children = this.children, paths = this.paths, length = paths.length; for (i = 0; i < length; i++) { // sometimes `element` can be modified by one of the linker functions in `this.linkFns` // and childNodes may be added or removed // TODO: element structure needs to be re-evaluated if new children added // if the childNode still exists if (childNodes[paths[i]]) children[i].link(jqLite(childNodes[paths[i]]), childScope); else delete paths[i]; // if child no longer available, delete path } }, addLinkFn:function(linkingFn) { if (linkingFn) { this.linkFns.push(linkingFn); } }, addChild: function(index, template) { if (template) { this.paths.push(index); this.children.push(template); } }, empty: function() { return this.linkFns.length === 0 && this.paths.length === 0; } }; /////////////////////////////////// //Compiler ////////////////////////////////// /** * @ngdoc function * @name angular.compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link angular.scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup}, * {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it * executes corresponding markup, attrMarkup, widget or directive template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link angular.widget.@ng:repeat repeater} many-times, in which case each call results in a view * that is a DOM clone of the original template. * <pre> // compile the entire window.document and give me the scope bound to this template. var rootScope = angular.compile(window.document)(); // compile a piece of html var rootScope2 = angular.compile('<div ng:click="clicked = true">click me</div>')(); // compile a piece of html and retain reference to both the dom and scope var template = angular.element('<div ng:click="clicked = true">click me</div>'), scope = angular.compile(template)(); // at this point template was transformed into a view </pre> * * * @param {string|DOMElement} element Element or HTML to compile into a template function. * @returns {function([scope][, cloneAttachFn])} a template function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link angular.scope Scope} to bind to. If none specified, then a new * root scope is created. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br/> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the template function returns the scope to which the element is bound to. It is either * the same scope as the one passed into the template function, or if none were provided it's the * newly create scope. * * It is important to understand that the returned scope is "linked" to the view DOM, but no linking * (instance) functions registered by {@link angular.directive directives} or * {@link angular.widget widgets} found in the template have been executed yet. This means that the * view is likely empty and doesn't contain any values that result from evaluation on the scope. To * bring the view to life, the scope needs to run through a $digest phase which typically is done by * Angular automatically, except for the case when an application is being * {@link guide/dev_guide.bootstrap.manual_bootstrap} manually bootstrapped, in which case the * $digest phase must be invoked by calling {@link angular.scope.$apply}. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var view = angular.element('<p>{{total}}</p>'), * scope = angular.compile(view)(); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var original = angular.element('<p>{{total}}</p>'), * scope = someParentScope.$new(), * clone; * * angular.compile(original)(scope, function(clonedElement, scope) { * clone = clonedElement; * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * Compiler Methods For Widgets and Directives: * * The following methods are available for use when you write your own widgets, directives, * and markup. (Recall that the compile function's this is a reference to the compiler.) * * `compile(element)` - returns linker - * Invoke a new instance of the compiler to compile a DOM element and return a linker function. * You can apply the linker function to the original element or a clone of the original element. * The linker function returns a scope. * * * `comment(commentText)` - returns element - Create a comment element. * * * `element(elementName)` - returns element - Create an element by name. * * * `text(text)` - returns element - Create a text element. * * * `descend([set])` - returns descend state (true or false). Get or set the current descend * state. If true the compiler will descend to children elements. * * * `directives([set])` - returns directive state (true or false). Get or set the current * directives processing state. The compiler will process directives only when directives set to * true. * * For information on how the compiler works, see the * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide. */ function Compiler(markup, attrMarkup, directives, widgets){ this.markup = markup; this.attrMarkup = attrMarkup; this.directives = directives; this.widgets = widgets; } Compiler.prototype = { compile: function(templateElement) { templateElement = jqLite(templateElement); var index = 0, template, parent = templateElement.parent(); if (templateElement.length > 1) { // https://github.com/angular/angular.js/issues/338 throw Error("Cannot compile multiple element roots: " + jqLite('<div>').append(templateElement.clone()).html()); } if (parent && parent[0]) { parent = parent[0]; for(var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i] == templateElement[0]) { index = i; } } } template = this.templatize(templateElement, index) || new Template(); return function(scope, cloneConnectFn){ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var element = cloneConnectFn ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!! : templateElement; scope = scope || createScope(); element.data($$scope, scope); scope.$element = element; (cloneConnectFn||noop)(element, scope); template.link(element, scope); return scope; }; }, templatize: function(element, elementIndex){ var self = this, widget, fn, directiveFns = self.directives, descend = true, directives = true, elementName = nodeName_(element), elementNamespace = elementName.indexOf(':') > 0 ? lowercase(elementName).replace(':', '-') : '', template, selfApi = { compile: bind(self, self.compile), descend: function(value){ if(isDefined(value)) descend = value; return descend;}, directives: function(value){ if(isDefined(value)) directives = value; return directives;}, scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;} }; element.addClass(elementNamespace); template = new Template(); eachAttribute(element, function(value, name){ if (!widget) { if ((widget = self.widgets('@' + name))) { element.addClass('ng-attr-widget'); widget = bind(selfApi, widget, value, element); } } }); if (!widget) { if ((widget = self.widgets(elementName))) { if (elementNamespace) element.addClass('ng-widget'); widget = bind(selfApi, widget, element); } } if (widget) { descend = false; directives = false; var parent = element.parent(); template.addLinkFn(widget.call(selfApi, element)); if (parent && parent[0]) { element = jqLite(parent[0].childNodes[elementIndex]); } } if (descend){ // process markup for text nodes only for(var i=0, child=element[0].childNodes; i<child.length; i++) { if (isTextNode(child[i])) { forEach(self.markup, function(markup){ if (i<child.length) { var textNode = jqLite(child[i]); markup.call(selfApi, textNode.text(), textNode, element); } }); } } } if (directives) { // Process attributes/directives eachAttribute(element, function(value, name){ forEach(self.attrMarkup, function(markup){ markup.call(selfApi, value, name, element); }); }); eachAttribute(element, function(value, name){ fn = directiveFns[name]; if (fn) { element.addClass('ng-directive'); template.addLinkFn((directiveFns[name]).call(selfApi, value, element)); } }); } // Process non text child nodes if (descend) { eachNode(element, function(child, i){ template.addChild(i, self.templatize(child, i)); }); } return template.empty() ? null : template; } }; function eachNode(element, fn){ var i, chldNodes = element[0].childNodes || [], chld; for (i = 0; i < chldNodes.length; i++) { if(!isTextNode(chld = chldNodes[i])) { fn(jqLite(chld), i); } } } function eachAttribute(element, fn){ var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {}; for (i = 0; i < attrs.length; i++) { attr = attrs[i]; name = attr.name; value = attr.value; if (msie && name == 'href') { value = decodeURIComponent(element[0].getAttribute(name, 2)); } attrValue[name] = value; } forEachSorted(attrValue, fn); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ function createScope(providers, instanceCache) { var scope = new Scope(); (scope.$service = createInjector(scope, providers, instanceCache)).eager(); return scope; } /** * @ngdoc function * @name angular.scope * * @description * A root scope can be created by calling {@link angular.scope angular.scope()}. Child scopes * are created using the {@link angular.scope.$new $new()} method. * (Most scopes are created automatically when compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> var scope = angular.scope(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { this.greeting = this.salutation + ' ' + this.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = angular.scope(); var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * # Dependency Injection * See {@link guide/dev_guide.di dependency injection}. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link angular.service}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this.$destructor = noop; this['this'] = this.$root = this; this.$$asyncQueue = []; this.$$listeners = {}; } /** * @ngdoc property * @name angular.scope.$id * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ /** * @ngdoc property * @name angular.scope.$service * @function * * @description * Provides reference to an instance of {@link angular.injector injector} which can be used to * retrieve {@link angular.service services}. In general the use of this api is discouraged, * in favor of proper {@link guide/dev_guide.di dependency injection}. * * @returns {function} {@link angular.injector injector} */ /** * @ngdoc property * @name angular.scope.$root * @returns {Scope} The root scope of the current scope hierarchy. */ /** * @ngdoc property * @name angular.scope.$parent * @returns {Scope} The parent scope of the current scope. */ Scope.prototype = { /** * @ngdoc function * @name angular.scope.$new * @function * * @description * Creates a new child {@link angular.scope scope}. The new scope can optionally behave as a * controller. The parent scope will propagate the {@link angular.scope.$digest $digest()} and * {@link angular.scope.$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link angular.scope.$destroy $destroy()}. * * {@link angular.scope.$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {function()=} Class Constructor function which the scope should be applied to the scope. * @param {...*} curryArguments Any additional arguments which are curried into the constructor. * See {@link guide/dev_guide.di dependency injection}. * @returns {Object} The newly created child scope. * */ $new: function(Class, curryArguments) { var Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. var child; Child.prototype = this; child = new Child(); child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$id = nextUid(); child.$$asyncQueue = []; child.$$phase = child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } // short circuit if we have no class if (Class) { // can't use forEach, we need speed! var ClassPrototype = Class.prototype; for(var key in ClassPrototype) { child[key] = bind(child, ClassPrototype[key]); } this.$service.invoke(child, Class, curryArguments); } return child; }, /** * @ngdoc function * @name angular.scope.$watch * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link angular.scope.$digest $digest()} and * should return the value which will be watched. (Since {@link angular.scope.$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link angular.scope.$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression' are not equal. The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 100 to prevent infinity loop deadlock. * * * If you want to be notified whenever {@link angular.scope.$digest $digest} is called, * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`, * can execute multiple times per {@link angular.scope.$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link angular.scope.$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(scope, newValue, oldValue)`: called with current `scope` an previous and * current values as parameters. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener) { var scope = this, get = compileToFn(watchExp, 'watch'), listenFn = compileToFn(listener || noop, 'listener'), array = scope.$$watchers, watcher = { fn: listenFn, last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run. get: get }; if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { angularArray.remove(array, watcher); }; }, /** * @ngdoc function * @name angular.scope.$digest * @function * * @description * Process all of the {@link angular.scope.$watch watchers} of the current scope and its children. * Because a {@link angular.scope.$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link angular.scope.$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100. * * Usually you don't call `$digest()` directly in * {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}. * Instead a call to {@link angular.scope.$apply $apply()} (typically from within a * {@link angular.directive directive}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link angular.scope.$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$digest('name', function(scope, newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue, length, dirty, ttl = 100, next, current, target = this; if (target.$$phase) { throw Error(target.$$phase + ' already in progress'); } do { dirty = false; current = target; do { current.$$phase = '$digest'; asyncQueue = current.$$asyncQueue; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { current.$service('$exceptionHandler')(e); } } if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) { dirty = true; watch.last = copy(value); watch.fn(current, value, last); } } catch (e) { current.$service('$exceptionHandler')(e); } } } current.$$phase = null; // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(!(ttl--)) { throw Error('100 $digest() iterations reached. Aborting!'); } } while (dirty); }, /** * @ngdoc function * @name angular.scope.$destroy * @function * * @description * Remove the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link angular.scope.$digest $digest()} will no longer propagate to the current * scope and its children. Removal also implies that the current scope is eligible for garbage * collection. * * The destructing scope emits an `$destroy` {@link angular.scope.$emit event}. * * The `$destroy()` is usually used by directives such as * {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop. * */ $destroy: function() { if (this.$root == this) return; // we can't remove the root node; this.$emit('$destroy'); var parent = this.$parent; if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; }, /** * @ngdoc function * @name angular.scope.$eval * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example <pre> var scope = angular.scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr) { var fn = isString(expr) ? expressionCompile(expr) : expr || noop; return fn(this); }, /** * @ngdoc function * @name angular.scope.$evalAsync * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link angular.scope.$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link angular.service.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name angular.scope.$apply * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link angular.service.$exceptionHandler exception handling}, * {@link angular.scope.$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/dev_guide.expressions expression} is executed using the * {@link angular.scope.$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link angular.service.$exceptionHandler $exceptionHandler} service. * 3. The {@link angular.scope.$watch watch} listeners are fired immediately after the expression * was executed using the {@link angular.scope.$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { return this.$eval(expr); } catch (e) { this.$service('$exceptionHandler')(e); } finally { this.$root.$digest(); } }, /** * @ngdoc function * @name angular.scope.$on * @function * * @description * Listen on events of a given type. See {@link angular.scope.$emit $emit} for discussion of * event life cycle. * * @param {string} name Event name to listen on. * @param {function(event)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. * * The event listener function format is: `function(event)`. The `event` object passed into the * listener has the following attributes * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - {Scope}: the current scope which is handling the event. * - `name` - {string}: Name of the event. * - `cancel` - {function=}: calling `cancel` function will cancel further event propagation * (available only for events that were `$emit`-ed). */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { angularArray.remove(namedListeners, listener); }; }, /** * @ngdoc function * @name angular.scope.$emit * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link angular.scope.$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link angular.scope.$on listeners} will be passed * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. */ $emit: function(name, args) { var empty = [], namedListeners, canceled = false, scope = this, event = { name: name, targetScope: scope, cancel: function() {canceled = true;} }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { try { namedListeners[i].apply(null, listenerArgs); if (canceled) return; } catch (e) { scope.$service('$exceptionHandler')(e); } } //traverse upwards scope = scope.$parent; } while (scope); }, /** * @ngdoc function * @name angular.scope.$broadcast * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link angular.scope.$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link angular.scope.$on listeners} will be passed * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target }, listenerArgs = concat([event], arguments, 1); //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; forEach(current.$$listeners[name], function(listener) { try { listener.apply(null, listenerArgs); } catch(e) { current.$service('$exceptionHandler')(e); } }); // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); } }; function compileToFn(exp, name) { var fn = isString(exp) ? expressionCompile(exp) : exp; assertArgFn(fn, name); return fn; } /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/dev_guide.di dependency injection}). * * Angular creates an injector automatically for the root scope and it is available as the * {@link angular.scope.$service $service} property. Creating an injector doesn't automatically * create all of the `$eager` {@link angular.service services}. You have to call `injector.eager()` * to initialize them. * * @param {Object=} [factoryScope={}] The `this` for the service factory function. * @param {Object.<string, function()>=} [factories=angular.service] Map of the service factory * functions. * @param {Object.<string, function()>=} [instanceCache={}] Place where instances of services are * saved for reuse. Can also be used to override services specified by `serviceFactory` * (useful in tests). * @returns {function()} Injector function: * * * `injector(serviceName)`: * * `serviceName` - `{string=}` - Name of the service to retrieve. * * The injector function also has these properties: * * * An `invoke` property which can be used to invoke methods with dependency-injected arguments. * `injector.invoke(self, fn, curryArgs)` * * `self` - The "`this`" to be used when invoking the function. * * `fn` - The function to be invoked. The function may have the `$inject` property that * lists the set of arguments which should be auto-injected. * (see {@link guide/dev_guide.di dependency injection}). * * `curryArgs(array)` - Optional array of arguments to pass to the function * invocation after the injection arguments (also known as curry arguments or currying). * * An `eager` property which is used to initialize the eager services. * `injector.eager()` */ function createInjector(factoryScope, factories, instanceCache) { factories = factories || angularService; instanceCache = instanceCache || {}; factoryScope = factoryScope || {}; injector.invoke = invoke; injector.eager = function() { forEach(factories, function(factory, name){ if (factory.$eager) injector(name); if (factory.$creation) throw new Error("Failed to register service '" + name + "': $creation property is unsupported. Use $eager:true or see release notes."); }); }; return injector; function injector(value){ if (!(value in instanceCache)) { var factory = factories[value]; if (!factory) throw Error("Unknown provider for '"+value+"'."); inferInjectionArgs(factory); instanceCache[value] = invoke(factoryScope, factory); } return instanceCache[value]; } function invoke(self, fn, args){ args = args || []; var injectNames = fn.$inject || []; var i = injectNames.length; while(i--) { args.unshift(injector(injectNames[i])); } return fn.apply(self, args); } } /** * THIS IS NOT PUBLIC DOC YET! * * @name angular.annotate * @function * * @description * Annotate the function with injection arguments. This is equivalent to setting the `$inject` * property as described in {@link guide.di dependency injection}. * * <pre> * var MyController = angular.annotate('$location', function($location){ ... }); * </pre> * * is the same as * * <pre> * var MyController = function($location){ ... }; * MyController.$inject = ['$location']; * </pre> * * @param {String|Array} serviceName... zero or more service names to inject into the * `annotatedFunction`. * @param {function} annotatedFunction function to annotate with `$inject` * functions. * @returns {function} `annotatedFunction` */ function annotate(services, fn) { if (services instanceof Array) { fn.$inject = services; return fn; } else { var i = 0, length = arguments.length - 1, // last one is the destination function $inject = arguments[length].$inject = []; for (; i < length; i++) { $inject.push(arguments[i]); } return arguments[length]; // return the last one } } function angularServiceInject(name, fn, inject, eager) { angularService(name, fn, {$inject:inject, $eager:eager}); } /** * @returns the $inject property of function. If not found the * the $inject is computed by looking at the toString of function and * extracting all arguments which and assuming that they are the * injection names. */ var FN_ARGS = /^function\s*[^\(]*\(([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(.+?)\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function inferInjectionArgs(fn) { assertArgFn(fn); if (!fn.$inject) { var args = fn.$inject = []; var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, name){ args.push(name); }); }); } return fn.$inject; } var OPERATORS = { 'null':function(self){return null;}, 'true':function(self){return true;}, 'false':function(self){return false;}, $undefined:noop, '+':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, a,b){return a(self)*b(self);}, '/':function(self, a,b){return a(self)/b(self);}, '%':function(self, a,b){return a(self)%b(self);}, '^':function(self, a,b){return a(self)^b(self);}, '=':noop, '==':function(self, a,b){return a(self)==b(self);}, '!=':function(self, a,b){return a(self)!=b(self);}, '<':function(self, a,b){return a(self)<b(self);}, '>':function(self, a,b){return a(self)>b(self);}, '<=':function(self, a,b){return a(self)<=b(self);}, '>=':function(self, a,b){return a(self)>=b(self);}, '&&':function(self, a,b){return a(self)&&b(self);}, '||':function(self, a,b){return a(self)||b(self);}, '&':function(self, a,b){return a(self)&b(self);}, // '|':function(self, a,b){return a|b;}, '|':function(self, a,b){return b(self)(self, a(self));}, '!':function(self, a){return !a(self);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, parseStringsForObjects){ var dateParseLength = parseStringsForObjects ? DATE_ISOSTRING_LN : -1, tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = ""; var start = index; var fn; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { ident += ch; } else { break; } index++; } fn = OPERATORS[ident]; tokens.push({ index:start, text:ident, json: fn, fn:fn||extend(getterFn(ident), { assign:function(self, value){ return setter(self, ident, value); } }) }); } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({index:start, text:rawString, string:string, json:true, fn:function() { return (string.length == dateParseLength) ? angular['String']['toDate'](string) : string; }}); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json){ var ZERO = valueFn(0), tokens = lex(text, json), assignment = _assignment, assignable = logicalOR, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain, functionIdent = _functionIdent, pipeFunction = _pipeFunction; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = assignable = filterChain = functionIdent = pipeFunction = function() { throwError("is not valid json", {text:text, index:0}); }; } //TODO: Shouldn't all of the public methods have assertAllConsumed? //TODO: I think these should be public as part of the parser api instead of scope.$eval(). return { assignable: assertConsumed(assignable), primary: assertConsumed(primary), statements: assertConsumed(statements), filter: assertConsumed(filter) }; function assertConsumed(fn) { return function() { var value = fn(); if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; }; } /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self) { return fn(self, right); }; } function binaryFn(left, fn, right) { return function(self) { return fn(self, left, right); }; } function hasTokens () { return tokens.length > 0; } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { return pipeFunction(angularFilter); } function _pipeFunction(fnScope){ var fn = functionIdent(fnScope); var argsFn = []; var token; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self){ return left.assign(self, right(self)); }; } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function _functionIdent(fnScope) { var token = expect(); var element = token.text.split('.'); var instance = fnScope; var key; for ( var i = 0; i < element.length; i++) { key = element[i]; if (instance) instance = instance[key]; } if (!isFunction(instance)) { throwError("should be a function", token); } return instance; } function primary() { var primary; if (expect('(')) { var expression = filterChain(); consume(')'); primary = expression; } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary); } else if (next.text === '[') { primary = objectIndex(primary); } else if (next.text === '.') { primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field); return extend(function(self){ return getter(object(self)); }, { assign:function(self, value){ return setter(object(self), field, value); } }); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self){ var o = obj(self); var i = indexFn(self); return (o) ? o[i] : undefined; }, { assign:function(self, value){ return obj(self)[indexFn(self)] = value; } }); } function _functionCall(fn) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(self){ var args = []; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } var fnPtr = fn(self) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(self, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function(self){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function(self){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self); object[keyValue.key] = value; } return object; }; } function watchDecl () { var anchorName = expect().text; consume(":"); var expressionFn; if (peekToken().text == '{') { consume("{"); expressionFn = statements(); consume("}"); } else { expressionFn = expression(); } return function(self) { return {name:anchorName, fn:expressionFn}; }; } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } if (isUndefined(obj) && key.charAt(0) == '$') { var type = angularGlobal.typeOf(lastInstance); type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; var fn = type ? type[[key.substring(1)]] : _undefined; if (fn) { return obj = bind(lastInstance, fn, lastInstance); } } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}, compileCache = {}, JS_KEYWORDS = {}; forEach( ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," + "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," + "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," + "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," + "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/), function(key){ JS_KEYWORDS[key] = true;} ); function getterFn(path) { var fn = getterFnCache[path]; if (fn) return fn; var code = 'var l, fn, t;\n'; forEach(path.split('.'), function(key) { key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key; code += 'if(!s) return s;\n' + 'l=s;\n' + 's=s' + key + ';\n' + 'if(typeof s=="function" && !(s instanceof RegExp)) {\n' + ' fn=function(){ return l' + key + '.apply(l, arguments); };\n' + ' fn.$unboundFn=s;\n' + ' s=fn;\n' + '}\n'; if (key.charAt(1) == '$') { // special code for super-imposed functions var name = key.substr(2); code += 'if(!s) {\n' + ' t = angular.Global.typeOf(l);\n' + ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' + ' if (fn) ' + 's = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0))); };\n' + '}\n'; } }); code += 'return s;'; fn = Function('s', code); fn["toString"] = function() { return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// // TODO(misko): Should this function be public? function compileExpr(expr) { return parser(expr).statements(); } // TODO(misko): Deprecate? Remove! // I think that compilation should be a service. function expressionCompile(exp) { if (isFunction(exp)) return exp; var fn = compileCache[exp]; if (!fn) { fn = compileCache[exp] = parser(exp).statements(); } return fn; } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && template.match(new RegExp(":" + param + "\\W"))) { urlParams[param] = true; } }); } Route.prototype = { url: function(params) { var self = this, url = this.template, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; forEachSorted(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(xhr) { this.xhr = xhr; } ResourceFactory.DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; ResourceFactory.prototype = { route: function(url, paramDefaults, actions){ var self = this; var route = new Route(url); actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; forEach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name){ var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; Resource[name] = function(a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (isPostOrPut) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); self.xhr( action.method, route.url(extend({}, extractParams(data), action.params || {}, params)), data, function(status, response) { if (response) { if (action.isArray) { value.length = 0; forEach(response, function(item) { value.push(new Resource(item)); }); } else { copy(response, value); } } (success||noop)(value); }, error || action.verifyCache, action.verifyCache); return value; }; Resource.bind = function(additionalParamDefaults){ return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = isPostOrPut ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); return Resource; } }; ////////////////////////////// // Browser ////////////////////////////// var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc service * @name angular.service.$browser * @requires $log * * @description * Constructor for the object exposed as $browser service. * * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link angular.mock.service.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} body jQuery wrapped document.body. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, body, XHR, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; ////////////////////////////////////////////////////////////// // XHR API ////////////////////////////////////////////////////////////// var idCounter = 0; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @ngdoc method * @name angular.service.$browser#xhr * @methodOf angular.service.$browser * * @param {string} method Requested method (get|post|put|delete|head|json) * @param {string} url Requested url * @param {?string} post Post data to send (null if nothing to post) * @param {function(number, string)} callback Function that will be called on response * @param {object=} header additional HTTP headers to send with XHR. * Standard headers are: * <ul> * <li><tt>Content-Type</tt>: <tt>application/x-www-form-urlencoded</tt></li> * <li><tt>Accept</tt>: <tt>application/json, text/plain, &#42;/&#42;</tt></li> * <li><tt>X-Requested-With</tt>: <tt>XMLHttpRequest</tt></li> * </ul> * * @description * Send ajax request */ self.xhr = function(method, url, post, callback, headers) { outstandingRequestCount ++; if (lowercase(method) == 'json') { var callbackId = ("angular_" + Math.random() + '_' + (idCounter++)).replace(/\d\./, ''); window[callbackId] = function(data) { window[callbackId].data = data; }; var script = self.addJs(url.replace('JSON_CALLBACK', callbackId), function() { if (window[callbackId].data) { completeOutstandingRequest(callback, 200, window[callbackId].data); } else { completeOutstandingRequest(callback); } delete window[callbackId]; body[0].removeChild(script); }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // normalize IE bug (http://bugs.jquery.com/ticket/1450) var status = xhr.status == 1223 ? 204 : xhr.status; completeOutstandingRequest(callback, status, xhr.responseText); } }; xhr.send(post || ''); } }; /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @ngdoc method * @name angular.service.$browser#addPollFn * @methodOf angular.service.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href; /** * @ngdoc method * @name angular.service.$browser#url * @methodOf angular.service.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.service.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else history.pushState(null, '', url); } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { return location.href; } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @ngdoc method * @name angular.service.$browser#onUrlChange * @methodOf angular.service.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.service.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; /** * @ngdoc method * @name angular.service.$browser#cookies * @methodOf angular.service.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, keyValue, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @ngdoc method * @name angular.service.$browser#defer * @methodOf angular.service.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * THIS DOC IS NOT VISIBLE because ngdocs can't process docs for foo#method.method * * @name angular.service.$browser#defer.cancel * @methodOf angular.service.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * @ngdoc method * @name angular.service.$browser#addCss * @methodOf angular.service.$browser * * @param {string} url Url to css file * @description * Adds a stylesheet tag to the head. */ self.addCss = function(url) { var link = jqLite(rawDocument.createElement('link')); link.attr('rel', 'stylesheet'); link.attr('type', 'text/css'); link.attr('href', url); body.append(link); }; /** * @ngdoc method * @name angular.service.$browser#addJs * @methodOf angular.service.$browser * * @param {string} url Url to js file * * @description * Adds a script tag to the head. */ self.addJs = function(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'); script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { /loaded|complete/.test(script.readyState) && done && done(); }; } else { if (done) script.onload = script.onerror = done; } body[0].appendChild(script); return script; }; /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = document.find('base').attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; }; } /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," + "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," + "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," + "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," + "span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); var validAttrs = extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function() { return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = voidElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { var value = doubleQuotedValue || singleQoutedValue || unqoutedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent || ''; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); forEach(attrs, function(value, key){ var lkey=lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [hasClass()](http://api.jquery.com/hasClass/) * - [parent()](http://api.jquery.com/parent/) * - [prop()](http://api.jquery.com/prop/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [trigger()](http://api.jquery.com/trigger/) * - [unbind()](http://api.jquery.com/unbind/) * * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite: * * - `scope()` - retrieves the current Angular scope of the element. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return (jqId++); } function getStyle(element) { var current = {}, style = element[0].style, value, name, i; if (typeof style.length == 'number') { for(i = 0; i < style.length; i++) { name = style[i]; current[name] = style[name]; } } else { for (name in style) { value = style[name]; if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false') current[name] = value; } } return current; } /** * Converts dash-separated names to camelCase. Useful for dealing with css properties. */ function camelCase(name) { return name.replace(/\-(\w)/g, function(all, letter, offset){ return (offset == 0 && letter == 'w') ? 'w' : letter.toUpperCase(); }); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, data; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { data = element.data('events'); if ( (fns = data && data.$destroy) ) { forEach(fns, function(fn){ fn.handler(); }); } } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function jqLiteWrap(element) { if (isString(element) && element.charAt(0) != '<') { throw new Error('selectors not implemented'); } return new JQLite(element); } function JQLite(element) { if (element instanceof JQLite) { return element; } else if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteRemoveData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { if (cache.bind) { forEach(cache.bind, function(fn, type){ if (type == '$destroy') { fn({}); } else { removeEventListenerFn(element, type, fn); } }); } delete jqCache[cacheId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteData(element, key, value) { var cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : null; } } function JQLiteHasClass(element, selector, _) { // the argument '_' is important, since it makes the function have 3 arguments, which // is needed for delegate function to realize the this is a getter. return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. jqLiteWrap(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); forEach({ data: JQLiteData, inheritedData: function(element, name, value) { element = jqLite(element); while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } }, scope: function(element) { return jqLite(element).inheritedData($$scope); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || element.getAttribute(name) !== null && (msie < 9 ? element.getAttribute(name) !== '' : true)) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { // NodeType == 3 is text node if (element.nodeType == 3) { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } else { if (isUndefined(value)) return element.innerText; element.innerText = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; if ((fn.length == 2 ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { for (key in arg1) { fn(this[i], key, arg1[key]); } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function(element, type, fn){ var bind = JQLiteData(element, 'bind'); if (!bind) JQLiteData(element, 'bind', bind = {}); forEach(type.split(' '), function(type){ var eventHandler = bind[type]; if (!eventHandler) { bind[type] = eventHandler = function(event) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(eventHandler.fns, function(fn){ fn.call(element, event); }); }; eventHandler.fns = []; addEventListenerFn(element, type, eventHandler); } eventHandler.fns.push(fn); }); }, unbind: function(element, type, fn) { var bind = JQLiteData(element, 'bind'); if (!bind) return; //no listeners registered if (isUndefined(type)) { forEach(bind, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete bind[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, bind[type]); delete bind[type]; } else { angularArray.remove(bind[type].fns, fn); } } }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); var angularGlobal = { 'typeOf':function(obj){ if (obj === null) return $null; var type = typeof obj; if (type == $object) { if (obj instanceof Array) return $array; if (isDate(obj)) return $date; if (obj.nodeType == 1) return 'element'; } return type; } }; /** * @ngdoc overview * @name angular.Object * @function * * @description * A namespace for utility functions used to work with JavaScript objects. These functions are * exposed in two ways: * * * __Angular expressions:__ Functions are bound to all objects and augment the Object type. * The names of these methods are prefixed with the '$' character in order to minimize naming * collisions. To call a method, invoke the function without the first argument, for example, * `myObject.$foo(param2)`. * * * __JavaScript code:__ Functions don't augment the Object type and must be invoked as functions * of `angular.Object` as `angular.Object.foo(myObject, param2)`. * * * {@link angular.Object.copy angular.Object.copy()} - Creates a deep copy of the source * parameter. * * {@link angular.Object.equals angular.Object.equals()} - Determines if two objects or values * are equivalent. * * {@link angular.Object.size angular.Object.size()} - Determines the number of elements in * strings, arrays, and objects. */ var angularCollection = { 'copy': copy, 'size': size, 'equals': equals }; var angularObject = { 'extend': extend }; /** * @ngdoc overview * @name angular.Array * * @description * A namespace for utility functions for the manipulation of JavaScript Array objects. * * These functions are exposed in two ways: * * * __Angular expressions:__ Functions are bound to the Array objects and augment the Array type * as array methods. The names of these methods are prefixed with the `$` character to minimize * naming collisions. To call a method, invoke myArrayObject.$foo(params). * * Because Array type is a subtype of the Object type, all angular.Object functions augment * the Array type in Angular expressions as well. * * * __JavaScript code:__ Functions do nor augment the Array type and must be invoked as functions * of `angular.Array` as `angular.Array.foo(myArrayObject, params)`. * * The following APIs are built in to the Angular Array object: * * * {@link angular.Array.add angular.Array.add()} - Optionally adds a new element to an array. * * {@link angular.Array.count angular.Array.count()} - Determines the number of elements in an * array. * * {@link angular.Array.filter angular.Array.filter()} - Returns the subset of elements specified * in the filter as a new array. * * {@link angular.Array.indexOf angular.Array.indexOf()} - Determines the index of an array * value. * * {@link angular.Array.limitTo angular.Array.limitTo()} - Creates a sub-array of an existing * array. * * {@link angular.Array.orderBy angular.Array.orderBy()} - Orders array elements. * * {@link angular.Array.remove angular.Array.remove()} - Removes array elements. * * {@link angular.Array.sum angular.Array.sum()} - Sums the numbers in an array. */ var angularArray = { /** * @ngdoc function * @name angular.Array.indexOf * @function * * @description * Determines the index of a `value` in an `array`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array Array to search. * @param {*} value Value to search for. * @returns {number} The position of the element in `array`. The position is 0-based. * If the value cannot be found, `-1` is returned. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.books = ['Moby Dick', 'Great Gatsby', 'Romeo and Juliet']; this.bookName = 'Romeo and Juliet'; } </script> <div ng:controller="Ctrl"> <input ng:model='bookName'> <br> Index of '{{bookName}}' in the list {{books}} is <em>{{books.$indexOf(bookName)}}</em>. </div> </doc:source> <doc:scenario> it('should correctly calculate the initial index', function() { expect(binding('books.$indexOf(bookName)')).toBe('2'); }); it('should recalculate', function() { input('bookName').enter('foo'); expect(binding('books.$indexOf(bookName)')).toBe('-1'); input('bookName').enter('Moby Dick'); expect(binding('books.$indexOf(bookName)')).toBe('0'); }); </doc:scenario> </doc:example> */ 'indexOf': indexOf, /** * @ngdoc function * @name angular.Array.sum * @function * * @description * The `sum` function calculates the sum of all numbers in an `array`. If an `expression` is * supplied, `sum` evaluates each element in the `array` with the expression and then returns * the sum of the calculated values. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more info about Angular arrays. * * @param {Array} array The source array. * @param {(string|function())=} expression Angular expression or a function to be evaluated for * each element in `array`. The array element becomes the `this` during the evaluation. * @returns {number} Sum of items in the array. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.invoice = { items:[ { qty:10, description:'gadget', cost:9.95 } ] }; } </script> <table class="invoice" ng:controller="Ctrl"> <tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr> <tr ng:repeat="item in invoice.items"> <td><input type="integer" ng:model="item.qty" size="4" required></td> <td><input type="text" ng:model="item.description"></td> <td><input type="number" ng:model="item.cost" required size="6"></td> <td>{{item.qty * item.cost | currency}}</td> <td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td> </tr> <tr> <td><a href ng:click="invoice.items.$add({qty:1, cost:0})">add item</a></td> <td></td> <td>Total:</td> <td>{{invoice.items.$sum('qty*cost') | currency}}</td> </tr> </table> </doc:source> <doc:scenario> //TODO: these specs are lame because I had to work around issues #164 and #167 it('should initialize and calculate the totals', function() { expect(repeater('table.invoice tr', 'item in invoice.items').count()).toBe(3); expect(repeater('table.invoice tr', 'item in invoice.items').row(1)). toEqual(['$99.50']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); }); it('should add an entry and recalculate', function() { element('.doc-example-live a:contains("add item")').click(); using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20'); using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100'); expect(repeater('table.invoice tr', 'item in invoice.items').row(2)). toEqual(['$2,000.00']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50'); }); </doc:scenario> </doc:example> */ 'sum':function(array, expression) { var fn = angularFunction.compile(expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, /** * @ngdoc function * @name angular.Array.remove * @function * * @description * Modifies `array` by removing an element from it. The element will be looked up using the * {@link angular.Array.indexOf indexOf} function on the `array` and only the first instance of * the element will be removed. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array Array from which an element should be removed. * @param {*} value Element to be removed. * @returns {*} The removed element. * * @example <doc:example> <doc:source> <ul ng:init="tasks=['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']"> <li ng:repeat="task in tasks"> {{task}} [<a href="" ng:click="tasks.$remove(task)">X</a>] </li> </ul> <hr/> tasks = {{tasks}} </doc:source> <doc:scenario> it('should initialize the task list with for tasks', function() { expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(4); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']); }); it('should initialize the task list with for tasks', function() { element('.doc-example-live ul li a:contains("X"):first').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(3); element('.doc-example-live ul li a:contains("X"):last').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(2); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Read Documentation', 'Check out demos']); }); </doc:scenario> </doc:example> */ 'remove':function(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, /** * @ngdoc function * @name angular.Array.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input ng:model="searchText"/> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(searchText)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input ng:model="search.$"/> <br> Name only <input ng:model="search.name"/><br> Phone only <input ng:model="search.phone"/><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(search)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function() { var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, /** * @ngdoc function * @name angular.Array.add * @function * * @description * The `add` function in Angualar is similar to JavaScript's `Array#push` method in that it * appends a new element to an array. Angular's function differs from the JavaScript method in * that specifying a value for the function is optional and the default for the function is an * empty object. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array The array to be expanded. * @param {*=} [value={}] The value to be appended. * @returns {Array} The expanded array. * * @TODO simplify the example. * * @example * This example shows how you can use the `$add` method to populate an initially empty array * with objects created from user input. <doc:example> <doc:source> <script> function Ctrl() { this.people = []; } </script> <div ng:controller="Ctrl"> [<a href="" ng:click="people.$add()">add empty</a>] [<a href="" ng:click="people.$add({name:'John', sex:'male'})">add 'John'</a>] [<a href="" ng:click="people.$add({name:'Mary', sex:'female'})">add 'Mary'</a>] <ul> <li ng:repeat="person in people"> <input ng:model="person.name"> <select ng:model="person.sex"> <option value="">--chose one--</option> <option>male</option> <option>female</option> </select> [<a href="" ng:click="people.$remove(person)">X</a>] </li> </ul> <pre>people = {{people}}</pre> </div> </doc:source> <doc:scenario> beforeEach(function() { expect(binding('people')).toBe('people = []'); }); it('should create an empty record when "add empty" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); expect(binding('people')).toBe('people = [{\n }]'); }); it('should create a "John" record when "add \'John\'" is clicked', function() { element('.doc-example-live a:contains("add \'John\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"John",\n "sex":"male"}]'); }); it('should create a "Mary" record when "add \'Mary\'" is clicked', function() { element('.doc-example-live a:contains("add \'Mary\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"Mary",\n "sex":"female"}]'); }); it('should delete a record when "X" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); element('.doc-example-live li a:contains("X"):first').click(); expect(binding('people')).toBe('people = []'); }); </doc:scenario> </doc:example> */ 'add':function(array, value) { array.push(isUndefined(value)? {} : value); return array; }, /** * @ngdoc function * @name angular.Array.count * @function * * @description * Determines the number of elements in an array. Provides an option for counting only those * elements for which a specified `condition` evaluates to `true`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array The array containing the elements to be counted. * @param {(function()|string)=} condition A function to be evaluated or * an Angular expression to be compiled and evaluated. The element being * iterated over is exposed to the `condition` as `this`. * @returns {number} Number of elements in the array. If a `condition` is specified, returns * the number of elements whose `condition` evaluates to `true`. * * @example <doc:example> <doc:source> <pre ng:init="items = [{name:'knife', points:1}, {name:'fork', points:3}, {name:'spoon', points:1}]"></pre> <ul> <li ng:repeat="item in items"> {{item.name}}: points= <input type="text" ng:model="item.points"/> <!-- id="item{{$index}} --> </li> </ul> <p>Number of items which have one point: <em>{{ items.$count('points==1') }}</em></p> <p>Number of items which have more than one point: <em>{{items.$count('points&gt;1')}}</em></p> </doc:source> <doc:scenario> it('should calculate counts', function() { expect(binding('items.$count(\'points==1\')')).toEqual('2'); expect(binding('items.$count(\'points>1\')')).toEqual('1'); }); it('should recalculate when updated', function() { using('.doc-example-live li:first-child').input('item.points').enter('23'); expect(binding('items.$count(\'points==1\')')).toEqual('1'); expect(binding('items.$count(\'points>1\')')).toEqual('2'); }); </doc:scenario> </doc:example> */ 'count':function(array, condition) { if (!condition) return array.length; var fn = angularFunction.compile(condition), count = 0; forEach(array, function(value){ if (fn(value)) { count ++; } }); return count; }, /** * @ngdoc function * @name angular.Array.orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] this.predicate = '-age'; } </script> <div ng:controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng:click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng:click="predicate = 'name'; reverse=false">Name</a> (<a href ng:click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng:click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng:click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng:repeat="friend in friends.$orderBy(predicate, reverse)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('Sorting predicate = -age; reverse = '); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ 'orderBy':function(array, sortPredicate, reverseOrder) { if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = expressionCompile(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }, /** * @ngdoc function * @name angular.Array.limitTo * @function * * @description * Creates a new array containing only a specified number of elements in an array. The elements * are taken from either the beginning or the end of the source array, as specified by the * value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the `limit` number is * positive, `limit` number of items from the beginning of the source array are copied. * If the number is negative, `limit` number of items from the end of the source array are * copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` * elements. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.numbers = [1,2,3,4,5,6,7,8,9]; this.limit = 3; } </script> <div ng:controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng:model="limit"/> <p>Output: {{ numbers.$limitTo(limit) | json }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[ng\\:model=limit]').val()).toBe('3'); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[7,8,9]'); }); it('should not exceed the maximum size of input array', function() { input('limit').enter(100); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3,4,5,6,7,8,9]'); }); </doc:scenario> </doc:example> */ limitTo: function(array, limit) { limit = parseInt(limit, 10); var out = [], i, n; // check that array is iterable if (!array || !(array instanceof Array)) return out; // if abs(limit) exceeds maximum length, trim it if (limit > array.length) limit = array.length; else if (limit < -array.length) limit = -array.length; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } }; var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/; var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, /** * Tries to convert input to date and if successful returns the date, otherwise returns the * input. * * @param {string} string * @return {(Date|string)} */ 'toDate':function(string){ var match; if (isString(string) && (match = string.match(R_ISO8061_STR))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0); return date; } return string; } }; var angularDate = { 'toString':function(date){ if (!date) return date; var isoString = date.toISOString ? date.toISOString() : ''; return (isoString.length==24) ? isoString : padNumber(date.getUTCFullYear(), 4) + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + '.' + padNumber(date.getUTCMilliseconds(), 3) + 'Z'; } }; var angularFunction = { 'compile': function(expression) { if (isFunction(expression)){ return expression; } else if (expression){ return expressionCompile(expression); } else { return identity; } } }; /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {String} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj; var key = obj; if (objType == 'object') { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that the form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } } }; function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; forEach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal]); defineApi('Collection', [angularGlobal, angularCollection]); defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); //IE bug angular.Date.toString = angularDate.toString; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); /** * @ngdoc overview * @name angular.filter * @description * * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * Following is the list of built-in angular filters: * * * {@link angular.filter.currency currency} * * {@link angular.filter.date date} * * {@link angular.filter.html html} * * {@link angular.filter.json json} * * {@link angular.filter.linky linky} * * {@link angular.filter.lowercase lowercase} * * {@link angular.filter.number number} * * {@link angular.filter.uppercase uppercase} * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc filter * @name angular.filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * @css ng-format-negative * When the value is negative, this css class is applied to the binding making it (by default) red. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.amount = 1234.56; } </script> <div ng:controller="Ctrl"> <input type="number" ng:model="amount"/> <br/> default currency symbol ($): {{amount | currency}}<br/> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); expect(element('.doc-example-live .ng-binding').prop('className')). toMatch(/ng-format-negative/); }); </doc:scenario> </doc:example> */ angularFilter.currency = function(amount, currencySymbol){ var formats = this.$service('$locale').NUMBER_FORMATS; this.$element.toggleClass('ng-format-negative', amount < 0); if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; /** * @ngdoc filter * @name angular.filter.number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.val = 1234.56789; } </script> <div ng:controller="Ctrl"> Enter number: <input ng:model='val'><br/> Default formatting: {{val | number}}<br/> No fractions: {{val | number:0}}<br/> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ var DECIMAL_SEP = '.'; angularFilter.number = function(number, fractionSize) { var formats = this.$service('$locale').NUMBER_FORMATS; return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var GET_TIME_ZONE = /[A-Z]{3}(?![+\-])/, DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, OPERA_TOSTRING_PATTERN = /^[\d].*Z$/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name angular.filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/dev_guide.i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng:non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ angularFilter.date = function(date, format) { var $locale = this.$service('$locale'), text = '', parts = [], fn, match; format = format || 'mediumDate' format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = parseInt(date, 10); } else { date = angularString.toDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; /** * @ngdoc filter * @name angular.filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * @css ng-monospace Always applied to the encapsulating element. * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding('| json')).toBe('{\n "name":"value"}'); }); </doc:scenario> </doc:example> * */ angularFilter.json = function(object) { this.$element.addClass("ng-monospace"); return toJson(object, true, /^(\$|this$)/); }; /** * @ngdoc filter * @name angular.filter.lowercase * @function * * @see angular.lowercase */ angularFilter.lowercase = lowercase; /** * @ngdoc filter * @name angular.filter.uppercase * @function * * @see angular.uppercase */ angularFilter.uppercase = uppercase; /** * @ngdoc filter * @name angular.filter.html * @function * * @description * Prevents the input from getting escaped by angular. By default the input is sanitized and * inserted into the DOM as is. * * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses * the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this * option is strongly discouraged and should be used only if you absolutely trust the input being * filtered and you can't get the content through the sanitizer. * * @param {string} html Html input. * @param {string=} option If 'unsafe' then do not sanitize the HTML input. * @returns {string} Sanitized or raw html. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; } </script> <div ng:controller="Ctrl"> Snippet: <textarea ng:model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng:bind="snippet | html"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | html"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng:bind="snippet | html:'unsafe'"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet | html:'unsafe'"></div></td> </tr> </table> </div> </doc:source> <doc:scenario> it('should sanitize the html snippet ', function() { expect(using('#html-filter').binding('snippet | html')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should escape snippet without any filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function() { input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>'); expect(using('#escaped-html').binding('snippet')).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>'); }); </doc:scenario> </doc:example> */ angularFilter.html = function(html, option){ return new HTML(html, option); }; /** * @ngdoc filter * @name angular.filter.linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:us@somewhere.org,\n'+ 'another@somewhere.org,\n'+ 'and one more: ftp://127.0.0.1/.'; } </script> <div ng:controller="Ctrl"> Snippet: <textarea ng:model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng:bind="snippet | linky"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should linkify the snippet with urls', function() { expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:\n' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,\n' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,\n' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function() { input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); </doc:scenario> </doc:example> */ var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/, MAILTO_REGEXP = /^mailto:/; angularFilter.linky = function(text) { if (!text) return text; var match; var raw = text; var html = []; var writer = htmlSanitizeWriter(html); var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2] == match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(MAILTO_REGEXP, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return new HTML(html.join('')); }; /** * @ngdoc service * @name angular.service.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ angularServiceInject('$cookieStore', function($store) { return { /** * @ngdoc method * @name angular.service.$cookieStore#get * @methodOf angular.service.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return fromJson($store[key]); }, /** * @ngdoc method * @name angular.service.$cookieStore#put * @methodOf angular.service.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $store[key] = toJson(value); }, /** * @ngdoc method * @name angular.service.$cookieStore#remove * @methodOf angular.service.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $store[key]; } }; }, ['$cookies']); /** * @ngdoc service * @name angular.service.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ angularServiceInject('$cookies', function($browser) { var rootScope = this, cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. this.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!isString(value)) { if (isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }, ['$browser']); /** * @ngdoc service * @name angular.service.$defer * @requires $browser * * @description * Delegates to {@link angular.service.$browser $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.service.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$defer.cancel()`. */ /** * @ngdoc function * @name angular.service.$defer#cancel * @methodOf angular.service.$defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ angularServiceInject('$defer', function($browser) { var scope = this; function defer(fn, delay) { return $browser.defer(function() { scope.$apply(fn); }, delay); } defer.cancel = function(deferId) { return $browser.defer.cancel(deferId); }; return defer; }, ['$browser']); /** * @ngdoc service * @name angular.service.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ angularServiceInject("$document", function(window){ return jqLite(window.document); }, ['$window']); /** * @ngdoc service * @name angular.service.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overriden by * {@link angular.mock.service.$exceptionHandler mock $exceptionHandler} * * @example */ var $exceptionHandlerFactory; //reference to be used only in tests angularServiceInject('$exceptionHandler', $exceptionHandlerFactory = function($log){ return function(e) { $log.error(e); }; }, ['$log']); /** * @ngdoc service * @name angular.service.$formFactory * * @description * Use `$formFactory` to create a new instance of a {@link guide/dev_guide.forms form} * controller or to find the nearest form instance for a given DOM element. * * The form instance is a collection of widgets, and is responsible for life cycle and validation * of widget. * * Keep in mind that both form and widget instances are {@link api/angular.scope scopes}. * * @param {Form=} parentForm The form which should be the parent form of the new form controller. * If none specified default to the `rootForm`. * @returns {Form} A new <a href="#form">form</a> instance. * * @example * * This example shows how one could write a widget which would enable data-binding on * `contenteditable` feature of HTML. * <doc:example> <doc:source> <script> function EditorCntl() { this.html = '<b>Hello</b> <i>World</i>!'; } function HTMLEditorWidget(element) { var self = this; var htmlFilter = angular.filter('html'); this.$parseModel = function() { // need to protect for script injection try { this.$viewValue = htmlFilter(this.$modelValue || '').get(); if (this.$error.HTML) { // we were invalid, but now we are OK. this.$emit('$valid', 'HTML'); } } catch (e) { // if HTML not parsable invalidate form. this.$emit('$invalid', 'HTML'); } } this.$render = function() { element.html(this.$viewValue); } element.bind('keyup', function() { self.$apply(function() { self.$emit('$viewChange', element.html()); }); }); } angular.directive('ng:contenteditable', function() { function linkFn($formFactory, element) { var exp = element.attr('ng:contenteditable'), form = $formFactory.forElement(element), widget; element.attr('contentEditable', true); widget = form.$createWidget({ scope: this, model: exp, controller: HTMLEditorWidget, controllerArgs: [element]}); // if the element is destroyed, then we need to notify the form. element.bind('$destroy', function() { widget.$destroy(); }); } linkFn.$inject = ['$formFactory']; return linkFn; }); </script> <form name='editorForm' ng:controller="EditorCntl"> <div ng:contenteditable="html"></div> <hr/> HTML: <br/> <textarea ng:model="html" cols=80></textarea> <hr/> <pre>editorForm = {{editorForm}}</pre> </form> </doc:source> <doc:scenario> it('should enter invalid HTML', function() { expect(element('form[name=editorForm]').prop('className')).toMatch(/ng-valid/); input('html').enter('<'); expect(element('form[name=editorForm]').prop('className')).toMatch(/ng-invalid/); }); </doc:scenario> </doc:example> */ angularServiceInject('$formFactory', function() { /** * @ngdoc proprety * @name rootForm * @propertyOf angular.service.$formFactory * @description * Static property on `$formFactory` * * Each application ({@link guide/dev_guide.scopes.internals root scope}) gets a root form which * is the top-level parent of all forms. */ formFactory.rootForm = formFactory(this); /** * @ngdoc method * @name forElement * @methodOf angular.service.$formFactory * @description * Static method on `$formFactory` service. * * Retrieve the closest form for a given element or defaults to the `root` form. Used by the * {@link angular.widget.form form} element. * @param {Element} element The element where the search for form should initiate. */ formFactory.forElement = function(element) { return element.inheritedData('$form') || formFactory.rootForm; }; return formFactory; function formFactory(parent) { return (parent || formFactory.rootForm).$new(FormController); } }); function propertiesUpdate(widget) { widget.$valid = !(widget.$invalid = !(widget.$readonly || widget.$disabled || equals(widget.$error, {}))); } /** * @ngdoc property * @name $error * @propertyOf angular.service.$formFactory * @description * Property of the form and widget instance. * * Summary of all of the errors on the page. If a widget emits `$invalid` with `REQUIRED` key, * then the `$error` object will have a `REQUIRED` key with an array of widgets which have * emitted this key. `form.$error.REQUIRED == [ widget ]`. */ /** * @ngdoc property * @name $invalid * @propertyOf angular.service.$formFactory * @description * Property of the form and widget instance. * * True if any of the widgets of the form are invalid. */ /** * @ngdoc property * @name $valid * @propertyOf angular.service.$formFactory * @description * Property of the form and widget instance. * * True if all of the widgets of the form are valid. */ /** * @ngdoc event * @name angular.service.$formFactory#$valid * @eventOf angular.service.$formFactory * @eventType listen on form * @description * Upon receiving the `$valid` event from the widget update the `$error`, `$valid` and `$invalid` * properties of both the widget as well as the from. * * @param {String} validationKey The validation key to be used when updating the `$error` object. * The validation key is what will allow the template to bind to a specific validation error * such as `<div ng:show="form.$error.KEY">error for key</div>`. */ /** * @ngdoc event * @name angular.service.$formFactory#$invalid * @eventOf angular.service.$formFactory * @eventType listen on form * @description * Upon receiving the `$invalid` event from the widget update the `$error`, `$valid` and `$invalid` * properties of both the widget as well as the from. * * @param {String} validationKey The validation key to be used when updating the `$error` object. * The validation key is what will allow the template to bind to a specific validation error * such as `<div ng:show="form.$error.KEY">error for key</div>`. */ /** * @ngdoc event * @name angular.service.$formFactory#$validate * @eventOf angular.service.$formFactory * @eventType emit on widget * @description * Emit the `$validate` event on the widget, giving a widget a chance to emit a * `$valid` / `$invalid` event base on its state. The `$validate` event is triggered when the * model or the view changes. */ /** * @ngdoc event * @name angular.service.$formFactory#$viewChange * @eventOf angular.service.$formFactory * @eventType listen on widget * @description * A widget is responsible for emitting this event whenever the view changes do to user interaction. * The event takes a `$viewValue` parameter, which is the new value of the view. This * event triggers a call to `$parseView()` as well as `$validate` event on widget. * * @param {*} viewValue The new value for the view which will be assigned to `widget.$viewValue`. */ function FormController() { var form = this, $error = form.$error = {}; form.$on('$destroy', function(event){ var widget = event.targetScope; if (widget.$widgetId) { delete form[widget.$widgetId]; } forEach($error, removeWidget, widget); }); form.$on('$valid', function(event, error){ var widget = event.targetScope; delete widget.$error[error]; propertiesUpdate(widget); removeWidget($error[error], error, widget); }); form.$on('$invalid', function(event, error){ var widget = event.targetScope; addWidget(error, widget); widget.$error[error] = true; propertiesUpdate(widget); }); propertiesUpdate(form); function removeWidget(queue, errorKey, widget) { if (queue) { widget = widget || this; // so that we can be used in forEach; for (var i = 0, length = queue.length; i < length; i++) { if (queue[i] === widget) { queue.splice(i, 1); if (!queue.length) { delete $error[errorKey]; } } } propertiesUpdate(form); } } function addWidget(errorKey, widget) { var queue = $error[errorKey]; if (queue) { for (var i = 0, length = queue.length; i < length; i++) { if (queue[i] === widget) { return; } } } else { $error[errorKey] = queue = []; } queue.push(widget); propertiesUpdate(form); } } /** * @ngdoc method * @name $createWidget * @methodOf angular.service.$formFactory * @description * * Use form's `$createWidget` instance method to create new widgets. The widgets can be created * using an alias which makes the accessible from the form and available for data-binding, * useful for displaying validation error messages. * * The creation of a widget sets up: * * - `$watch` of `expression` on `model` scope. This code path syncs the model to the view. * The `$watch` listener will: * * - assign the new model value of `expression` to `widget.$modelValue`. * - call `widget.$parseModel` method if present. The `$parseModel` is responsible for copying * the `widget.$modelValue` to `widget.$viewValue` and optionally converting the data. * (For example to convert a number into string) * - emits `$validate` event on widget giving a widget a chance to emit `$valid` / `$invalid` * event. * - call `widget.$render()` method on widget. The `$render` method is responsible for * reading the `widget.$viewValue` and updating the DOM. * * - Listen on `$viewChange` event from the `widget`. This code path syncs the view to the model. * The `$viewChange` listener will: * * - assign the value to `widget.$viewValue`. * - call `widget.$parseView` method if present. The `$parseView` is responsible for copying * the `widget.$viewValue` to `widget.$modelValue` and optionally converting the data. * (For example to convert a string into number) * - emits `$validate` event on widget giving a widget a chance to emit `$valid` / `$invalid` * event. * - Assign the `widget.$modelValue` to the `expression` on the `model` scope. * * - Creates these set of properties on the `widget` which are updated as a response to the * `$valid` / `$invalid` events: * * - `$error` - object - validation errors will be published as keys on this object. * Data-binding to this property is useful for displaying the validation errors. * - `$valid` - boolean - true if there are no validation errors * - `$invalid` - boolean - opposite of `$valid`. * @param {Object} params Named parameters: * * - `scope` - `{Scope}` - The scope to which the model for this widget is attached. * - `model` - `{string}` - The name of the model property on model scope. * - `controller` - {WidgetController} - The controller constructor function. * The controller constructor should create these instance methods. * - `$parseView()`: optional method responsible for copying `$viewVale` to `$modelValue`. * The method may fire `$valid`/`$invalid` events. * - `$parseModel()`: optional method responsible for copying `$modelVale` to `$viewValue`. * The method may fire `$valid`/`$invalid` events. * - `$render()`: required method which needs to update the DOM of the widget to match the * `$viewValue`. * * - `controllerArgs` - `{Array}` (Optional) - Any extra arguments will be curried to the * WidgetController constructor. * - `onChange` - `{(string|function())}` (Optional) - Expression to execute when user changes the * value. * - `alias` - `{string}` (Optional) - The name of the form property under which the widget * instance should be published. The name should be unique for each form. * @returns {Widget} Instance of a widget scope. */ FormController.prototype.$createWidget = function(params) { var form = this, modelScope = params.scope, onChange = params.onChange, alias = params.alias, scopeGet = parser(params.model).assignable(), scopeSet = scopeGet.assign, widget = this.$new(params.controller, params.controllerArgs); widget.$error = {}; // Set the state to something we know will change to get the process going. widget.$modelValue = Number.NaN; // watch for scope changes and update the view appropriately modelScope.$watch(scopeGet, function(scope, value) { if (!equals(widget.$modelValue, value)) { widget.$modelValue = value; widget.$parseModel ? widget.$parseModel() : (widget.$viewValue = value); widget.$emit('$validate'); widget.$render && widget.$render(); } }); widget.$on('$viewChange', function(event, viewValue){ if (!equals(widget.$viewValue, viewValue)) { widget.$viewValue = viewValue; widget.$parseView ? widget.$parseView() : (widget.$modelValue = widget.$viewValue); scopeSet(modelScope, widget.$modelValue); if (onChange) modelScope.$eval(onChange); widget.$emit('$validate'); } }); propertiesUpdate(widget); // assign the widgetModel to the form if (alias && !form.hasOwnProperty(alias)) { form[alias] = widget; widget.$widgetId = alias; } else { alias = null; } return widget; }; var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function matchUrl(url, obj) { var match = URL_MATCH.exec(url), match = { protocol: match[1], host: match[3], port: parseInt(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) != 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) != 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} url HTML5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} url HTML5 url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.path.indexOf(pathPrefix) != 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }, /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) != 0) { throw 'Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'; } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$parse(url); } LocationUrl.prototype = LocationHashbangUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name angular.service.$location#absUrl * @methodOf angular.service.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name angular.service.$location#url * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); this.path(decodeURIComponent(match[1] || '')).search(match[3] || '') .hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name angular.service.$location#protocol * @methodOf angular.service.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name angular.service.$location#host * @methodOf angular.service.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} */ host: locationGetter('$$host'), /** * @ngdoc method * @name angular.service.$location#port * @methodOf angular.service.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} */ port: locationGetter('$$port'), /** * @ngdoc method * @name angular.service.$location#path * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name angular.service.$location#search * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search part - string or hash object * @return {string} */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = encodeUriQuery(paramValue); } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name angular.service.$location#hash * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name angular.service.$location#replace * @methodOf angular.service.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc service * @name angular.service.$location * * @requires $browser * @requires $sniffer * @requires $locationConfig * @requires $document * * @description * The $location service parses the URL in the browser address bar (based on the {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location} */ angularServiceInject('$location', function($browser, $sniffer, $locationConfig, $document) { var scope = this, currentUrl, basePath = $browser.baseHref() || '/', pathPrefix = pathPrefixFromBase(basePath), hashPrefix = $locationConfig.hashPrefix || '', initUrl = $browser.url(); if ($locationConfig.html5Mode) { if ($sniffer.history) { currentUrl = new LocationUrl(convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix); } else { currentUrl = new LocationHashbangUrl(convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix); } // link rewriting var u = currentUrl, absUrlPrefix = composeProtocolHostPort(u.protocol(), u.host(), u.port()) + pathPrefix; $document.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (elm.length && lowercase(elm[0].nodeName) !== 'a') { elm = elm.parent(); } var href = elm.attr('href'); if (!href || isDefined(elm.attr('ng:ext-link')) || elm.attr('target')) return; // remove same domain from full url links (IE7 always returns full hrefs) href = href.replace(absUrlPrefix, ''); // link to different domain (or base path) if (href.substr(0, 4) == 'http') return; // remove pathPrefix from absolute links href = href.indexOf(pathPrefix) === 0 ? href.substr(pathPrefix.length) : href; currentUrl.url(href); scope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; }); } else { currentUrl = new LocationHashbangUrl(initUrl, hashPrefix); } // rewrite hashbang url <> html5 url if (currentUrl.absUrl() != initUrl) { $browser.url(currentUrl.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if (currentUrl.absUrl() != newUrl) { currentUrl.$$parse(newUrl); scope.$apply(); } }); // update browser var changeCounter = 0; scope.$watch(function() { if ($browser.url() != currentUrl.absUrl()) { changeCounter++; scope.$evalAsync(function() { $browser.url(currentUrl.absUrl(), currentUrl.$$replace); currentUrl.$$replace = false; }); } return changeCounter; }); return currentUrl; }, ['$browser', '$sniffer', '$locationConfig', '$document']); angular.service('$locationConfig', function() { return { html5Mode: false, hashPrefix: '' }; }); /** * @ngdoc service * @name angular.service.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <script> function LogCtrl($log) { this.$log = $log; this.message = 'Hello World!'; } </script> <div ng:controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng:model="message"/> <button ng:click="$log.log(message)">log</button> <button ng:click="$log.warn(message)">warn</button> <button ng:click="$log.info(message)">info</button> <button ng:click="$log.error(message)">error</button> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ var $logFactory; //reference to be used only in tests angularServiceInject("$log", $logFactory = function($window){ return { /** * @ngdoc method * @name angular.service.$log#log * @methodOf angular.service.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name angular.service.$log#warn * @methodOf angular.service.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name angular.service.$log#info * @methodOf angular.service.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name angular.service.$log#error * @methodOf angular.service.$log * * @description * Write an error message */ error: consoleLog('error') }; function consoleLog(type) { var console = $window.console || {}; var logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg){ args.push(formatError(arg)); }); return logFn.apply(console, args); }; } else { // we are IE, in which case there is nothing we can do return logFn; } } }, ['$window']); /** * @ngdoc service * @name angular.service.$resource * @requires $xhr.cache * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link angular.service.$xhr $xhr} service or * raw XMLHttpRequest. * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?, verifyCache:?}, * action2: {method:?, params:?, isArray:?, verifyCache:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSON` (also known as JSONP). * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * - verifyCache – {boolean=} – If true then whenever cache hit occurs, the object is returned and * an async request will be made to the server and the resources as well as the cache will be * updated when the response is received. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link angular.service.$xhr} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class `save`, `remove` and `delete` actions are available on it as * methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, * update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action(postData, [parameters], [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(); // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$xhr` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server, so one could rewrite the above example as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u){ u.abc = true; u.$save(); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.userId = 'googlebuzz'; this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng:controller="BuzzController"> <input ng:model="userId"/> <button ng:click="fetch()">fetch</button> <hr/> <div ng:repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$resource', function($xhr){ var resource = new ResourceFactory($xhr); return bind(resource, resource.route); }, ['$xhr.cache']); /** * @ngdoc service * @name angular.service.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * @property {Array.<Object>} routes Array of all configured routes. * * @description * Watches `$location.url()` and tries to map the path to an existing route * definition. It is used for deep-linking URLs to controllers and views (HTML partials). * * The `$route` service is typically used in conjunction with {@link angular.widget.ng:view ng:view} * widget and the {@link angular.service.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the <tt>$route</tt> to match a route against the URL, and the <tt>[[ng:include]]</tt> pulls in the partial. <doc:example> <doc:source jsfiddle="false"> <script> function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; $route.when('/Book/:bookId', {template: 'examples/book.html', controller: BookCntl}); $route.when('/Book/:bookId/ch/:chapterId', {template: 'examples/chapter.html', controller: ChapterCntl}); } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </script> <div ng:controller="MainCntl"> Choose: <a href="#/Book/Moby">Moby</a> | <a href="#/Book/Moby/ch/1">Moby: Ch1</a> | <a href="#/Book/Gatsby">Gatsby</a> | <a href="#/Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a><br/> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> <hr /> <ng:view></ng:view> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$route', function($location, $routeParams) { /** * @ngdoc event * @name angular.service.$route#$beforeRouteChange * @eventOf angular.service.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. * * @param {Route} next Future route information. * @param {Route} current Current route information. * * The `Route` object extends the route definition with the following properties. * * * `scope` - The instance of the route controller. * * `params` - The current {@link angular.service.$routeParams params}. * */ /** * @ngdoc event * @name angular.service.$route#$afterRouteChange * @eventOf angular.service.$route * @eventType broadcast on root scope * @description * Broadcasted after a route change. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * * The `Route` object extends the route definition with the following properties. * * * `scope` - The instance of the route controller. * * `params` - The current {@link angular.service.$routeParams params}. * */ /** * @ngdoc event * @name angular.service.$route#$routeUpdate * @eventOf angular.service.$route * @eventType emit on the current route scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var routes = {}, matcher = switchRouteMatcher, parentScope = this, rootScope = this, dirty = 0, forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name angular.service.$route#parent * @methodOf angular.service.$route * * @param {Scope} [scope=rootScope] Scope to be used as parent for newly created * `$route.current.scope` scopes. * * @description * Sets a scope to be used as the parent scope for scopes created on route change. If not * set, defaults to the root scope. */ parent: function(scope) { if (scope) parentScope = scope; }, /** * @ngdoc method * @name angular.service.$route#when * @methodOf angular.service.$route * * @param {string} path Route path (matched against `$location.hash`) * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – path to an html template that should be used by * {@link angular.widget.ng:view ng:view} or * {@link angular.widget.ng:include ng:include} widgets. * - `redirectTo` – {(string|function())=} – value to update * {@link angular.service.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route template. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to false and url in the browser changes, then * $routeUpdate event is emited on the current route scope. You can use this event to * react to {@link angular.service.$routeParams} changes: * * function MyCtrl($route, $routeParams) { * this.$on('$routeUpdate', function() { * // do stuff with $routeParams * }); * } * * @returns {Object} route object * * @description * Adds a new route definition to the `$route` service. */ when: function(path, route) { var routeDef = routes[path]; if (!routeDef) routeDef = routes[path] = {reloadOnSearch: true}; if (route) extend(routeDef, route); // TODO(im): what the heck? merge two route definitions? dirty++; return routeDef; }, /** * @ngdoc method * @name angular.service.$route#otherwise * @methodOf angular.service.$route * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. */ otherwise: function(params) { $route.when(null, params); }, /** * @ngdoc method * @name angular.service.$route#reload * @methodOf angular.service.$route * * @description * Causes `$route` service to reload (and recreate the `$route.current` scope) upon the next * eval even if {@link angular.service.$location $location} hasn't changed. */ reload: function() { dirty++; forceReload = true; } }; this.$watch(function() { return dirty + $location.url(); }, updateRoute); return $route; ///////////////////////////////////////////////////// function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param) { if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current, Controller; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { $route.current = next; copy(next.params, $routeParams); last.scope && last.scope.$emit('$routeUpdate'); } else { forceReload = false; rootScope.$broadcast('$beforeRouteChange', next, last); last && last.scope && last.scope.$destroy(); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } else { copy(next.params, $routeParams); (Controller = next.controller) && inferInjectionArgs(Controller); next.scope = parentScope.$new(Controller); } } rootScope.$broadcast('$afterRouteChange', next, last); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = matcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }, ['$location', '$routeParams']); /** * @ngdoc service * @name angular.service.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link angular.service.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link angular.service.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ angularService('$routeParams', function() { return {}; }); /** * @ngdoc service * @name angular.service.$sniffer * @requires $window * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ angularServiceInject('$sniffer', function($window) { if ($window.Modernizr) return $window.Modernizr; return { history: !!($window.history && $window.history.pushState), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!$window.document.documentMode || $window.document.documentMode > 7) }; }, ['$window']); /** * @ngdoc service * @name angular.service.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng:init="$window = $service('$window'); greeting='Hello World!'" type="text" ng:model="greeting" /> <button ng:click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject("$window", bind(window, identity, window)); /** * @ngdoc service * @name angular.service.$xhr.bulk * @requires $xhr * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } var currentQueue; forEach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; var request = { method: method, url: url, data: post, success: success}; if (error) request.error = error; currentQueue.requests.push(request); } else { $xhr(method, url, post, success, error); } } bulkXHR.urls = {}; bulkXHR.flush = function(success, errorback) { assertArgFn(success = success || noop, 0); assertArgFn(errorback = errorback || noop, 1); forEach(bulkXHR.urls, function(queue, url) { var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests: currentRequests}, function(code, response) { forEach(response, function(response, i) { try { if (response.status == 200) { (currentRequests[i].success || noop)(response.status, response.response); } else if (isFunction(currentRequests[i].error)) { currentRequests[i].error(response.status, response.response); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); success(); }, function(code, response) { forEach(currentRequests, function(request, i) { try { if (isFunction(request.error)) { request.error(code, response); } else { $error(request, response); } } catch(e) { $log.error(e); } }); noop(); }); } }); }; this.$watch(function() { bulkXHR.flush(); }); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']); /** * @ngdoc service * @name angular.service.$xhr.cache * @function * * @requires $xhr.bulk * @requires $defer * @requires $xhr.error * @requires $log * * @description * Acts just like the {@link angular.service.$xhr $xhr} service but caches responses for `GET` * requests. All cache misses are delegated to the $xhr service. * * @property {function()} delegate Function to delegate all the cache misses to. Defaults to * the {@link angular.service.$xhr $xhr} service. * @property {object} data The hashmap where all cached entries are stored. * * @param {string} method HTTP method. * @param {string} url Destination URL. * @param {(string|Object)=} post Request body. * @param {function(number, (string|Object))} success Response success callback. * @param {function(number, (string|Object))=} error Response error callback. * @param {boolean=} [verifyCache=false] If `true` then a result is immediately returned from cache * (if present) while a request is sent to the server for a fresh response that will update the * cached entry. The `success` function will be called when the response is received. * @param {boolean=} [sync=false] in case of cache hit execute `success` synchronously. */ angularServiceInject('$xhr.cache', function($xhr, $defer, $error, $log) { var inflight = {}, self = this; function cache(method, url, post, success, error, verifyCache, sync) { if (isFunction(post)) { if (!isFunction(success)) { verifyCache = success; sync = error; error = null; } else { sync = verifyCache; verifyCache = error; error = success; } success = post; post = null; } else if (!isFunction(error)) { sync = verifyCache; verifyCache = error; error = null; } if (method == 'GET') { var data, dataCached; if ((dataCached = cache.data[url])) { if (sync) { success(200, copy(dataCached.value)); } else { $defer(function() { success(200, copy(dataCached.value)); }); } if (!verifyCache) return; } if ((data = inflight[url])) { data.successes.push(success); data.errors.push(error); } else { inflight[url] = {successes: [success], errors: [error]}; cache.delegate(method, url, post, function(status, response) { if (status == 200) cache.data[url] = {value: response}; var successes = inflight[url].successes; delete inflight[url]; forEach(successes, function(success) { try { (success||noop)(status, copy(response)); } catch(e) { $log.error(e); } }); }, function(status, response) { var errors = inflight[url].errors, successes = inflight[url].successes; delete inflight[url]; forEach(errors, function(error, i) { try { if (isFunction(error)) { error(status, copy(response)); } else { $error( {method: method, url: url, data: post, success: successes[i]}, {status: status, body: response}); } } catch(e) { $log.error(e); } }); }); } } else { cache.data = {}; cache.delegate(method, url, post, success, error); } } cache.data = {}; cache.delegate = $xhr; return cache; }, ['$xhr.bulk', '$defer', '$xhr.error', '$log']); /** * @ngdoc service * @name angular.service.$xhr.error * @function * @requires $log * * @description * Error handler for {@link angular.service.$xhr $xhr service}. An application can replaces this * service with one specific for the application. The default implementation logs the error to * {@link angular.service.$log $log.error}. * * @param {Object} request Request object. * * The object has the following properties * * - `method` – `{string}` – The http request method. * - `url` – `{string}` – The request destination. * - `data` – `{(string|Object)=} – An optional request body. * - `success` – `{function()}` – The success callback function * * @param {Object} response Response object. * * The response object has the following properties: * * - status – {number} – Http status code. * - body – {string|Object} – Body of the response. * * @example <doc:example> <doc:source> fetch a non-existent file and log an error in the console: <button ng:click="$service('$xhr')('GET', '/DOESNT_EXIST')">fetch</button> </doc:source> </doc:example> */ angularServiceInject('$xhr.error', function($log){ return function(request, response){ $log.error('ERROR: XHR: ' + request.url, request, response); }; }, ['$log']); /** * @ngdoc service * @name angular.service.$xhr * @function * @requires $browser $xhr delegates all XHR requests to the `$browser.xhr()`. A mock version * of the $browser exists which allows setting expectations on XHR requests * in your tests * @requires $xhr.error $xhr delegates all non `2xx` response code to this service. * @requires $log $xhr delegates all exceptions to `$log.error()`. * * @description * Generates an XHR request. The $xhr service delegates all requests to * {@link angular.service.$browser $browser.xhr()} and adds error handling and security features. * While $xhr service provides nicer api than raw XmlHttpRequest, it is still considered a lower * level api in angular. For a higher level abstraction that utilizes `$xhr`, please check out the * {@link angular.service.$resource $resource} service. * * # Error handling * If no `error callback` is specified, XHR response with response code other then `2xx` will be * delegated to {@link angular.service.$xhr.error $xhr.error}. The `$xhr.error` can intercept the * request and process it in application specific way, or resume normal execution by calling the * request `success` method. * * # HTTP Headers * The $xhr service will automatically add certain http headers to all requests. These defaults can * be fully configured by accessing the `$xhr.defaults.headers` configuration object, which * currently contains this default configuration: * * - `$xhr.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, *\/*` * - `X-Requested-With: XMLHttpRequest` * - `$xhr.defaults.headers.post` (header defaults for HTTP POST requests): * - `Content-Type: application/x-www-form-urlencoded` * * To add or overwrite these defaults, simple add or remove a property from this configuration * object. To add headers for an HTTP method other than POST, simple create a new object with name * equal to the lowercased http method name, e.g. `$xhr.defaults.headers.get['My-Header']='value'`. * * * # Security Considerations * When designing web applications your design needs to consider security threats from * {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} and {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}. * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which an * unauthorized site can gain your user's private data. Angular provides following mechanism to * counter XSRF. When performing XHR requests, the $xhr service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the server * can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure that only * JavaScript running on your domain could have read the token. The token must be unique for each * user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). * We recommend that the token is a digest of your site's authentication cookie with * {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * @param {string} method HTTP method to use. Valid values are: `GET`, `POST`, `PUT`, `DELETE`, and * `JSON`. `JSON` is a special case which causes a * [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP) cross domain request using script tag * insertion. * @param {string} url Relative or absolute URL specifying the destination of the request. For * `JSON` requests, `url` should include `JSON_CALLBACK` string to be replaced with a name of an * angular generated callback function. * @param {(string|Object)=} post Request content as either a string or an object to be stringified * as JSON before sent to the server. * @param {function(number, (string|Object))} success A function to be called when the response is * received. The success function will be called with: * * - {number} code [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) of * the response. This will currently always be 200, since all non-200 responses are routed to * {@link angular.service.$xhr.error} service (or custom error callback). * - {string|Object} response Response object as string or an Object if the response was in JSON * format. * @param {function(number, (string|Object))} error A function to be called if the response code is * not 2xx.. Accepts the same arguments as success, above. * * @example <doc:example> <doc:source jsfiddle="false"> <script> function FetchCntl($xhr) { var self = this; this.url = 'index.html'; this.fetch = function() { self.code = null; self.response = null; $xhr(self.method, self.url, function(code, response) { self.code = code; self.response = response; }, function(code, response) { self.code = code; self.response = response || "Request failed"; }); }; this.updateModel = function(method, url) { self.method = method; self.url = url; }; } FetchCntl.$inject = ['$xhr']; </script> <div ng:controller="FetchCntl"> <select ng:model="method"> <option>GET</option> <option>JSON</option> </select> <input type="text" ng:model="url" size="80"/> <button ng:click="fetch()">fetch</button><br> <button ng:click="updateModel('GET', 'index.html')">Sample GET</button> <button ng:click="updateModel('JSON', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng:click="updateModel('JSON', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>code={{code}}</pre> <pre>response={{response}}</pre> </div> </doc:source> <doc:scenario> it('should make xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code=200'); expect(binding('response')).toMatch(/angularjs.org/); }); it('should make JSONP request to the angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code=200'); expect(binding('response')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code='); expect(binding('response')).toBe('response=Request failed'); }); </doc:scenario> </doc:example> */ angularServiceInject('$xhr', function($browser, $error, $log){ var rootScope = this; var xhrHeaderDefaults = { common: { "Accept": "application/json, text/plain, */*", "X-Requested-With": "XMLHttpRequest" }, post: {'Content-Type': 'application/x-www-form-urlencoded'}, get: {}, // all these empty properties are needed so that client apps can just do: head: {}, // $xhr.defaults.headers.head.foo="bar" without having to create head object put: {}, // it also means that if we add a header for these methods in the future, it 'delete': {}, // won't be easily silently lost due to an object assignment. patch: {} }; function xhr(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } if (post && isObject(post)) { post = toJson(post); } $browser.xhr(method, url, post, function(code, response){ try { if (isString(response)) { if (response.match(/^\)\]\}',\n/)) response=response.substr(6); if (/^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { response = fromJson(response, true); } } rootScope.$apply(function() { if (200 <= code && code < 300) { success(code, response); } else if (isFunction(error)) { error(code, response); } else { $error( {method: method, url: url, data: post, success: success}, {status: code, body: response}); } }); } catch (e) { $log.error(e); } }, extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, xhrHeaderDefaults.common, xhrHeaderDefaults[lowercase(method)])); } xhr.defaults = {headers: xhrHeaderDefaults}; return xhr; }, ['$browser', '$xhr.error', '$log']); /** * @ngdoc service * @name angular.service.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ angularServiceInject('$locale', function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }); /** * @ngdoc overview * @name angular.directive * @description * * Angular directives create custom attributes for DOM elements. A directive can modify the * behavior of the element in which it is specified. Do not use directives to add elements to the * DOM; instead, use {@link angular.widget widgets} to add DOM elements. * * Following is the list of built-in Angular directives: * * * {@link angular.directive.ng:autobind ng:autobind} - An Angular bootstrap parameter that can * act as a directive. * * {@link angular.directive.ng:bind ng:bind} - Creates a data-binding between an HTML text value * and a data model. * * {@link angular.directive.ng:bind-attr ng:bind-attr} - Creates a data-binding in a way similar * to `ng:bind`, but uses JSON key / value pairs to do so. * * {@link angular.directive.ng:bind-template ng:bind-template} - Replaces the text value of an * element with a specified template. * * {@link angular.directive.ng:class ng:class} - Conditionally set a CSS class on an element. * * {@link angular.directive.ng:class-even ng:class-even} - Like `ng:class`, but works in * conjunction with {@link angular.widget.@ng:repeat} to affect even rows in a collection. * * {@link angular.directive.ng:class-odd ng:class-odd} - Like `ng:class`, but works with {@link * angular.widget.@ng:repeat} to affect odd rows. * * {@link angular.directive.ng:click ng:click} - Executes custom behavior when an element is * clicked. * * {@link angular.directive.ng:controller ng:controller} - Creates a scope object linked to the * DOM element and assigns behavior to the scope. * * {@link angular.directive.ng:hide ng:hide} - Conditionally hides a portion of HTML. * * {@link angular.directive.ng:href ng:href} - Places an href in the Angular namespace. * * {@link angular.directive.ng:init} - Initialization tasks run before a template is executed. * * {@link angular.directive.ng:show ng:show} - Conditionally displays a portion of HTML. * * {@link angular.directive.ng:src ng:src} - Places a `src` attribute into the Angular namespace. * * {@link angular.directive.ng:style ng:style} - Conditionally set CSS styles on an element. * * {@link angular.directive.ng:submit} - Binds Angular expressions to `onSubmit` events. * * For more information about how Angular directives work, and to learn how to create your own * directives, see {@link guide/dev_guide.compiler.directives Understanding Angular Directives} in * the Angular Developer Guide. */ /** * @ngdoc directive * @name angular.directive.ng:init * * @description * The `ng:init` attribute specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <div ng:init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ angularDirective("ng:init", function(expression){ return function(element){ this.$eval(expression); }; }); /** * @ngdoc directive * @name angular.directive.ng:controller * * @description * The `ng:controller` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ng:controller` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link angular.service.$route}` * service. * * @element ANY * @param {expression} expression Name of a globally accessible constructor function or an * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script type="text/javascript"> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; } SettingsController.prototype = { greet: function() { alert(this.name); }, addContact: function() { this.contacts.push({type:'email', value:'yourname@example.org'}); }, removeContact: function(contactToRemove) { angular.Array.remove(this.contacts, contactToRemove); }, clearContact: function(contact) { contact.type = 'phone'; contact.value = ''; } }; </script> <div ng:controller="SettingsController"> Name: <input type="text" ng:model="name"/> [ <a href="" ng:click="greet()">greet</a> ]<br/> Contact: <ul> <li ng:repeat="contact in contacts"> <select ng:model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng:model="contact.value"/> [ <a href="" ng:click="clearContact(contact)">clear</a> | <a href="" ng:click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng:click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ angularDirective("ng:controller", function(expression){ this.scope(function(scope){ var Controller = getter(scope, expression, true) || getter(window, expression, true); assertArgFn(Controller, expression); inferInjectionArgs(Controller); return Controller; }); return noop; }); /** * @ngdoc directive * @name angular.directive.ng:bind * * @description * The `ng:bind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ng:bind` directly, but instead you use the double curly markup like * `{{ expression }}` and let the Angular compiler transform it to * `<span ng:bind="expression"></span>` when the template is compiled. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl() { this.name = 'Whirled'; } </script> <div ng:controller="Ctrl"> Enter name: <input type="text" ng:model="name"> <br/> Hello <span ng:bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng:bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind", function(expression, element){ element.addClass('ng-binding'); var exprFn = parser(expression).statements(); return function(element) { var lastValue = Number.NaN; this.$watch(function(scope) { // TODO(misko): remove error handling https://github.com/angular/angular.js/issues/347 var value, html, isHtml, isDomElement, hadOwnElement = scope.hasOwnProperty('$element'), oldElement = scope.$element; // TODO(misko): get rid of $element https://github.com/angular/angular.js/issues/348 scope.$element = element; try { value = exprFn(scope); // If we are HTML than save the raw HTML data so that we don't recompute sanitization since // it is expensive. // TODO(misko): turn this into a more generic way to compute this if ((isHtml = (value instanceof HTML))) value = (html = value).html; if (lastValue === value) return; isDomElement = isElement(value); if (!isHtml && !isDomElement && isObject(value)) { value = toJson(value, true); } if (value != lastValue) { lastValue = value; if (isHtml) { element.html(html.get()); } else if (isDomElement) { element.html(''); element.append(value); } else { element.text(value == undefined ? '' : value); } } } catch (e) { scope.$service('$exceptionHandler')(e); } finally { if (hadOwnElement) { scope.$element = oldElement; } else { delete scope.$element; } } }); }; }); var bindTemplateCache = {}; function compileBindTemplate(template){ var fn = bindTemplateCache[template]; if (!fn) { var bindings = []; forEach(parseBindings(template), function(text){ var exp = binding(text); bindings.push(exp ? function(scope, element) { return scope.$eval(exp); } : function() { return text; }); }); bindTemplateCache[template] = fn = function(scope, element, prettyPrintJson) { var parts = [], hadOwnElement = scope.hasOwnProperty('$element'), oldElement = scope.$element; // TODO(misko): get rid of $element scope.$element = element; try { for (var i = 0; i < bindings.length; i++) { var value = bindings[i](scope, element); if (isElement(value)) value = ''; else if (isObject(value)) value = toJson(value, prettyPrintJson); parts.push(value); } return parts.join(''); } finally { if (hadOwnElement) { scope.$element = oldElement; } else { delete scope.$element; } } }; } return fn; } /** * @ngdoc directive * @name angular.directive.ng:bind-template * * @description * The `ng:bind-template` attribute specifies that the element * text should be replaced with the template in ng:bind-template. * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl() { this.salutation = 'Hello'; this.name = 'World'; } </script> <div ng:controller="Ctrl"> Salutation: <input type="text" ng:model="salutation"><br/> Name: <input type="text" ng:model="name"><br/> <pre ng:bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng:bind', function() { expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Hello World!'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Greetings user!'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-template", function(expression, element){ element.addClass('ng-binding'); var templateFn = compileBindTemplate(expression); return function(element) { var lastValue; this.$watch(function(scope) { var value = templateFn(scope, element, true); if (value != lastValue) { element.text(value); lastValue = value; } }); }; }); /** * @ngdoc directive * @name angular.directive.ng:bind-attr * * @description * The `ng:bind-attr` attribute specifies that a * {@link guide/dev_guide.templates.databinding databinding} should be created between a particular * element attribute and a given expression. Unlike `ng:bind`, the `ng:bind-attr` contains one or * more JSON key value pairs; each pair specifies an attribute and the * {@link guide/dev_guide.expressions expression} to which it will be mapped. * * Instead of writing `ng:bind-attr` statements in your HTML, you can use double-curly markup to * specify an <tt ng:non-bindable>{{expression}}</tt> for the value of an attribute. * At compile time, the attribute is translated into an `<span ng:bind-attr="{attr:expression}"/>` * * The following HTML snippet shows how to specify `ng:bind-attr`: * <pre> * <a href="http://www.google.com/search?q={{query}}">Google</a> * </pre> * * During compilation, the snippet gets translated to the following: * <pre> * <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a> * </pre> * * @element ANY * @param {string} attribute_json one or more JSON key-value pairs representing * the attributes to replace with expressions. Each key matches an attribute * which needs to be replaced. Each value is a text template of * the attribute with the embedded * <tt ng:non-bindable>{{expression}}</tt>s. Any number of * key-value pairs can be specified. * * @example * Enter a search string in the Live Preview text box and then click "Google". The search executes instantly. <doc:example> <doc:source> <script> function Ctrl() { this.query = 'AngularJS'; } </script> <div ng:controller="Ctrl"> Google for: <input type="text" ng:model="query"/> <a href="http://www.google.com/search?q={{query}}">Google</a> </div> </doc:source> <doc:scenario> it('should check ng:bind-attr', function() { expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-attr", function(expression){ return function(element){ var lastValue = {}; this.$watch(function(scope){ var values = scope.$eval(expression); for(var key in values) { var value = compileBindTemplate(values[key])(scope, element); if (lastValue[key] !== value) { lastValue[key] = value; element.attr(key, BOOLEAN_ATTR[lowercase(key)] ? toBoolean(value) : value); } } }); }; }); /** * @ngdoc directive * @name angular.directive.ng:click * * @description * The ng:click allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon * click. * * @example <doc:example> <doc:source> <button ng:click="count = count + 1" ng:init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng:click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. * * TODO: maybe we should consider allowing users to control event propagation in the future. */ angularDirective("ng:click", function(expression, element){ return function(element){ var self = this; element.bind('click', function(event){ self.$apply(expression); event.stopPropagation(); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:submit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.list = []; this.text = 'hello'; this.submit = function() { this.list.push(this.text); this.text = ''; }; } </script> <form ng:submit="submit()" ng:controller="Ctrl"> Enter text and hit enter: <input type="text" ng:model="text"/> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng:submit', function() { expect(binding('list')).toBe('list=[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('list=["hello"]'); }); </doc:scenario> </doc:example> */ angularDirective("ng:submit", function(expression, element) { return function(element) { var self = this; element.bind('submit', function(event) { self.$apply(expression); event.preventDefault(); }); }; }); function ngClass(selector) { return function(expression, element) { return function(element) { this.$watch(expression, function(scope, newVal, oldVal) { if (selector(scope.$index)) { if (oldVal) element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal); if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); } }); }; }; } /** * @ngdoc directive * @name angular.directive.ng:class * * @description * The `ng:class` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the classes * new classes are added. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'"> <input type="button" value="clear" ng:click="myVar=''"> <br> <span ng:class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> </doc:source> <doc:scenario> it('should check ng:class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class", ngClass(function() {return true;})); /** * @ngdoc directive * @name angular.directive.ng:class-odd * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * {@link angular.directive.ng:class ng:class}, except it works in conjunction with `ng:repeat` and * takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.widget.@ng:repeat ng:repeat}. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;})); /** * @ngdoc directive * @name angular.directive.ng:class-even * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * {@link angular.directive.ng:class ng:class}, except it works in conjunction with `ng:repeat` and * takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.widget.@ng:repeat ng:repeat}. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;})); /** * @ngdoc directive * @name angular.directive.ng:show * * @description * The `ng:show` and `ng:hide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng:model="checked"><br/> Show: <span ng:show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng:hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:show", function(expression, element){ return function(element){ this.$watch(expression, function(scope, value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:hide * * @description * The `ng:hide` and `ng:show` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng:model="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:hide", function(expression, element){ return function(element){ this.$watch(expression, function(scope, value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:style * * @description * The ng:style allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myStyle={color:'red'}"> <input type="button" value="clear" ng:click="myStyle={}"> <br/> <span ng:style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </doc:source> <doc:scenario> it('should check ng:style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </doc:scenario> </doc:example> */ angularDirective("ng:style", function(expression, element){ // TODO(i): this is inefficient (runs on every $digest) and obtrusive (overrides 3rd part css) // we should change it in a similar way as I changed ng:class return function(element){ var resetStyle = getStyle(element); this.$watch(function(scope){ var style = scope.$eval(expression) || {}, key, mergedStyle = {}; for(key in style) { if (resetStyle[key] === undefined) resetStyle[key] = ''; mergedStyle[key] = style[key]; } for(key in resetStyle) { mergedStyle[key] = mergedStyle[key] || resetStyle[key]; } element.css(mergedStyle); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:cloak * * @description * The `ng:cloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ng:cloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng:cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ng:cloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ng-cloak` in addition to `ng:cloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng:cloak>{{ 'hello' }}</div> <div id="template2" ng:cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng:cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng:cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ angularDirective("ng:cloak", function(expression, element) { element.removeAttr('ng:cloak'); element.removeClass('ng-cloak'); }); /** * @ngdoc overview * @name angular.markup * @description * * Angular markup transforms the content of DOM elements or portions of the content into other * text or DOM elements for further compilation. * * Markup extensions do not themselves produce linking functions. Think of markup as a way to * produce shorthand for a {@link angular.widget widget} or a {@link angular.directive directive}. * * The most prominent example of a markup in Angular is the built-in, double curly markup * `{{expression}}`, which is shorthand for `<span ng:bind="expression"></span>`. * * Create custom markup like this: * * <pre> * angular.markup('newMarkup', function(text, textNode, parentElement){ * //tranformation code * }); * </pre> * * For more information, see {@link guide/dev_guide.compiler.markup Understanding Angular Markup} * in the Angular Developer Guide. */ /** * @ngdoc overview * @name angular.attrMarkup * @description * * Attribute markup allows you to modify the state of an attribute's text. * * Attribute markup extends the Angular complier in a way similar to {@link angular.markup}, * which allows you to modify the content of a node. * * The most prominent example of an attribute markup in Angular is the built-in double curly markup * which is a shorthand for {@link angular.directive.ng:bind-attr ng:bind-attr}. * * ## Example * * <pre> * angular.attrMarkup('newAttrMarkup', function(attrValue, attrName, element){ * //tranformation code * }); * </pre> * * For more information about Angular attribute markup, see {@link guide/dev_guide.compiler.markup * Understanding Angular Markup} in the Angular Developer Guide. */ function parseBindings(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; } function binding(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : null; } function hasBindings(bindings) { return bindings.length > 1 || binding(bindings[0]) !== null; } angularTextMarkup('{{}}', function(text, textNode, parentElement) { var bindings = parseBindings(text), self = this; if (hasBindings(bindings)) { if (isLeafNode(parentElement[0])) { parentElement.attr('ng:bind-template', text); } else { var cursor = textNode, newElement; forEach(parseBindings(text), function(text){ var exp = binding(text); if (exp) { newElement = jqLite('<span>'); newElement.attr('ng:bind', exp); } else { newElement = jqLite(document.createTextNode(text)); } if (msie && text.charAt(0) == ' ') { newElement = jqLite('<span>&nbsp;</span>'); var nbsp = newElement.html(); newElement.text(text.substr(1)); newElement.html(nbsp + newElement.html()); } cursor.after(newElement); cursor = newElement; }); textNode.remove(); } } }); /** * This tries to normalize the behavior of value attribute across browsers. If value attribute is * not specified, then specify it to be that of the text. */ angularTextMarkup('option', function(text, textNode, parentElement){ if (lowercase(nodeName_(parentElement)) == 'option') { if (msie <= 7) { // In IE7 The issue is that there is no way to see if the value was specified hence // we have to resort to parsing HTML; htmlParser(parentElement[0].outerHTML, { start: function(tag, attrs) { if (isUndefined(attrs.value)) { parentElement.attr('value', text); } } }); } else if (parentElement[0].getAttribute('value') == null) { // jQuery does normalization on 'value' so we have to bypass it. parentElement.attr('value', text); } } }); /** * @ngdoc directive * @name angular.directive.ng:href * * @description * Using <angular/> markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ng:href` solves this problem by placing the `href` in the * `ng:` namespace. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng:href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng:model="value" /><br /> <a id="link-1" href ng:click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng:click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng:href="/{{'123'}}" ng:ext-link>link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng:click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng:click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng:href="/{{value}}" ng:ext-link>link</a> (link, change hash) </doc:source> <doc:scenario> it('should execute ng:click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng:click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng:click and change url when ng:href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().location().path()).toEqual('/123'); }); it('should execute ng:click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(""); }); it('should execute ng:click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng:href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe("/6"); element('#link-6').click(); expect(browser().location().path()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name angular.directive.ng:src * * @description * Using <angular/> markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until <angular/> replaces the expression inside * `{{hash}}`. The `ng:src` attribute solves this problem by placing * the `src` attribute in the `ng:` namespace. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng:src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name angular.directive.ng:disabled * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng:init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:disabled. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng:model="checked"><br/> <button ng:model="button" ng:disabled="{{checked}}">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @ngdoc directive * @name angular.directive.ng:checked * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:checked. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng:model="master"><br/> <input id="checkSlave" type="checkbox" ng:checked="{{master}}"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @ngdoc directive * @name angular.directive.ng:multiple * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:multiple. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng:model="checked"><br/> <select id="select" ng:multiple="{{checked}}"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @ngdoc directive * @name angular.directive.ng:readonly * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:readonly. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng:model="checked"><br/> <input type="text" ng:readonly="{{checked}}" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @ngdoc directive * @name angular.directive.ng:selected * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:selected. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng:model="checked"><br/> <select> <option>Hello!</option> <option id="greet" ng:selected="{{checked}}">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ var NG_BIND_ATTR = 'ng:bind-attr'; var SIDE_EFFECT_ATTRS = {}; forEach('src,href,multiple,selected,checked,disabled,readonly,required'.split(','), function(name) { SIDE_EFFECT_ATTRS['ng:' + name] = name; }); angularAttrMarkup('{{}}', function(value, name, element){ // don't process existing attribute markup if (angularDirective(name) || angularDirective("@" + name)) return; if (msie && name == 'src') value = decodeURI(value); var bindings = parseBindings(value), bindAttr; if (hasBindings(bindings) || SIDE_EFFECT_ATTRS[name]) { element.removeAttr(name); bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}"); bindAttr[SIDE_EFFECT_ATTRS[name] || name] = value; element.attr(NG_BIND_ATTR, toJson(bindAttr)); } }); /** * @ngdoc overview * @name angular.widget * @description * * An angular widget can be either a custom attribute that modifies an existing DOM element or an * entirely new DOM element. * * During html compilation, widgets are processed after {@link angular.markup markup}, but before * {@link angular.directive directives}. * * Following is the list of built-in angular widgets: * * * {@link angular.widget.@ng:non-bindable ng:non-bindable} - Blocks angular from processing an * HTML element. * * {@link angular.widget.@ng:repeat ng:repeat} - Creates and manages a collection of cloned HTML * elements. * * {@link angular.inputType HTML input elements} - Standard HTML input elements data-bound by * angular. * * {@link angular.widget.ng:view ng:view} - Works with $route to "include" partial templates * * {@link angular.widget.ng:switch ng:switch} - Conditionally changes DOM structure * * {@link angular.widget.ng:include ng:include} - Includes an external HTML fragment * * For more information about angular widgets, see {@link guide/dev_guide.compiler.widgets * Understanding Angular Widgets} in the angular Developer Guide. */ /** * @ngdoc widget * @name angular.widget.ng:include * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ng:include won't work for file:// access). * * @param {string} src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {Scope=} [scope=new_child_scope] optional expression which evaluates to an * instance of angular.scope to set the HTML fragment to. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @example <doc:example> <doc:source jsfiddle="false"> <script> function Ctrl() { this.templates = [ { name: 'template1.html', url: 'examples/ng-include/template1.html'} , { name: 'template2.html', url: 'examples/ng-include/template2.html'} ]; this.template = this.templates[0]; } </script> <div ng:controller="Ctrl"> <select ng:model="template" ng:options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt><a href="{{template.url}}">{{template.url}}</a></tt> <hr/> <ng:include src="template.url"></ng:include> </div> </doc:source> <doc:scenario> it('should load template1.html', function() { expect(element('.doc-example-live .ng-include').text()). toBe('Content of template1.html\n'); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live .ng-include').text()). toBe('Content of template2.html\n'); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live .ng-include').text()).toEqual(''); }); </doc:scenario> </doc:example> */ angularWidget('ng:include', function(element){ var compiler = this, srcExp = element.attr("src"), scopeExp = element.attr("scope") || '', onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537 if (element[0]['ng:compiled']) { this.descend(true); this.directives(true); } else { element[0]['ng:compiled'] = true; return extend(function(xhr, element){ var scope = this, changeCounter = 0, releaseScopes = [], childScope, oldScope; function incrementChange() { changeCounter++;} this.$watch(srcExp, incrementChange); this.$watch(function(scope){ var newScope = scope.$eval(scopeExp); if (newScope !== oldScope) { oldScope = newScope; incrementChange(); } }); this.$watch(function() {return changeCounter;}, function(scope) { var src = scope.$eval(srcExp), useScope = scope.$eval(scopeExp); while(releaseScopes.length) { releaseScopes.pop().$destroy(); } if (src) { xhr('GET', src, null, function(code, response){ element.html(response); if (useScope) { childScope = useScope; } else { releaseScopes.push(childScope = scope.$new()); } compiler.compile(element)(childScope); scope.$eval(onloadExp); }, false, true); } else { childScope = null; element.html(''); } }); }, {$inject:['$xhr.cache']}); } }); /** * @ngdoc widget * @name angular.widget.ng:switch * * @description * Conditionally change the DOM structure. * * @usageContent * <any ng:switch-when="matchValue1">...</any> * <any ng:switch-when="matchValue2">...</any> * ... * <any ng:switch-default>...</any> * * @param {*} on expression to match against <tt>ng:switch-when</tt>. * @paramDescription * On child elments add: * * * `ng:switch-when`: the case statement to match against. If match then this * case will be displayed. * * `ng:switch-default`: the default case when no other casses match. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.items = ['settings', 'home', 'other']; this.selection = this.items[0]; } </script> <div ng:controller="Ctrl"> <select ng:model="selection" ng:options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <ng:switch on="selection" > <div ng:switch-when="settings">Settings Div</div> <span ng:switch-when="home">Home Span</span> <span ng:switch-default>default</span> </ng:switch> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live ng\\:switch').text()).toEqual('Settings Div'); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('Home Span'); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('default'); }); </doc:scenario> </doc:example> */ angularWidget('ng:switch', function(element) { var compiler = this, watchExpr = element.attr("on"), changeExpr = element.attr('change'), casesTemplate = {}, defaultCaseTemplate, children = element.children(), length = children.length, child, when; if (!watchExpr) throw new Error("Missing 'on' attribute."); while(length--) { child = jqLite(children[length]); // this needs to be here for IE child.remove(); when = child.attr('ng:switch-when'); if (isString(when)) { casesTemplate[when] = compiler.compile(child); } else if (isString(child.attr('ng:switch-default'))) { defaultCaseTemplate = compiler.compile(child); } } children = null; // release memory; element.html(''); return function(element){ var changeCounter = 0; var childScope; var selectedTemplate; this.$watch(watchExpr, function(scope, value) { element.html(''); if ((selectedTemplate = casesTemplate[value] || defaultCaseTemplate)) { changeCounter++; if (childScope) childScope.$destroy(); childScope = scope.$new(); childScope.$eval(changeExpr); } }); this.$watch(function() {return changeCounter;}, function() { element.html(''); if (selectedTemplate) { selectedTemplate(childScope, function(caseElement) { element.append(caseElement); }); } }); }; }); /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with ng:click without * changing the location or causing page reloads, e.g.: * <a href="" ng:click="model.$save()">Save</a> */ angularWidget('a', function() { this.descend(true); this.directives(true); return function(element) { var hasNgHref = ((element.attr('ng:bind-attr') || '').indexOf('"href":') !== -1); // turn <a href ng:click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!hasNgHref && !element.attr('name') && !element.attr('href')) { element.attr('href', ''); } if (element.attr('href') === '' && !hasNgHref) { element.bind('click', function(event){ event.preventDefault(); }); } }; }); /** * @ngdoc widget * @name angular.widget.@ng:repeat * * @description * The `ng:repeat` widget instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$position` – `{string}` – position of the repeated element in the iterator. One of: * * `'first'`, * * `'middle'` * * `'last'` * * Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget. * * @element ANY * @param {string} repeat_expression The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ng:repeat` to display every person: <doc:example> <doc:source> <div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng:repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng:repeat', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ angularWidget('@ng:repeat', function(expression, element){ element.removeAttr('ng:repeat'); element.replaceWith(jqLite('<!-- ng:repeat: ' + expression + ' -->')); var linker = this.compile(element); return function(iterStartElement){ var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ng:repeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + keyValue + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; var parentScope = this; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is an array of objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // We need an array of these objects since the same object can be returned from the iterator. // We expect this to be a rare case. var lastOrder = new HashQueueMap(); this.$watch(function(scope){ var index = 0, collection = scope.$eval(rhs), collectionLength = size(collection, true), childScope, // Same as lastOrder but it has the current state. It will become the // lastOrder on the next iteration. nextOrder = new HashQueueMap(), key, value, // key/value of iteration array, last, // last object information {scope, element, index} cursor = iterStartElement; // current position of the node for (key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { last = lastOrder.shift(value = collection[key]); if (last) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = last.scope; nextOrder.push(value, last); if (index === last.index) { // do nothing cursor = last.element; } else { // existing item which got moved last.index = index; // This may be a noop, if the element is next, but I don't know of a good way to // figure this out, since it would require extra DOM access, so let's just hope that // the browsers realizes that it is noop, and treats it as such. cursor.after(last.element); cursor = last.element; } } else { // new item which we don't know about childScope = parentScope.$new(); } childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); if (!last) { linker(childScope, function(clone){ cursor.after(clone); last = { scope: childScope, element: (cursor = clone), index: index }; nextOrder.push(value, last); }); } index ++; } } //shrink children for (key in lastOrder) { if (lastOrder.hasOwnProperty(key)) { array = lastOrder[key]; while(array.length) { value = array.pop(); value.element.remove(); value.scope.$destroy(); } } } lastOrder = nextOrder; }); }; }); /** * @ngdoc widget * @name angular.widget.@ng:non-bindable * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML. * * Note: `ng:non-bindable` looks like a directive, but is actually an attribute widget. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ng:non-bindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng:non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng:non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ angularWidget("@ng:non-bindable", noop); /** * @ngdoc widget * @name angular.widget.ng:view * * @description * # Overview * `ng:view` is a widget that complements the {@link angular.service.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when * used like this: * * <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include> * * * # Advantages * Compared to `ng:include`, `ng:view` offers these advantages: * * - shorter syntax * - more efficient execution * - doesn't require `$route` service to be available on the root scope * * * @example <doc:example> <doc:source jsfiddle="false"> <script> function MyCtrl($route) { $route.when('/overview', { controller: OverviewCtrl, template: 'partials/guide/dev_guide.overview.html'}); $route.when('/bootstrap', { controller: BootstrapCtrl, template: 'partials/guide/dev_guide.bootstrap.auto_bootstrap.html'}); }; MyCtrl.$inject = ['$route']; function BootstrapCtrl() {} function OverviewCtrl() {} </script> <div ng:controller="MyCtrl"> <a href="overview">overview</a> | <a href="bootstrap">bootstrap</a> | <a href="undefined">undefined</a> <br/> The view is included below: <hr/> <ng:view></ng:view> </div> </doc:source> <doc:scenario> it('should load templates', function() { element('.doc-example-live a:contains(overview)').click(); expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Overview/); element('.doc-example-live a:contains(bootstrap)').click(); expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Initializing Angular: Automatic Initialization/); }); </doc:scenario> </doc:example> */ angularWidget('ng:view', function(element) { var compiler = this; if (!element[0]['ng:compiled']) { element[0]['ng:compiled'] = true; return annotate('$xhr.cache', '$route', function($xhr, $route, element){ var template; var changeCounter = 0; this.$on('$afterRouteChange', function() { changeCounter++; }); this.$watch(function() {return changeCounter;}, function() { var template = $route.current && $route.current.template; if (template) { //xhr's callback must be async, see commit history for more info $xhr('GET', template, function(code, response) { element.html(response); compiler.compile(element)($route.current.scope); }); } else { element.html(''); } }); }); } else { compiler.descend(true); compiler.directives(true); } }); /** * @ngdoc widget * @name angular.widget.ng:pluralize * * @description * # Overview * ng:pluralize is a widget that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/dev_guide.i18n Angular i18n} dev guide). You configure ng:pluralize by * specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ng:pluralize * You configure ng:pluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/dev_guide.expressions * Angular expression}; these are evaluated on the current scope for its binded value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ng:pluralize: * * <pre> * <ng:pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng:pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng:non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng:non-bindable>{{numberExpression}}</span>. * * # Configuring ng:pluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng:pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng:pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.person1 = 'Igor'; this.person2 = 'Misko'; this.personCount = 1; } </script> <div ng:controller="Ctrl"> Person 1:<input type="text" ng:model="person1" value="Igor" /><br/> Person 2:<input type="text" ng:model="person2" value="Misko" /><br/> Number of People:<input type="text" ng:model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng:pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng:pluralize><br> <!--- Example with offset ---> With Offset(2): <ng:pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng:pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ angularWidget('ng:pluralize', function(element) { var numberExp = element.attr('count'), whenExp = element.attr('when'), offset = element.attr('offset') || 0; return annotate('$locale', function($locale, element) { var scope = this, whens = scope.$eval(whenExp), whensExpFns = {}; forEach(whens, function(expression, key) { whensExpFns[key] = compileBindTemplate(expression.replace(/{}/g, '{{' + numberExp + '-' + offset + '}}')); }); scope.$watch(function() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function(scope, newVal) { element.text(newVal); }); }); }); /** * @ngdoc widget * @name angular.widget.form * * @description * Angular widget that creates a form scope using the * {@link angular.service.$formFactory $formFactory} API. The resulting form scope instance is * attached to the DOM element using the jQuery `.data()` method under the `$form` key. * See {@link guide/dev_guide.forms forms} on detailed discussion of forms and widgets. * * * # Alias: `ng:form` * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides `<ng:form>` alias which behaves identical to `<form>` but allows * element nesting. * * * @example <doc:example> <doc:source> <script> function Ctrl() { this.text = 'guest'; } </script> <div ng:controller="Ctrl"> <form name="myForm"> text: <input type="text" name="input" ng:model="text" required> <span class="error" ng:show="myForm.text.$error.REQUIRED">Required!</span> </form> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularWidget('form', function(form){ this.descend(true); this.directives(true); return annotate('$formFactory', function($formFactory, formElement) { var name = formElement.attr('name'), parentForm = $formFactory.forElement(formElement), form = $formFactory(parentForm); formElement.data('$form', form); formElement.bind('submit', function(event){ event.preventDefault(); }); if (name) { this[name] = form; } watch('valid'); watch('invalid'); function watch(name) { form.$watch('$' + name, function(scope, value) { formElement[value ? 'addClass' : 'removeClass']('ng-' + name); }); } }); }); angularWidget('ng:form', angularWidget('form')); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var INTEGER_REGEXP = /^\s*(\-|\+)?\d+\s*$/; /** * @ngdoc inputType * @name angular.inputType.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.text = 'guest'; this.word = /^\w*$/; } </script> <div ng:controller="Ctrl"> <form name="myForm"> Single word: <input type="text" name="input" ng:model="text" ng:pattern="word" required> <span class="error" ng:show="myForm.input.$error.REQUIRED"> Required!</span> <span class="error" ng:show="myForm.input.$error.PATTERN"> Single word only!</span> </form> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ /** * @ngdoc inputType * @name angular.inputType.email * * @description * Text input with email validation. Sets the `EMAIL` validation error key if not a valid email * address. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.text = 'me@example.com'; } </script> <div ng:controller="Ctrl"> <form name="myForm"> Email: <input type="email" name="input" ng:model="text" required> <span class="error" ng:show="myForm.input.$error.REQUIRED"> Required!</span> <span class="error" ng:show="myForm.input.$error.EMAIL"> Not valid email!</span> </form> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> <tt>myForm.$error.EMAIL = {{!!myForm.$error.EMAIL}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('me@example.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('text')).toEqual('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularInputType('email', function() { var widget = this; this.$on('$validate', function(event){ var value = widget.$viewValue; widget.$emit(!value || value.match(EMAIL_REGEXP) ? "$valid" : "$invalid", "EMAIL"); }); }); /** * @ngdoc inputType * @name angular.inputType.url * * @description * Text input with URL validation. Sets the `URL` validation error key if the content is not a * valid URL. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.text = 'http://google.com'; } </script> <div ng:controller="Ctrl"> <form name="myForm"> URL: <input type="url" name="input" ng:model="text" required> <span class="error" ng:show="myForm.input.$error.REQUIRED"> Required!</span> <span class="error" ng:show="myForm.input.$error.url"> Not valid url!</span> </form> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('text')).toEqual('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularInputType('url', function() { var widget = this; this.$on('$validate', function(event){ var value = widget.$viewValue; widget.$emit(!value || value.match(URL_REGEXP) ? "$valid" : "$invalid", "URL"); }); }); /** * @ngdoc inputType * @name angular.inputType.list * * @description * Text input that converts between comma-seperated string into an array of strings. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.names = ['igor', 'misko', 'vojta']; } </script> <div ng:controller="Ctrl"> <form name="myForm"> List: <input type="list" name="input" ng:model="names" required> <span class="error" ng:show="myForm.list.$error.REQUIRED"> Required!</span> </form> <tt>names = {{names}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularInputType('list', function() { function parse(viewValue) { var list = []; forEach(viewValue.split(/\s*,\s*/), function(value){ if (value) list.push(trim(value)); }); return list; } this.$parseView = function() { isString(this.$viewValue) && (this.$modelValue = parse(this.$viewValue)); }; this.$parseModel = function() { var modelValue = this.$modelValue; if (isArray(modelValue) && (!isString(this.$viewValue) || !equals(parse(this.$viewValue), modelValue))) { this.$viewValue = modelValue.join(', '); } }; }); /** * @ngdoc inputType * @name angular.inputType.number * * @description * Text input with number validation and transformation. Sets the `NUMBER` validation * error if not a valid number. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} min Sets the `MIN` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `MAX` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.value = 12; } </script> <div ng:controller="Ctrl"> <form name="myForm"> Number: <input type="number" name="input" ng:model="value" min="0" max="99" required> <span class="error" ng:show="myForm.list.$error.REQUIRED"> Required!</span> <span class="error" ng:show="myForm.list.$error.NUMBER"> Not valid number!</span> </form> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual('123'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularInputType('number', numericRegexpInputType(NUMBER_REGEXP, 'NUMBER')); /** * @ngdoc inputType * @name angular.inputType.integer * * @description * Text input with integer validation and transformation. Sets the `INTEGER` * validation error key if not a valid integer. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} min Sets the `MIN` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `MAX` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.value = 12; } </script> <div ng:controller="Ctrl"> <form name="myForm"> Integer: <input type="integer" name="input" ng:model="value" min="0" max="99" required> <span class="error" ng:show="myForm.list.$error.REQUIRED"> Required!</span> <span class="error" ng:show="myForm.list.$error.INTEGER"> Not valid integer!</span> </form> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br/> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter('1.2'); expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual('123'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularInputType('integer', numericRegexpInputType(INTEGER_REGEXP, 'INTEGER')); /** * @ngdoc inputType * @name angular.inputType.checkbox * * @description * HTML checkbox. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} ng:true-value The value to which the expression should be set when selected. * @param {string=} ng:false-value The value to which the expression should be set when not selected. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.value1 = true; this.value2 = 'YES' } </script> <div ng:controller="Ctrl"> <form name="myForm"> Value1: <input type="checkbox" ng:model="value1"> <br/> Value2: <input type="checkbox" ng:model="value2" ng:true-value="YES" ng:false-value="NO"> <br/> </form> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </div> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ angularInputType('checkbox', function(inputElement) { var widget = this, trueValue = inputElement.attr('ng:true-value'), falseValue = inputElement.attr('ng:false-value'); if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; inputElement.bind('click', function() { widget.$apply(function() { widget.$emit('$viewChange', inputElement[0].checked); }); }); widget.$render = function() { inputElement[0].checked = widget.$viewValue; }; widget.$parseModel = function() { widget.$viewValue = this.$modelValue === trueValue; }; widget.$parseView = function() { widget.$modelValue = widget.$viewValue ? trueValue : falseValue; }; }); /** * @ngdoc inputType * @name angular.inputType.radio * * @description * HTML radio button. * * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.color = 'blue'; } </script> <div ng:controller="Ctrl"> <form name="myForm"> <input type="radio" ng:model="color" value="red"> Red <br/> <input type="radio" ng:model="color" value="green"> Green <br/> <input type="radio" ng:model="color" value="blue"> Blue <br/> </form> <tt>color = {{color}}</tt><br/> </div> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ angularInputType('radio', function(inputElement) { var widget = this; //correct the name inputElement.attr('name', widget.$id + '@' + inputElement.attr('name')); inputElement.bind('click', function() { widget.$apply(function() { if (inputElement[0].checked) { widget.$emit('$viewChange', widget.$value); } }); }); widget.$render = function() { inputElement[0].checked = isDefined(widget.$value) && (widget.$value == widget.$viewValue); }; if (inputElement[0].checked) { widget.$viewValue = widget.$value; } }); function numericRegexpInputType(regexp, error) { return function(inputElement) { var widget = this, min = 1 * (inputElement.attr('min') || Number.MIN_VALUE), max = 1 * (inputElement.attr('max') || Number.MAX_VALUE); widget.$on('$validate', function(event){ var value = widget.$viewValue, filled = value && trim(value) != '', valid = isString(value) && value.match(regexp); widget.$emit(!filled || valid ? "$valid" : "$invalid", error); filled && (value = 1 * value); widget.$emit(valid && value < min ? "$invalid" : "$valid", "MIN"); widget.$emit(valid && value > max ? "$invalid" : "$valid", "MAX"); }); widget.$parseView = function() { if (widget.$viewValue.match(regexp)) { widget.$modelValue = 1 * widget.$viewValue; } else if (widget.$viewValue == '') { widget.$modelValue = null; } }; widget.$parseModel = function() { if (isNumber(widget.$modelValue)) { widget.$viewValue = '' + widget.$modelValue; } }; }; } var HTML5_INPUTS_TYPES = makeMap( "search,tel,url,email,datetime,date,month,week,time,datetime-local,number,range,color," + "radio,checkbox,text,button,submit,reset,hidden,password"); /** * @ngdoc widget * @name angular.widget.input * * @description * HTML input element widget with angular data-binding. Input widget follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * The {@link angular.inputType custom angular.inputType}s provide a shorthand for declaring new * inputs. This is a sharthand for text-box based inputs, and there is no need to go through the * full {@link angular.service.$formFactory $formFactory} widget lifecycle. * * * @param {string} type Widget types as defined by {@link angular.inputType}. If the * type is in the format of `@ScopeType` then `ScopeType` is loaded from the * current scope, allowing quick definition of type. * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl() { this.user = {name: 'guest', last: 'visitor'}; } </script> <div ng:controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng:model="user.name" required> <span class="error" ng:show="myForm.userName.$error.REQUIRED"> Required!</span><br> Last name: <input type="text" name="lastName" ng:model="user.last" ng:minlength="3" ng:maxlength="10"> <span class="error" ng:show="myForm.lastName.$error.MINLENGTH"> Too short!</span> <span class="error" ng:show="myForm.lastName.$error.MAXLENGTH"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br> <tt>myForm.$error.MINLENGTH = {{!!myForm.$error.MINLENGTH}}</tt><br> <tt>myForm.$error.MAXLENGTH = {{!!myForm.$error.MAXLENGTH}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{\n \"last\":\"visitor",\n \"name\":\"guest\"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{\n \"last\":\"visitor",\n \"name\":\"\"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{\n \"last\":\"",\n \"name\":\"guest\"}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{\n \"last\":\"xx",\n \"name\":\"guest\"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/MINLENGTH/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{\n \"last\":\"some ridiculously long name",\n \"name\":\"guest\"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/MAXLENGTH/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ angularWidget('input', function(inputElement){ this.directives(true); this.descend(true); var modelExp = inputElement.attr('ng:model'); return modelExp && annotate('$defer', '$formFactory', function($defer, $formFactory, inputElement){ var form = $formFactory.forElement(inputElement), // We have to use .getAttribute, since jQuery tries to be smart and use the // type property. Trouble is some browser change unknown to text. type = inputElement[0].getAttribute('type') || 'text', TypeController, modelScope = this, patternMatch, widget, pattern = trim(inputElement.attr('ng:pattern')), minlength = parseInt(inputElement.attr('ng:minlength'), 10), maxlength = parseInt(inputElement.attr('ng:maxlength'), 10), loadFromScope = type.match(/^\s*\@\s*(.*)/); if (!pattern) { patternMatch = valueFn(true); } else { if (pattern.match(/^\/(.*)\/$/)) { pattern = new RegExp(pattern.substr(1, pattern.length - 2)); patternMatch = function(value) { return pattern.test(value); }; } else { patternMatch = function(value) { var patternObj = modelScope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return patternObj.test(value); }; } } type = lowercase(type); TypeController = (loadFromScope ? (assertArgFn(this.$eval(loadFromScope[1]), loadFromScope[1])).$unboundFn : angularInputType(type)) || noop; if (!HTML5_INPUTS_TYPES[type]) { try { // jquery will not let you so we have to go to bare metal inputElement[0].setAttribute('type', 'text'); } catch(e){ // also turns out that ie8 will not allow changing of types, but since it is not // html5 anyway we can ignore the error. } } !TypeController.$inject && (TypeController.$inject = []); widget = form.$createWidget({ scope: modelScope, model: modelExp, onChange: inputElement.attr('ng:change'), alias: inputElement.attr('name'), controller: TypeController, controllerArgs: [inputElement]}); watchElementProperty(this, widget, 'value', inputElement); watchElementProperty(this, widget, 'required', inputElement); watchElementProperty(this, widget, 'readonly', inputElement); watchElementProperty(this, widget, 'disabled', inputElement); widget.$pristine = !(widget.$dirty = false); widget.$on('$validate', function() { var $viewValue = trim(widget.$viewValue), inValid = widget.$required && !$viewValue, tooLong = maxlength && $viewValue && $viewValue.length > maxlength, tooShort = minlength && $viewValue && $viewValue.length < minlength, missMatch = $viewValue && !patternMatch($viewValue); if (widget.$error.REQUIRED != inValid){ widget.$emit(inValid ? '$invalid' : '$valid', 'REQUIRED'); } if (widget.$error.PATTERN != missMatch){ widget.$emit(missMatch ? '$invalid' : '$valid', 'PATTERN'); } if (widget.$error.MINLENGTH != tooShort){ widget.$emit(tooShort ? '$invalid' : '$valid', 'MINLENGTH'); } if (widget.$error.MAXLENGTH != tooLong){ widget.$emit(tooLong ? '$invalid' : '$valid', 'MAXLENGTH'); } }); forEach(['valid', 'invalid', 'pristine', 'dirty'], function(name) { widget.$watch('$' + name, function(scope, value) { inputElement[value ? 'addClass' : 'removeClass']('ng-' + name); }); }); inputElement.bind('$destroy', function() { widget.$destroy(); }); if (type != 'checkbox' && type != 'radio') { // TODO (misko): checkbox / radio does not really belong here, but until we can do // widget registration with CSS, we are hacking it this way. widget.$render = function() { inputElement.val(widget.$viewValue || ''); }; inputElement.bind('keydown change', function(event){ var key = event.keyCode; if (/*command*/ key != 91 && /*modifiers*/ !(15 < key && key < 19) && /*arrow*/ !(37 < key && key < 40)) { $defer(function() { widget.$dirty = !(widget.$pristine = false); var value = trim(inputElement.val()); if (widget.$viewValue !== value ) { widget.$emit('$viewChange', value); } }); } }); } }); }); /** * @ngdoc widget * @name angular.widget.textarea * * @description * HTML textarea element widget with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link angular.widget.input input element}. * * @param {string} type Widget types as defined by {@link angular.inputType}. If the * type is in the format of `@ScopeType` then `ScopeType` is loaded from the * current scope, allowing quick definition of type. * @param {string} ng:model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the widgets is published. * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than * minlength. * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than * maxlength. * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ng:change Angular expression to be executed when input changes due to user * interaction with the input element. */ angularWidget('textarea', angularWidget('input')); function watchElementProperty(modelScope, widget, name, element) { var bindAttr = fromJson(element.attr('ng:bind-attr') || '{}'), match = /\s*{{(.*)}}\s*/.exec(bindAttr[name]), isBoolean = BOOLEAN_ATTR[name]; widget['$' + name] = isBoolean ? ( // some browsers return true some '' when required is set without value. isString(element.prop(name)) || !!element.prop(name) || // this is needed for ie9, since it will treat boolean attributes as false !!element[0].attributes[name]) : element.attr(name); if (bindAttr[name] && match) { modelScope.$watch(match[1], function(scope, value){ widget['$' + name] = isBoolean ? !!value : value; widget.$emit('$validate'); }); } } /** * @ngdoc widget * @name angular.widget.select * * @description * HTML `SELECT` element with angular data-binding. * * # `ng:options` * * Optionally `ng:options` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ng:options` expression. * * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `name` attribute * of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ng:options` provides iterator facility for `<option>` element which must be used instead * of {@link angular.widget.@ng:repeat ng:repeat}. `ng:repeat` is not suitable for use with * `<option>` element because of the following reasons: * * * value attribute of the option element that we need to bind to requires a string, but the * source of data for the iteration might be in a form of array containing objects instead of * strings * * {@link angular.widget.@ng:repeat ng:repeat} unrolls after the select binds causing * incorect rendering on most browsers. * * binding to a value not in list confuses most browsers. * * @param {string} name assignable expression to data-bind to. * @param {string=} required The widget is considered valid only if value is entered. * @param {comprehension_expression=} ng:options in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl() { this.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; this.color = this.colors[2]; // red } </script> <div ng:controller="MyCntrl"> <ul> <li ng:repeat="color in colors"> Name: <input ng:model="color.name"> [<a href ng:click="colors.$remove(color)">X</a>] </li> <li> [<a href ng:click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng:model="color" ng:options="c.name for c in colors"></select><br> Color (null allowed): <div class="nullable"> <select ng:model="color" ng:options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </div><br/> Color grouped by shade: <select ng:model="color" ng:options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng:click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng:style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng:options', function() { expect(binding('color')).toMatch('red'); select('color').option('0'); expect(binding('color')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('color')).toMatch('null'); }); </doc:scenario> </doc:example> */ //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; angularWidget('select', function(element){ this.directives(true); this.descend(true); return element.attr('ng:model') && annotate('$formFactory', function($formFactory, selectElement){ var modelScope = this, match, form = $formFactory.forElement(selectElement), multiple = selectElement.attr('multiple'), optionsExp = selectElement.attr('ng:options'), modelExp = selectElement.attr('ng:model'), widget = form.$createWidget({ scope: this, model: modelExp, onChange: selectElement.attr('ng:change'), alias: selectElement.attr('name'), controller: optionsExp ? Options : (multiple ? Multiple : Single)}); selectElement.bind('$destroy', function() { widget.$destroy(); }); widget.$pristine = !(widget.$dirty = false); watchElementProperty(modelScope, widget, 'required', selectElement); watchElementProperty(modelScope, widget, 'readonly', selectElement); watchElementProperty(modelScope, widget, 'disabled', selectElement); widget.$on('$validate', function() { var valid = !widget.$required || !!widget.$modelValue; if (valid && multiple && widget.$required) valid = !!widget.$modelValue.length; if (valid !== !widget.$error.REQUIRED) { widget.$emit(valid ? '$valid' : '$invalid', 'REQUIRED'); } }); widget.$on('$viewChange', function() { widget.$pristine = !(widget.$dirty = true); }); forEach(['valid', 'invalid', 'pristine', 'dirty'], function(name) { widget.$watch('$' + name, function(scope, value) { selectElement[value ? 'addClass' : 'removeClass']('ng-' + name); }); }); //////////////////////////// function Multiple() { var widget = this; this.$render = function() { var items = new HashMap(this.$viewValue); forEach(selectElement.children(), function(option){ option.selected = isDefined(items.get(option.value)); }); }; selectElement.bind('change', function() { widget.$apply(function() { var array = []; forEach(selectElement.children(), function(option){ if (option.selected) { array.push(option.value); } }); widget.$emit('$viewChange', array); }); }); } function Single() { var widget = this; widget.$render = function() { selectElement.val(widget.$viewValue); }; selectElement.bind('change', function() { widget.$apply(function() { widget.$emit('$viewChange', selectElement.val()); }); }); widget.$viewValue = selectElement.val(); } function Options() { var widget = this, match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + optionsExp + "'."); } var widgetScope = this, displayFn = expressionCompile(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = expressionCompile(match[3] || ''), valueFn = expressionCompile(match[2] ? match[1] : valueName), valuesFn = expressionCompile(match[7]), // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate = jqLite(document.createElement('optgroup')), nullOption = false, // if false then user will not be able to select it // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; // find existing special options forEach(selectElement.children(), function(option) { if (option.value == '') { // developer declared null option, so user should be able to select it nullOption = jqLite(option).remove(); // compile the element since there might be bindings in it compile(nullOption)(modelScope); } }); selectElement.html(''); // clear contents selectElement.bind('change', function() { widgetScope.$apply(function() { var optionGroup, collection = valuesFn(modelScope) || [], key = selectElement.val(), tempScope = inherit(modelScope), value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { if (keyName) tempScope[keyName] = key; tempScope[valueName] = collection[optionElement.val()]; value.push(valueFn(tempScope)); } } } } else { if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { tempScope[valueName] = collection[key]; if (keyName) tempScope[keyName] = key; value = valueFn(tempScope); } } if (isDefined(value) && modelScope.$viewVal !== value) { widgetScope.$emit('$viewChange', value); } }); }); widgetScope.$watch(render); widgetScope.$render = render; function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = widget.$modelValue, values = valuesFn(modelScope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, optionScope = inherit(modelScope), selected, selectedSet = false, // nothing is selected yet lastElement, element; if (multiple) { selectedSet = new HashMap(modelValue); } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push({selected:modelValue === null, id:'', label:''}); selectedSet = true; } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { optionScope[valueName] = values[keyName ? optionScope[keyName]=keys[index]:index]; optionGroupName = groupByFn(optionScope) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(valueFn(optionScope)) != undefined; } else { selected = modelValue === valueFn(optionScope); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(optionScope) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } if (!multiple && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the begining for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.element.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } }; } }); }); var browserSingleton; angularService('$browser', function($log, $sniffer) { if (!browserSingleton) { browserSingleton = new Browser(window, jqLite(window.document), jqLite(window.document.body), XHR, $log, $sniffer); } return browserSingleton; }, {$inject: ['$log', '$sniffer']}); extend(angular, { // disabled for now until we agree on public name //'annotate': annotate, 'compile': compile, 'scope': createScope, 'copy': copy, 'extend': extend, 'equals': equals, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase }); //try to bind to jquery now so that one can write angular.element().read() //but we will rebind on bootstrap again. bindJQuery(); jqLiteWrap(document).ready(function() { angularInit(angularJsConfig(document), document); }); })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],.ng-cloak{display:none;}.ng-format-negative{color:red;}</style>');
src/examples/firstCourse/style.js
AugustinLF/react-training
import cx from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import './style.css'; const ElementWithClasses = ({text, selected}) => { const classes = cx('element-with-classes', { 'element-with-classes--selected': selected, }); return <div className={classes}>{text}</div>; }; const ElementWithInlineStyle = ({text, selected}) => { const styles = { opacity: selected ? 1 : 0.6, textDecoration: 'underline', }; return <div style={styles}>{text}</div>; }; const App = () => ( <div className="style"> <ElementWithClasses text="A" /> <ElementWithClasses text="B" selected /> <ElementWithInlineStyle text="C" /> <ElementWithInlineStyle text="D" selected /> </div> ); ReactDOM.render(<App />, document.getElementById('root'));
public/_admin/assets/plugins/flot/jquery.min.js
atticus88/MediaCloud
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
docs/src/app/components/pages/components/FloatingActionButton/Page.js
rscnt/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import floatingButtonReadmeText from './README'; import floatingButtonExampleSimpleCode from '!raw!./ExampleSimple'; import FloatingButtonExampleSimple from './ExampleSimple'; import floatingButtonCode from '!raw!material-ui/lib/FloatingActionButton/FloatingActionButton'; const descriptions = { simple: 'Default size and `mini` FABs, in primary (default), `secondary` and `disabled` colors.', }; const FloatingActionButtonPage = () => ( <div> <Title render={(previousTitle) => `Floating Action Button - ${previousTitle}`} /> <MarkdownElement text={floatingButtonReadmeText} /> <CodeExample description={descriptions.simple} code={floatingButtonExampleSimpleCode}> <FloatingButtonExampleSimple /> </CodeExample> <PropTypeDescription code={floatingButtonCode} /> </div> ); export default FloatingActionButtonPage;
src/routes.js
codingbox/isomorphic-react-redux-tutorial
/* eslint react/jsx-filename-extension: 0 */ import React from 'react'; import { IndexRoute, Route } from 'react-router'; import { App, Home, NotFound, } from './containers'; export default (store) => { // eslint-disable-line return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home} /> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
ajax/libs/forerunnerdb/1.3.52/fdb-core+views.min.js
rlugojr/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":26}],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.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),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":25}],3:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.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._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",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if("dropped"===this._state)return a&&a(!1,!0),!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._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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},n.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)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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},n.prototype.upsert=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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||[]},n.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 this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.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":case"$data":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;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"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw'ForerunnerDB.Collection "'+this.name()+'": Cannot update cast to unknown type: '+b[p]}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"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(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},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.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)},1))},n.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()},n.prototype.insert=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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)},n.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}},n.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"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.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},n.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)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},n.prototype.subsetOf=function(){return this.__subsetOf},n.prototype._subsetOf=function(a){return this.__subsetOf=a,this},n.prototype.distinct=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,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)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.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},n.prototype.find=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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,x,y,z,A,B,C=this._metrics.create("find"),D=this.primaryKey(),E=this,F=!0,G={},H=[],I=[],J=[],K={},L={},M=function(b){return E._match(b,a,"and",K)};if(C.start(),a){if(C.time("analyseQuery"),c=this._analyseQuery(a,b,C),C.time("analyseQuery"),C.data("analysis",c),c.hasJoin&&c.queriesJoin){for(C.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],G[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);C.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(C.data("index.potential",c.indexMatch),C.data("index.used",c.indexMatch[0].index),C.time("indexLookup"),e=c.indexMatch[0].lookup,C.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(F=!1)):C.flag("usedIndex",!1),F&&(e&&e.length?(d=e.length,C.time("tableScan: "+d),e=e.filter(M)):(d=this._data.length,C.time("tableScan: "+d),e=this._data.filter(M)),b.$orderBy&&(C.time("sort"),e=this.sort(b.$orderBy,e),C.time("sort")),C.time("tableScan: "+d)),void 0!==b.$page&&void 0!==b.$limit&&(L.page=b.$page,L.pages=Math.ceil(e.length/b.$limit),L.records=e.length,b.$page&&b.$limit>0&&(C.data("cursor",L),e.splice(0,b.$page*b.$limit))),b.$skip&&(L.skip=b.$skip,e.splice(0,b.$skip),C.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(L.limit=b.$limit,e.length=b.$limit,C.data("limit",b.$limit)),b.$decouple&&(C.time("decouple"),e=this.decouple(e),C.time("decouple"),C.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:H.push(e[t])}C.data("flag.join",!0)}if(H.length){for(C.time("removalQueue"),v=0;v<H.length;v++)u=e.indexOf(H[v]),u>-1&&e.splice(u,1);C.time("removalQueue")}if(b.$transform){for(C.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.$transform(e[v]));C.time("transform"),C.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(C.time("transformOut"),e=this.transformOut(e),C.time("transformOut")),C.data("results",e.length)}else e=[];C.time("scanFields");for(v in b)b.hasOwnProperty(v)&&0!==v.indexOf("$")&&(1===b[v]?I.push(v):0===b[v]&&J.push(v));if(C.time("scanFields"),I.length||J.length){for(C.data("flag.limitFields",!0),C.data("limitFields.on",I),C.data("limitFields.off",J),C.time("limitFields"),v=0;v<e.length;v++){B=e[v];for(w in B)B.hasOwnProperty(w)&&(I.length&&w!==D&&-1===I.indexOf(w)&&delete B[w],J.length&&J.indexOf(w)>-1&&delete B[w])}C.time("limitFields")}if(b.$elemMatch){C.data("flag.elemMatch",!0),C.time("projection-elemMatch");for(v in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length)for(x=0;x<z.length;x++)if(E._match(z[x],b.$elemMatch[v],"",{})){y.set(e[w],v,[z[x]]);break}C.time("projection-elemMatch")}if(b.$elemsMatch){C.data("flag.elemsMatch",!0),C.time("projection-elemsMatch");for(v in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length){for(A=[],x=0;x<z.length;x++)E._match(z[x],b.$elemsMatch[v],"",{})&&A.push(z[x]);y.set(e[w],v,A)}C.time("projection-elemsMatch")}return C.stop(),e.__fdbOp=C,e.$cursor=L,e},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},n.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}},n.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},n.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},n.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)},n.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)},n.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)},n.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},n.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},n.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},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.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)},n.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},n.prototype.ensureIndex=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';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()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.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},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({object:function(a){return this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b).db(this),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+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.sort(function(a,b){return a.name.localeCompare(b.name)}),c},d.finishModule("Collection"),b.exports=n},{"./Crc":6,"./IndexBinaryTree":8,"./IndexHashMap":9,"./KeyValueStore":10,"./Metrics":11,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":25}],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.Db,f=d.modules.Db.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=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),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),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),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":25}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a){this.init.apply(this,arguments)};h.prototype.init=function(){this._db={},this._debug={}},h.prototype.moduleLoaded=new g({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()}}}),h.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},h.moduleLoaded=h.prototype.moduleLoaded,h.version=h.prototype.version,h.shared=d,h.prototype.shared=d,d.addModule("Core",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),h.prototype._isServer=!1,h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=h},{"./Db.js":7,"./Metrics.js":11,"./Overload":22,"./Shared":25}],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,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a){this.init.apply(this,arguments)};j.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},j.prototype.moduleLoaded=new i({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()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.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},j.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},j.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},j.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},j.prototype.drop=new i({"":function(){if("dropped"!==this._state){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":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),delete this._core._db[this._name]}return!0},"boolean":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if("dropped"!==this._state){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a).core(this),this._db[a]},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},b.exports=j},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":11,"./Overload":22,"./Shared":25}],8:[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":23,"./Shared":25}],9:[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":23,"./Shared":25}],10:[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":25}],11:[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":21,"./Shared":25}],12:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],13:[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,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||"dropped"===d._state))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";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},{}],14:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},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":22}],15:[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},{}],16:[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]:this._listeners&&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":22}],17:[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),d.$rootData=d.$rootData||{},"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.$rootData["//distinctLookup"]=d.$rootData["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootData["//distinctLookup"][m]=d.$rootData["//distinctLookup"][m]||{},d.$rootData["//distinctLookup"][m][b[m]]?!1:(d.$rootData["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],18:[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},{}],19:[function(a,b,c){"use strict";var d=a("./Overload"),e={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,enabled:!0}),!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},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},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],i.enabled){if(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=e},{"./Overload":22}],20:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "'+b+'" for "'+this.name()+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for "'+this.name()+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c}};b.exports=d},{}],21:[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":23,"./Shared":25}],22:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;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 h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)f.push(e);if(d=f.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],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},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],23:[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":25}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments 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":25}],25:[function(a,b,c){"use strict";var d={version:"1.3.52",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&&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"),"Mixin.Updating":a("./Mixin.Updating")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":12,"./Mixin.ChainReactor":13,"./Mixin.Common":14,"./Mixin.Constants":15,"./Mixin.Events":16,"./Mixin.Matching":17,"./Mixin.Sorting":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],26:[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._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.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor"),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._from.on("drop",this._collectionDroppedWrap),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(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return 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._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(d){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.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},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,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}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.filter=function(a,b,c){return this.publicData().filter(a,b,c)},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("Db.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":24,"./Shared":25}]},{},[1]);
examples/demos/dndresource.js
intljusticemission/react-big-calendar
import React from 'react' import { Calendar } from 'react-big-calendar' import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop' import 'react-big-calendar/lib/addons/dragAndDrop/styles.scss' const DragAndDropCalendar = withDragAndDrop(Calendar) const events = [ { id: 0, title: 'Board meeting', start: new Date(2018, 0, 29, 9, 0, 0), end: new Date(2018, 0, 29, 13, 0, 0), resourceId: 1, }, { id: 1, title: 'MS training', start: new Date(2018, 0, 29, 14, 0, 0), end: new Date(2018, 0, 29, 16, 30, 0), resourceId: 2, }, { id: 2, title: 'Team lead meeting', start: new Date(2018, 0, 29, 8, 30, 0), end: new Date(2018, 0, 29, 12, 30, 0), resourceId: 3, }, { id: 10, title: 'Board meeting', start: new Date(2018, 0, 30, 23, 0, 0), end: new Date(2018, 0, 30, 23, 59, 0), resourceId: 1, }, { id: 11, title: 'Birthday Party', start: new Date(2018, 0, 30, 7, 0, 0), end: new Date(2018, 0, 30, 10, 30, 0), resourceId: 4, }, { id: 12, title: 'Board meeting', start: new Date(2018, 0, 29, 23, 59, 0), end: new Date(2018, 0, 30, 13, 0, 0), resourceId: 1, }, { id: 13, title: 'Board meeting', start: new Date(2018, 0, 29, 23, 50, 0), end: new Date(2018, 0, 30, 13, 0, 0), resourceId: 2, }, { id: 14, title: 'Board meeting', start: new Date(2018, 0, 29, 23, 40, 0), end: new Date(2018, 0, 30, 13, 0, 0), resourceId: 4, }, ] const resourceMap = [ { resourceId: 1, resourceTitle: 'Board room' }, { resourceId: 2, resourceTitle: 'Training room' }, { resourceId: 3, resourceTitle: 'Meeting room 1' }, { resourceId: 4, resourceTitle: 'Meeting room 2' }, ] class Dnd extends React.Component { constructor(props) { super(props) this.state = { events: events, } this.moveEvent = this.moveEvent.bind(this) } moveEvent({ event, start, end, resourceId, isAllDay: droppedOnAllDaySlot }) { const { events } = this.state const idx = events.indexOf(event) let allDay = event.allDay if (!event.allDay && droppedOnAllDaySlot) { allDay = true } else if (event.allDay && !droppedOnAllDaySlot) { allDay = false } const updatedEvent = { ...event, start, end, resourceId, allDay } const nextEvents = [...events] nextEvents.splice(idx, 1, updatedEvent) this.setState({ events: nextEvents, }) } resizeEvent = (resizeType, { event, start, end }) => { const { events } = this.state const nextEvents = events.map(existingEvent => { return existingEvent.id == event.id ? { ...existingEvent, start, end } : existingEvent }) this.setState({ events: nextEvents, }) } render() { return ( <DragAndDropCalendar selectable localizer={this.props.localizer} events={this.state.events} onEventDrop={this.moveEvent} resizable resources={resourceMap} resourceIdAccessor="resourceId" resourceTitleAccessor="resourceTitle" onEventResize={this.resizeEvent} defaultView="day" step={15} showMultiDayTimes={true} defaultDate={new Date(2018, 0, 29)} /> ) } } export default Dnd
js/setup.js
kwoumn3/khemet
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import App from './App'; import configureStore from './configureStore'; function setup():React.Component { class Root extends Component { constructor() { super(); this.state = { isLoading: false, store: configureStore(() => this.setState({ isLoading: false })), }; } render() { return ( <Provider store={this.state.store}> <App /> </Provider> ); } } return Root; } export default setup;
ajax/libs/react-datetime/3.0.0-alpha.2/react-datetime.js
sufuf3/cdnjs
/* react-datetime v3.0.0-alpha.1 https://github.com/YouCanBookMe/react-datetime MIT: https://github.com/YouCanBookMe/react-datetime/raw/master/LICENSE */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("React"), require("moment"), require("ReactDOM")); else if(typeof define === 'function' && define.amd) define(["React", "moment", "ReactDOM"], factory); else if(typeof exports === 'object') exports["Datetime"] = factory(require("React"), require("moment"), require("ReactDOM")); else root["Datetime"] = factory(root["React"], root["moment"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_16__, __WEBPACK_EXTERNAL_MODULE_22__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var assign = __webpack_require__(1), PropTypes = __webpack_require__(2), createClass = __webpack_require__(11), moment = __webpack_require__(16), React = __webpack_require__(12), DaysView = __webpack_require__(17), MonthsView = __webpack_require__(18), YearsView = __webpack_require__(19), TimeView = __webpack_require__(20), onClickOutside = __webpack_require__(21).default ; var viewModes = { YEARS: 'years', MONTHS: 'months', DAYS: 'days', TIME: 'time', }; var TYPES = PropTypes; var nofn = function(){}; var Datetime = createClass({ displayName: 'DateTime', propTypes: { // value: TYPES.object | TYPES.string, // defaultValue: TYPES.object | TYPES.string, // viewDate: TYPES.object | TYPES.string, onOpen: TYPES.func, onClose: TYPES.func, onChange: TYPES.func, onViewModeChange: TYPES.func, onNavigateBack: TYPES.func, onNavigateForward: TYPES.func, locale: TYPES.string, utc: TYPES.bool, displayTimeZone: TYPES.string, input: TYPES.bool, // dateFormat: TYPES.string | TYPES.bool, // timeFormat: TYPES.string | TYPES.bool, inputProps: TYPES.object, timeConstraints: TYPES.object, viewMode: TYPES.oneOf([viewModes.YEARS, viewModes.MONTHS, viewModes.DAYS, viewModes.TIME]), isValidDate: TYPES.func, open: TYPES.bool, strictParsing: TYPES.bool, closeOnSelect: TYPES.bool, closeOnTab: TYPES.bool }, getDefaultProps: function(){ return { onOpen: nofn, onClose: nofn, onCalendarOpen: nofn, onCalendarClose: nofn, onChange: nofn, onViewModeChange: nofn, onNavigateBack: nofn, onNavigateForward: nofn, dateFormat: true, timeFormat: true, utc: false, viewMode: viewModes.DAYS, className: '', input: true, inputProps: {}, timeConstraints: {}, isValidDate: function(){ return true }, strictParsing: true, closeOnSelect: false, closeOnTab: true, closeOnClickOutside: true } }, getInitialState: function() { var props = this.props; var selectedDate = this.parseDate( props.value || props.defaultValue ); var inputFormat = this.getFormat('datetime'); this.checkTZ( props ); return { open: !props.input, currentView: props.dateFormat ? props.viewMode : viewMode.TIME, viewDate: props.viewDate ? this.parseDate( props.viewDate ) : (selectedDate && selectedDate.isValid() ? selectedDate.clone() : this.localMoment()), selectedDate: selectedDate && selectedDate.isValid() ? selectedDate : undefined, inputValue: props.inputProps.value || selectedDate && selectedDate.isValid() && selectedDate.format( inputFormat ) || '' } }, parseDate: function (date, formats) { var parsedDate; if (date && typeof date === 'string') parsedDate = this.localMoment(date, formats.datetime); else if (date) parsedDate = this.localMoment(date); if (parsedDate && !parsedDate.isValid()) parsedDate = null; return parsedDate; }, isOpen: function(){ return !this.props.input || (this.props.open === undefined ? this.state.open : this.props.open); }, getUpdateOn: function( dateFormat ) { if ( dateFormat.match(/[lLD]/) ) { return viewModes.DAYS; } else if ( dateFormat.indexOf('M') !== -1 ) { return viewModes.MONTHS; } else if ( dateFormat.indexOf('Y') !== -1 ) { return viewModes.YEARS; } return viewModes.DAYS; }, getLocaleData: function( props ){ var p = props || this.props; return this.localMoment( p.date ).localeData(); }, getDateFormat: function( locale ){ var format = this.props.dateFormat; if( format === true ) return locale.longDateFormat('L'); if( format ) return format; return '' }, getTimeFormat: function( locale ){ var format = this.props.timeFormat; if( format === true ) return locale.longDateFormat('LT'); if( format ) return format; return ''; }, getFormat: function( type ){ if( type === 'date' ){ return this.getDateFormat( this.getLocaleData() ) } else if( type === 'time' ){ return this.getTimeFormat( this.getLocaleData() ) } else if( type === 'datetime' ){ var locale = this.getLocaleData(); var dateFormat = this.getDateFormat( locale ) var timeFormat = this.getTimeFormat( locale ) return dateFormat && timeFormat ? dateFormat + ' ' + timeFormat : (dateFormat || timeFormat ); } }, onInputChange: function( e ) { var value = e.target === null ? e : e.target.value, localMoment = this.localMoment( value, this.state.inputFormat ), update = { inputValue: value } ; if ( localMoment.isValid() && !this.props.value ) { update.selectedDate = localMoment; update.viewDate = localMoment.clone().startOf('month'); } else { update.selectedDate = null; } return this.setState( update, function() { return this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue ); }); }, onInputKey: function( e ) { if ( e.which === 9 && this.props.closeOnTab ) { this.closeCalendar(); } }, showView: function( view ) { var me = this; // this is a function bound to a click so we need a closure return function( e ){ if( me.state.currentView !== view ){ me.props.onViewModeChange( view ) me.setState({ currentView: view }) } } }, updateTime: function( op, amount, type, toSelected ) { var update = {}, date = toSelected ? 'selectedDate' : 'viewDate'; update[ date ] = this.state[ date ].clone()[ op ]( amount, type ); this.setState( update ); }, viewToMethod: {days: 'date', months: 'month', years: 'year'}, nextView: { days: 'time', months: 'days', years: 'months'}, updateDate: function( e ){ var state = this.state; var currentView = state.currentView; var updateOnView = this.getUpdateOn( this.getFormat('date') ); var viewDate = this.state.viewDate.clone(); // Set the value into day/month/year var value = parseInt( e.target.getAttribute('data-value'), 10 ) viewDate[ this.viewToMethod[currentView] ]( value ) var update = {viewDate: viewDate}; if( currentView === updateOnView ){ update.selectedDate = viewDate.clone(); update.inputValue = viewDate.format( this.getFormat('datetime') ); if( this.props.open === undefined && this.props.input && this.props.closeOnSelect ){ this.closeCalendar(); } this.props.onChange( viewDate.clone() ); } else { update.currentView = this.nextView[ currentView ]; } this.setState( update ); }, navigate: function( modifier, unit ){ var me = this; // this is a function bound to a click so we need a closure return function( e ){ var viewDate = me.state.viewDate.clone(); var update = { viewDate: viewDate } // Subtracting is just adding negative time viewDate.add( modifier, unit ); me.props[ modifier > 0 ? 'onNavigateForward' : 'onNavigateBack']( modifier, unit ); me.setState( update ); } }, allowedSetTime: ['hours', 'minutes', 'seconds', 'milliseconds'], setTime: function( type, value ) { var state = this.state, date = (state.selectedDate || state.viewDate).clone() ; date[ type ]( value ); if ( !this.props.value ) { this.setState({ selectedDate: date, viewDate: date.clone(), inputValue: date.format( this.getFormat('datetime') ) }); } this.props.onChange( date.clone() ); }, openCalendar: function( e ) { if ( !this.isOpen() ) { this.setState({ open: true }, function() { this.props.onOpen( e ); }); } }, closeCalendar: function() { this.setState({ open: false }, function () { this.props.onClose( this.state.selectedDate || this.state.inputValue ); }); }, handleClickOutside: function() { var props = this.props; if ( props.input && props.open === undefined && !this.state.open && props.closeOnClickOutside ) { this.closeCalendar(); } }, localMoment: function( date, format, props ) { props = props || this.props; var m = null; if (props.utc) { m = moment.utc(date, format, props.strictParsing); } else if (props.displayTimeZone) { m = moment.tz(date, format, props.displayTimeZone); } else { m = moment(date, format, props.strictParsing); } if ( props.locale ) m.locale( props.locale ); return m; }, checkTZ: function( props ) { var con = console; if ( props.displayTimeZone && !this.tzWarning && !moment.tz ) { this.tzWarning = true; con && con.error('react-datetime: displayTimeZone prop with value "' + props.displayTimeZone + '" is used but moment.js timezone is not loaded.'); } }, overrideEvent: function( handler, action ) { if ( !this.overridenEvents ) { this.overridenEvents = {}; } if ( !this.overridenEvents[handler] ) { var me = this; this.overridenEvents[handler] = function( e ) { var result; if ( me.props.inputProps && me.props.inputProps[handler] ) { result = me.props.inputProps[handler]( e ); } if ( result !== false ) { action( e ); } }; } return this.overridenEvents[handler]; }, getClassName: function(){ var cn = 'rdt'; var props = this.props; var propCn = props.className; if( Array.isArray( propCn ) ){ cn += ' ' + propCn.join(' ') } else if( propCn ){ cn += ' ' + propCn } if( !props.input ){ cn += ' rdtStatic' } if( this.isOpen() ){ cn += ' rdtOpen' } return cn; }, render: function() { var cn = this.getClassName(); var children = []; if ( this.props.input ) { var finalInputProps = assign( { type: 'text', className: 'form-control', value: this.state.inputValue }, this.props.inputProps, { onClick: this.overrideEvent( 'onClick', this.openCalendar ), onOpen: this.overrideEvent( 'onOpen', this.openCalendar ), onChange: this.overrideEvent( 'onChange', this.onInputChange ), onKeyDown: this.overrideEvent( 'onKeyDown', this.onInputKey ), } ); if ( this.props.renderInput ) { children = [ React.createElement('div', { key: 'i' }, this.props.renderInput( finalInputProps, this.openCalendar, this.closeCalendar )) ]; } else { children = [ React.createElement('input', assign({ key: 'i' }, finalInputProps ))]; } } return React.createElement( ClickableWrapper, {className: cn, onClickOut: this.handleClickOutside}, children.concat( React.createElement( 'div', { key: 'dt', className: 'rdtPicker' }, this.renderCalendar( this.state.currentView ) ) )); }, renderCalendar: function( currentView ){ var p = this.props; var state = this.state; var props = { viewDate: state.viewDate, selectedDate: state.selectedDate, isValidDate: p.isValidDate, updateDate: this.updateDate, navigate: this.navigate, showView: this.showView } // I think updateOn, updateSelectedDate and setDate can be merged in the same method // that would update viewDate or selectedDate depending on the view and the dateFormat if( currentView === viewModes.YEARS ){ // Used props // { viewDate, selectedDate, renderYear, isValidDate, navigate, showView, updateDate } props.renderYear = p.renderYear return React.createElement( YearsView, props ) } else if( currentView === viewModes.MONTHS ){ // { viewDate, selectedDate, renderMonth, isValidDate, navigate, showView, updateDate } props.renderMonth = p.renderMonth return React.createElement( MonthsView, props ) } else if( currentView === viewModes.DAYS ){ // { viewDate, selectedDate, renderDay, isValidDate, navigate, showView, updateDate, timeFormat } props.renderDay = p.renderDay; props.timeFormat = this.getFormat('time'); return React.createElement( DaysView, props ); } else if( currentView === viewModes.TIME ){ // { viewDate, selectedDate, timeFormat, dateFormat, timeConstraints, setTime, showView } props.dateFormat = this.getFormat('date'); props.timeFormat = this.getFormat('time'); props.timeConstraints = p.timeConstraints; props.setTime = this.setTime; return React.createElement( TimeView, props ) } } }); var ClickableWrapper = onClickOutside( createClass({ render: function() { return React.createElement( 'div', { className: this.props.className }, this.props.children ); }, handleClickOutside: function( e ) { this.props.onClickOut( e ); } })); // Make moment accessible through the Datetime class Datetime.moment = moment; module.exports = Datetime; /***/ }), /* 1 */ /***/ (function(module, exports) { 'use strict'; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function ownEnumerableKeys(obj) { var keys = Object.getOwnPropertyNames(obj); if (Object.getOwnPropertySymbols) { keys = keys.concat(Object.getOwnPropertySymbols(obj)); } return keys.filter(function (key) { return propIsEnumerable.call(obj, key); }); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = ownEnumerableKeys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-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. */ if (process.env.NODE_ENV !== 'production') { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(4)(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(10)(); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 3 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-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. */ 'use strict'; var emptyFunction = __webpack_require__(5); var invariant = __webpack_require__(6); var warning = __webpack_require__(7); var ReactPropTypesSecret = __webpack_require__(8); var checkPropTypes = __webpack_require__(9); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, '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 if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning( false, 'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction.thatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 5 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-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. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-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. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (process.env.NODE_ENV !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, 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. * */ 'use strict'; var emptyFunction = __webpack_require__(5); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 8 */ /***/ (function(module, exports) { /** * Copyright 2013-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. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-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. */ 'use strict'; if (process.env.NODE_ENV !== 'production') { var invariant = __webpack_require__(6); var warning = __webpack_require__(7); var ReactPropTypesSecret = __webpack_require__(8); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-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. */ 'use strict'; var emptyFunction = __webpack_require__(5); var invariant = __webpack_require__(6); var ReactPropTypesSecret = __webpack_require__(8); module.exports = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } invariant( false, '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' ); }; shim.isRequired = shim; function getShim() { return shim; }; // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; var React = __webpack_require__(12); var factory = __webpack_require__(13); if (typeof React === 'undefined') { throw Error( 'create-react-class could not find the React object. If you are using script tags, ' + 'make sure that React is being loaded before create-react-class.' ); } // Hack to grab NoopUpdateQueue from isomorphic React var ReactNoopUpdateQueue = new React.Component().updater; module.exports = factory( React.Component, React.isValidElement, ReactNoopUpdateQueue ); /***/ }), /* 12 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_12__; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; var _assign = __webpack_require__(14); var emptyObject = __webpack_require__(15); var _invariant = __webpack_require__(6); if (process.env.NODE_ENV !== 'production') { var warning = __webpack_require__(7); } var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } var ReactPropTypeLocationNames; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } else { ReactPropTypeLocationNames = {}; } function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) { /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillMount`. * * @optional */ UNSAFE_componentWillMount: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillReceiveProps`. * * @optional */ UNSAFE_componentWillReceiveProps: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillUpdate`. * * @optional */ UNSAFE_componentWillUpdate: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Similar to ReactClassInterface but for static methods. */ var ReactClassStaticInterface = { /** * This method is invoked after a component is instantiated and when it * receives new props. Return an object to update state in response to * prop changes. Return null to indicate no change to state. * * If an object is returned, its keys will be merged into the existing state. * * @return {object || null} * @optional */ getDerivedStateFromProps: 'DEFINE_MANY_MERGED' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an _invariant so components // don't show up in prod but only in __DEV__ if (process.env.NODE_ENV !== 'production') { warning( typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName ); } } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { _invariant( specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ); } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { _invariant( specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (process.env.NODE_ENV !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if (process.env.NODE_ENV !== 'production') { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; _invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ); var isAlreadyDefined = name in Constructor; if (isAlreadyDefined) { var specPolicy = ReactClassStaticInterface.hasOwnProperty(name) ? ReactClassStaticInterface[name] : null; _invariant( specPolicy === 'DEFINE_MANY_MERGED', 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ); Constructor[name] = createMergedResultFunction(Constructor[name], property); return; } Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis) { for ( var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { if (process.env.NODE_ENV !== 'production') { warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ); } } else if (!args.length) { if (process.env.NODE_ENV !== 'production') { warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ); } return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var IsMountedPreMixin = { componentDidMount: function() { this.__isMounted = true; } }; var IsMountedPostMixin = { componentWillUnmount: function() { this.__isMounted = false; } }; /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { this.updater.enqueueReplaceState(this, newState, callback); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if (process.env.NODE_ENV !== 'production') { warning( this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', (this.constructor && this.constructor.displayName) || this.name || 'Component' ); this.__didWarnIsMounted = true; } return !!this.__isMounted; } }; var ReactClassComponent = function() {}; _assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ function createClass(spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ); } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if ( initialState === undefined && this.getInitialState._isMockFunction ) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } _invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ); this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, IsMountedPreMixin); mixSpecIntoComponent(Constructor, spec); mixSpecIntoComponent(Constructor, IsMountedPostMixin); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } _invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ); if (process.env.NODE_ENV !== 'production') { warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component' ); warning( !Constructor.prototype.UNSAFE_componentWillRecieveProps, '%s has a method called UNSAFE_componentWillRecieveProps(). ' + 'Did you mean UNSAFE_componentWillReceiveProps()?', spec.displayName || 'A component' ); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; } return createClass; } module.exports = factory; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 14 */ /***/ (function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-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. * */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 16 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_16__; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(12), createClass = __webpack_require__(11), moment = __webpack_require__(16) ; var DateTimePickerDays = createClass({ render: function() { var footer = this.renderFooter(), date = this.props.viewDate, locale = date.localeData(), tableChildren ; tableChildren = [ React.createElement('thead', { key: 'th' }, [ React.createElement('tr', { key: 'h' }, [ React.createElement('th', { key: 'p', className: 'rdtPrev', onClick: this.props.navigate( -1, 'months' )}, React.createElement('span', {}, '‹' )), React.createElement('th', { key: 's', className: 'rdtSwitch', onClick: this.props.showView( 'months' ), colSpan: 5, 'data-value': this.props.viewDate.month() }, locale.months( date ) + ' ' + date.year() ), React.createElement('th', { key: 'n', className: 'rdtNext', onClick: this.props.navigate( 1, 'months' )}, React.createElement('span', {}, '›' )) ]), React.createElement('tr', { key: 'd'}, this.getDaysOfWeek( locale ).map( function( day, index ) { return React.createElement('th', { key: day + index, className: 'dow'}, day ); }) ) ]), React.createElement('tbody', { key: 'tb' }, this.renderDays()) ]; if ( footer ) tableChildren.push( footer ); return React.createElement('div', { className: 'rdtDays' }, React.createElement('table', {}, tableChildren ) ); }, /** * Get a list of the days of the week * depending on the current locale * @return {array} A list with the shortname of the days */ getDaysOfWeek: function( locale ) { var days = locale._weekdaysMin, first = locale.firstDayOfWeek(), dow = [], i = 0 ; days.forEach( function( day ) { dow[ (7 + ( i++ ) - first) % 7 ] = day; }); return dow; }, renderDays: function() { var date = this.props.viewDate, selected = this.props.selectedDate && this.props.selectedDate.clone(), prevMonth = date.clone().subtract( 1, 'months' ), currentYear = date.year(), currentMonth = date.month(), weeks = [], days = [], renderer = this.props.renderDay || this.renderDay, isValid = this.props.isValidDate || this.alwaysValidDate, classes, isDisabled, dayProps, currentDate ; // Go to the last week of the previous month prevMonth.date( prevMonth.daysInMonth() ).startOf( 'week' ); var lastDay = prevMonth.clone().add( 42, 'd' ); while ( prevMonth.isBefore( lastDay ) ) { classes = 'rdtDay'; currentDate = prevMonth.clone(); if ( ( prevMonth.year() === currentYear && prevMonth.month() < currentMonth ) || ( prevMonth.year() < currentYear ) ) classes += ' rdtOld'; else if ( ( prevMonth.year() === currentYear && prevMonth.month() > currentMonth ) || ( prevMonth.year() > currentYear ) ) classes += ' rdtNew'; if ( selected && prevMonth.isSame( selected, 'day' ) ) classes += ' rdtActive'; if ( prevMonth.isSame( moment(), 'day' ) ) classes += ' rdtToday'; isDisabled = !isValid( currentDate, selected ); if ( isDisabled ) classes += ' rdtDisabled'; dayProps = { key: prevMonth.format( 'M_D' ), 'data-value': prevMonth.date(), className: classes }; if ( !isDisabled ) dayProps.onClick = this.updateSelectedDate; days.push( renderer( dayProps, currentDate, selected ) ); if ( days.length === 7 ) { weeks.push( React.createElement('tr', { key: prevMonth.format( 'M_D' )}, days ) ); days = []; } prevMonth.add( 1, 'd' ); } return weeks; }, updateSelectedDate: function( event ) { this.props.updateDate( event ); }, renderDay: function( props, currentDate ) { return React.createElement('td', props, currentDate.date() ); }, renderFooter: function() { if ( !this.props.timeFormat ) return ''; var date = this.props.selectedDate || this.props.viewDate; return React.createElement('tfoot', { key: 'tf'}, React.createElement('tr', {}, React.createElement('td', { onClick: this.props.showView( 'time' ), colSpan: 7, className: 'rdtTimeToggle' }, date.format( this.props.timeFormat )) ) ); }, alwaysValidDate: function() { return 1; } }); module.exports = DateTimePickerDays; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(12), createClass = __webpack_require__(11) ; var DateTimePickerMonths = createClass({ render: function() { return React.createElement('div', { className: 'rdtMonths' }, [ React.createElement('table', { key: 'a' }, React.createElement('thead', {}, React.createElement('tr', {}, [ React.createElement('th', { key: 'prev', className: 'rdtPrev', onClick: this.props.navigate( -1, 'years' )}, React.createElement('span', {}, '‹' )), React.createElement('th', { key: 'year', className: 'rdtSwitch', onClick: this.props.showView( 'years' ), colSpan: 2, 'data-value': this.props.viewDate.year() }, this.props.viewDate.year() ), React.createElement('th', { key: 'next', className: 'rdtNext', onClick: this.props.navigate( 1, 'years' )}, React.createElement('span', {}, '›' )) ]))), React.createElement('table', { key: 'months' }, React.createElement('tbody', { key: 'b' }, this.renderMonths())) ]); }, renderMonths: function() { var date = this.props.selectedDate, month = this.props.viewDate.month(), year = this.props.viewDate.year(), rows = [], i = 0, months = [], renderer = this.props.renderMonth || this.renderMonth, isValid = this.props.isValidDate || this.alwaysValidDate, classes, props, currentMonth, isDisabled, noOfDaysInMonth, daysInMonth, validDay, // Date is irrelevant because we're only interested in month irrelevantDate = 1 ; while (i < 12) { classes = 'rdtMonth'; currentMonth = this.props.viewDate.clone().set({ year: year, month: i, date: irrelevantDate }); noOfDaysInMonth = currentMonth.endOf( 'month' ).format( 'D' ); daysInMonth = Array.from({ length: noOfDaysInMonth }, function( e, i ) { return i + 1; }); validDay = daysInMonth.find(function( d ) { var day = currentMonth.clone().set( 'date', d ); return isValid( day ); }); isDisabled = ( validDay === undefined ); if ( isDisabled ) classes += ' rdtDisabled'; if ( date && i === date.month() && year === date.year() ) classes += ' rdtActive'; props = { key: i, 'data-value': i, className: classes }; if ( !isDisabled ) props.onClick = this.updateSelectedMonth; months.push( renderer( props, i, year, date && date.clone() ) ); if ( months.length === 4 ) { rows.push( React.createElement('tr', { key: month + '_' + rows.length }, months ) ); months = []; } i++; } return rows; }, updateSelectedMonth: function( event ) { this.props.updateDate( event ); }, renderMonth: function( props, month ) { var localMoment = this.props.viewDate; var monthStr = localMoment.localeData().monthsShort( localMoment.month( month ) ); var strLength = 3; // Because some months are up to 5 characters long, we want to // use a fixed string length for consistency var monthStrFixedLength = monthStr.substring( 0, strLength ); return React.createElement('td', props, capitalize( monthStrFixedLength ) ); }, alwaysValidDate: function() { return 1; }, }); function capitalize( str ) { return str.charAt( 0 ).toUpperCase() + str.slice( 1 ); } module.exports = DateTimePickerMonths; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(12), createClass = __webpack_require__(11) ; var DateTimePickerYears = createClass({ render: function() { var year = parseInt( this.props.viewDate.year() / 10, 10 ) * 10; return React.createElement('div', { className: 'rdtYears' }, [ React.createElement('table', { key: 'a' }, React.createElement('thead', {}, React.createElement('tr', {}, [ React.createElement('th', { key: 'prev', className: 'rdtPrev', onClick: this.props.navigate( -10, 'years' )}, React.createElement('span', {}, '‹' )), React.createElement('th', { key: 'year', className: 'rdtSwitch', onClick: this.props.showView( 'years' ), colSpan: 2 }, year + '-' + ( year + 9 ) ), React.createElement('th', { key: 'next', className: 'rdtNext', onClick: this.props.navigate( 10, 'years' )}, React.createElement('span', {}, '›' )) ]))), React.createElement('table', { key: 'years' }, React.createElement('tbody', {}, this.renderYears( year ))) ]); }, renderYears: function( year ) { var years = [], i = -1, rows = [], renderer = this.props.renderYear || this.renderYear, selectedDate = this.props.selectedDate, isValid = this.props.isValidDate || this.alwaysValidDate, classes, props, currentYear, isDisabled, noOfDaysInYear, daysInYear, validDay, // Month and date are irrelevant here because // we're only interested in the year irrelevantMonth = 0, irrelevantDate = 1 ; year--; while (i < 11) { classes = 'rdtYear'; currentYear = this.props.viewDate.clone().set( { year: year, month: irrelevantMonth, date: irrelevantDate } ); // Not sure what 'rdtOld' is for, commenting out for now as it's not working properly // if ( i === -1 | i === 10 ) // classes += ' rdtOld'; noOfDaysInYear = currentYear.endOf( 'year' ).format( 'DDD' ); daysInYear = Array.from({ length: noOfDaysInYear }, function( e, i ) { return i + 1; }); validDay = daysInYear.find(function( d ) { var day = currentYear.clone().dayOfYear( d ); return isValid( day ); }); isDisabled = ( validDay === undefined ); if ( isDisabled ) classes += ' rdtDisabled'; if ( selectedDate && selectedDate.year() === year ) classes += ' rdtActive'; props = { key: year, 'data-value': year, className: classes }; if ( !isDisabled ) props.onClick = this.updateSelectedYear; years.push( renderer( props, year, selectedDate && selectedDate.clone() )); if ( years.length === 4 ) { rows.push( React.createElement('tr', { key: i }, years ) ); years = []; } year++; i++; } return rows; }, updateSelectedYear: function( event ) { this.props.updateDate( event ); }, renderYear: function( props, year ) { return React.createElement('td', props, year ); }, alwaysValidDate: function() { return 1; }, }); module.exports = DateTimePickerYears; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(12), createClass = __webpack_require__(11), assign = __webpack_require__(1) ; var DateTimePickerTime = createClass({ getInitialState: function() { return this.calculateState( this.props ); }, calculateState: function( props ) { var date = props.selectedDate || props.viewDate, format = props.timeFormat, counters = [] ; if ( format.toLowerCase().indexOf('h') !== -1 ) { counters.push('hours'); if ( format.indexOf('m') !== -1 ) { counters.push('minutes'); if ( format.indexOf('s') !== -1 ) { counters.push('seconds'); } } } var hours = date.format( 'H' ); var daypart = false; if ( this.state !== null && this.props.timeFormat.toLowerCase().indexOf( ' a' ) !== -1 ) { if ( this.props.timeFormat.indexOf( ' A' ) !== -1 ) { daypart = ( hours >= 12 ) ? 'PM' : 'AM'; } else { daypart = ( hours >= 12 ) ? 'pm' : 'am'; } } return { hours: hours, minutes: date.format( 'mm' ), seconds: date.format( 'ss' ), milliseconds: date.format( 'SSS' ), daypart: daypart, counters: counters }; }, renderCounter: function( type ) { if ( type !== 'daypart' ) { var value = this.state[ type ]; if ( type === 'hours' && this.props.timeFormat.toLowerCase().indexOf( ' a' ) !== -1 ) { value = ( value - 1 ) % 12 + 1; if ( value === 0 ) { value = 12; } } return React.createElement('div', { key: type, className: 'rdtCounter' }, [ React.createElement('span', { key: 'up', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'increase', type ), onContextMenu: this.disableContextMenu }, '▲' ), React.createElement('div', { key: 'c', className: 'rdtCount' }, value ), React.createElement('span', { key: 'do', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'decrease', type ), onContextMenu: this.disableContextMenu }, '▼' ) ]); } return ''; }, renderDayPart: function() { return React.createElement('div', { key: 'dayPart', className: 'rdtCounter' }, [ React.createElement('span', { key: 'up', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'toggleDayPart', 'hours'), onContextMenu: this.disableContextMenu }, '▲' ), React.createElement('div', { key: this.state.daypart, className: 'rdtCount' }, this.state.daypart ), React.createElement('span', { key: 'do', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'toggleDayPart', 'hours'), onContextMenu: this.disableContextMenu }, '▼' ) ]); }, render: function() { var me = this, counters = [] ; this.state.counters.forEach( function( c ) { if ( counters.length ) counters.push( React.createElement('div', { key: 'sep' + counters.length, className: 'rdtCounterSeparator' }, ':' ) ); counters.push( me.renderCounter( c ) ); }); if ( this.state.daypart !== false ) { counters.push( me.renderDayPart() ); } if ( this.state.counters.length === 3 && this.props.timeFormat.indexOf( 'S' ) !== -1 ) { counters.push( React.createElement('div', { className: 'rdtCounterSeparator', key: 'sep5' }, ':' ) ); counters.push( React.createElement('div', { className: 'rdtCounter rdtMilli', key: 'm' }, React.createElement('input', { value: this.state.milliseconds, type: 'text', onChange: this.updateMilli } ) ) ); } return React.createElement('div', { className: 'rdtTime' }, React.createElement('table', {}, [ this.renderHeader(), React.createElement('tbody', { key: 'b'}, React.createElement('tr', {}, React.createElement('td', {}, React.createElement('div', { className: 'rdtCounters' }, counters ) ))) ]) ); }, componentWillMount: function() { var me = this; me.timeConstraints = { hours: { min: 0, max: 23, step: 1 }, minutes: { min: 0, max: 59, step: 1 }, seconds: { min: 0, max: 59, step: 1 }, milliseconds: { min: 0, max: 999, step: 1 } }; ['hours', 'minutes', 'seconds', 'milliseconds'].forEach( function( type ) { assign(me.timeConstraints[ type ], me.props.timeConstraints[ type ]); }); this.setState( this.calculateState( this.props ) ); }, componentWillReceiveProps: function( nextProps ) { this.setState( this.calculateState( nextProps ) ); }, updateMilli: function( e ) { var milli = parseInt( e.target.value, 10 ); if ( milli === e.target.value && milli >= 0 && milli < 1000 ) { this.props.setTime( 'milliseconds', milli ); this.setState( { milliseconds: milli } ); } }, renderHeader: function() { if ( !this.props.dateFormat ) return null; var date = this.props.selectedDate || this.props.viewDate; return React.createElement('thead', { key: 'h' }, React.createElement('tr', {}, React.createElement('th', { className: 'rdtSwitch', colSpan: 4, onClick: this.props.showView( 'days' ) }, date.format( this.props.dateFormat ) ) )); }, onStartClicking: function( action, type ) { var me = this; return function() { var update = {}; update[ type ] = me[ action ]( type ); me.setState( update ); me.timer = setTimeout( function() { me.increaseTimer = setInterval( function() { update[ type ] = me[ action ]( type ); me.setState( update ); }, 70); }, 500); me.mouseUpListener = function() { clearTimeout( me.timer ); clearInterval( me.increaseTimer ); me.props.setTime( type, me.state[ type ] ); document.body.removeEventListener( 'mouseup', me.mouseUpListener ); document.body.removeEventListener( 'touchend', me.mouseUpListener ); }; document.body.addEventListener( 'mouseup', me.mouseUpListener ); document.body.addEventListener( 'touchend', me.mouseUpListener ); }; }, disableContextMenu: function( event ) { event.preventDefault(); return false; }, padValues: { hours: 1, minutes: 2, seconds: 2, milliseconds: 3 }, toggleDayPart: function( type ) { // type is always 'hours' var value = parseInt( this.state[ type ], 10) + 12; var tc = this.timeConstraints[ type ]; if ( value > tc.max ) value = tc.min + ( value - ( tc.max + 1 ) ); return this.pad( type, value ); }, increase: function( type ) { var tc = this.timeConstraints[ type ]; var value = parseInt( this.state[ type ], 10) + tc.step; if ( value > tc.max ) value = tc.min + ( value - ( tc.max + 1 ) ); return this.pad( type, value ); }, decrease: function( type ) { var tc = this.timeConstraints[ type ]; var value = parseInt( this.state[ type ], 10) - tc.step; if ( value < tc.min ) value = tc.max + 1 - ( tc.min - value ); return this.pad( type, value ); }, pad: function( type, value ) { var str = value + ''; while ( str.length < this.padValues[ type ] ) str = '0' + str; return str; }, }); module.exports = DateTimePickerTime; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.IGNORE_CLASS_NAME = undefined; exports.default = onClickOutsideHOC; var _react = __webpack_require__(12); var _reactDom = __webpack_require__(22); var _generateOutsideCheck = __webpack_require__(23); var _generateOutsideCheck2 = _interopRequireDefault(_generateOutsideCheck); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * A higher-order-component for handling onClickOutside for React components. */ var registeredComponents = []; var handlers = []; var touchEvents = ['touchstart', 'touchmove']; var IGNORE_CLASS_NAME = exports.IGNORE_CLASS_NAME = 'ignore-react-onclickoutside'; /** * This function generates the HOC function that you'll use * in order to impart onOutsideClick listening to an * arbitrary component. It gets called at the end of the * bootstrapping code to yield an instance of the * onClickOutsideHOC function defined inside setupHOC(). */ function onClickOutsideHOC(WrappedComponent, config) { var _class, _temp2; return _temp2 = _class = function (_Component) { _inherits(onClickOutside, _Component); function onClickOutside() { var _temp, _this, _ret; _classCallCheck(this, onClickOutside); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.__outsideClickHandler = null, _this.enableOnClickOutside = function () { var fn = _this.__outsideClickHandler; if (fn && typeof document !== 'undefined') { var events = _this.props.eventTypes; if (!events.forEach) { events = [events]; } events.forEach(function (eventName) { var handlerOptions = null; var isTouchEvent = touchEvents.indexOf(eventName) !== -1; if (isTouchEvent) { handlerOptions = { passive: !_this.props.preventDefault }; } document.addEventListener(eventName, fn, handlerOptions); }); } }, _this.disableOnClickOutside = function () { var fn = _this.__outsideClickHandler; if (fn && typeof document !== 'undefined') { var events = _this.props.eventTypes; if (!events.forEach) { events = [events]; } events.forEach(function (eventName) { return document.removeEventListener(eventName, fn); }); } }, _this.getRef = function (ref) { return _this.instanceRef = ref; }, _temp), _possibleConstructorReturn(_this, _ret); } /** * Access the WrappedComponent's instance. */ onClickOutside.prototype.getInstance = function getInstance() { if (!WrappedComponent.prototype.isReactComponent) { return this; } var ref = this.instanceRef; return ref.getInstance ? ref.getInstance() : ref; }; // this is given meaning in componentDidMount/componentDidUpdate /** * Add click listeners to the current document, * linked to this component's state. */ onClickOutside.prototype.componentDidMount = function componentDidMount() { // If we are in an environment without a DOM such // as shallow rendering or snapshots then we exit // early to prevent any unhandled errors being thrown. if (typeof document === 'undefined' || !document.createElement) { return; } var instance = this.getInstance(); if (config && typeof config.handleClickOutside === 'function') { this.__clickOutsideHandlerProp = config.handleClickOutside(instance); if (typeof this.__clickOutsideHandlerProp !== 'function') { throw new Error('WrappedComponent lacks a function for processing outside click events specified by the handleClickOutside config option.'); } } else if (typeof instance.handleClickOutside === 'function') { if (_react.Component.prototype.isPrototypeOf(instance)) { this.__clickOutsideHandlerProp = instance.handleClickOutside.bind(instance); } else { this.__clickOutsideHandlerProp = instance.handleClickOutside; } } else if (typeof instance.props.handleClickOutside === 'function') { this.__clickOutsideHandlerProp = instance.props.handleClickOutside; } else { throw new Error('WrappedComponent lacks a handleClickOutside(event) function for processing outside click events.'); } // TODO: try to get rid of this, could be done with function ref, might be problematic for SFC though, they do not expose refs if ((0, _reactDom.findDOMNode)(instance) === null) { return; } this.addOutsideClickHandler(); }; /** * Track for disableOnClickOutside props changes and enable/disable click outside */ onClickOutside.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (this.props.disableOnClickOutside && !nextProps.disableOnClickOutside) { this.enableOnClickOutside(); } else if (!this.props.disableOnClickOutside && nextProps.disableOnClickOutside) { this.disableOnClickOutside(); } }; onClickOutside.prototype.componentDidUpdate = function componentDidUpdate() { var componentNode = (0, _reactDom.findDOMNode)(this.getInstance()); if (componentNode === null && this.__outsideClickHandler) { this.removeOutsideClickHandler(); return; } if (componentNode !== null && !this.__outsideClickHandler) { this.addOutsideClickHandler(); return; } }; /** * Remove all document's event listeners for this component */ onClickOutside.prototype.componentWillUnmount = function componentWillUnmount() { this.removeOutsideClickHandler(); }; /** * Can be called to explicitly enable event listening * for clicks and touches outside of this element. */ /** * Can be called to explicitly disable event listening * for clicks and touches outside of this element. */ onClickOutside.prototype.addOutsideClickHandler = function addOutsideClickHandler() { var fn = this.__outsideClickHandler = (0, _generateOutsideCheck2.default)((0, _reactDom.findDOMNode)(this.getInstance()), this.__clickOutsideHandlerProp, this.props.outsideClickIgnoreClass, this.props.excludeScrollbar, this.props.preventDefault, this.props.stopPropagation); var pos = registeredComponents.length; registeredComponents.push(this); handlers[pos] = fn; // If there is a truthy disableOnClickOutside property for this // component, don't immediately start listening for outside events. if (!this.props.disableOnClickOutside) { this.enableOnClickOutside(); } }; onClickOutside.prototype.removeOutsideClickHandler = function removeOutsideClickHandler() { this.disableOnClickOutside(); this.__outsideClickHandler = false; var pos = registeredComponents.indexOf(this); if (pos > -1) { // clean up so we don't leak memory if (handlers[pos]) { handlers.splice(pos, 1); } registeredComponents.splice(pos, 1); } }; /** * Pass-through render */ onClickOutside.prototype.render = function render() { var _this2 = this; var props = Object.keys(this.props).filter(function (prop) { return prop !== 'excludeScrollbar'; }).reduce(function (props, prop) { props[prop] = _this2.props[prop]; return props; }, {}); if (WrappedComponent.prototype.isReactComponent) { props.ref = this.getRef; } else { props.wrappedRef = this.getRef; } props.disableOnClickOutside = this.disableOnClickOutside; props.enableOnClickOutside = this.enableOnClickOutside; return (0, _react.createElement)(WrappedComponent, props); }; return onClickOutside; }(_react.Component), _class.displayName = 'OnClickOutside(' + (WrappedComponent.displayName || WrappedComponent.name || 'Component') + ')', _class.defaultProps = { eventTypes: ['mousedown', 'touchstart'], excludeScrollbar: config && config.excludeScrollbar || false, outsideClickIgnoreClass: IGNORE_CLASS_NAME, preventDefault: false, stopPropagation: false }, _class.getClass = function () { return WrappedComponent.getClass ? WrappedComponent.getClass() : WrappedComponent; }, _temp2; } /***/ }), /* 22 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_22__; /***/ }), /* 23 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; exports.default = generateOutsideCheck; /** * Check whether some DOM node is our Component's node. */ function isNodeFound(current, componentNode, ignoreClass) { if (current === componentNode) { return true; } // SVG <use/> elements do not technically reside in the rendered DOM, so // they do not have classList directly, but they offer a link to their // corresponding element, which can have classList. This extra check is for // that case. // See: http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGUseElement // Discussion: https://github.com/Pomax/react-onclickoutside/pull/17 if (current.correspondingElement) { return current.correspondingElement.classList.contains(ignoreClass); } return current.classList.contains(ignoreClass); } /** * Try to find our node in a hierarchy of nodes, returning the document * node as highest node if our node is not found in the path up. */ function findHighest(current, componentNode, ignoreClass) { if (current === componentNode) { return true; } // If source=local then this event came from 'somewhere' // inside and should be ignored. We could handle this with // a layered approach, too, but that requires going back to // thinking in terms of Dom node nesting, running counter // to React's 'you shouldn't care about the DOM' philosophy. while (current.parentNode) { if (isNodeFound(current, componentNode, ignoreClass)) { return true; } current = current.parentNode; } return current; } /** * Check if the browser scrollbar was clicked */ function clickedScrollbar(evt) { return document.documentElement.clientWidth <= evt.clientX || document.documentElement.clientHeight <= evt.clientY; } /** * Generate the event handler that checks whether a clicked DOM node * is inside of, or lives outside of, our Component's node tree. */ function generateOutsideCheck(componentNode, eventHandler, ignoreClass, excludeScrollbar, preventDefault, stopPropagation) { return function (evt) { if (preventDefault) { evt.preventDefault(); } if (stopPropagation) { evt.stopPropagation(); } var current = evt.target; if (excludeScrollbar && clickedScrollbar(evt) || findHighest(current, componentNode, ignoreClass) !== document) { return; } eventHandler(evt); }; } /***/ }) /******/ ]) }); ;
src/common/routes.js
MatthewKosloski/server-side-react
import React from 'react'; import { browserHistory, Route, Router, IndexRoute } from 'react-router'; import App from './components/App'; import UserListContainer from './containers/UserListContainer'; const routes = ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={UserListContainer} /> </Route> </Router> ) export default routes;
src/components/Feedback/Feedback.js
ziedAb/PVMourakiboun
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.css'; class Feedback extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit" >Ask a question</a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new" >Report an issue</a> </div> </div> ); } } export default withStyles(s)(Feedback);
ajax/libs/primereact/6.6.0-rc.1/avatar/avatar.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, ObjectUtils } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Avatar = /*#__PURE__*/function (_Component) { _inherits(Avatar, _Component); var _super = _createSuper(Avatar); function Avatar() { _classCallCheck(this, Avatar); return _super.apply(this, arguments); } _createClass(Avatar, [{ key: "renderContent", value: function renderContent() { var _this = this; if (this.props.label) { return /*#__PURE__*/React.createElement("span", { className: "p-avatar-text" }, this.props.label); } else if (this.props.icon) { var iconClassName = classNames('p-avatar-icon', this.props.icon); return /*#__PURE__*/React.createElement("span", { className: iconClassName }); } else if (this.props.image) { var onError = function onError(e) { if (_this.props.onImageError) { _this.props.onImageError(e); } }; return /*#__PURE__*/React.createElement("img", { src: this.props.image, alt: this.props.imageAlt, onError: onError }); } return null; } }, { key: "render", value: function render() { var containerClassName = classNames('p-avatar p-component', { 'p-avatar-image': this.props.image != null, 'p-avatar-circle': this.props.shape === 'circle', 'p-avatar-lg': this.props.size === 'large', 'p-avatar-xl': this.props.size === 'xlarge', 'p-avatar-clickable': !!this.props.onClick }, this.props.className); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : this.renderContent(); return /*#__PURE__*/React.createElement("div", { className: containerClassName, style: this.props.style, onClick: this.props.onClick }, content, this.props.children); } }]); return Avatar; }(Component); _defineProperty(Avatar, "defaultProps", { label: null, icon: null, image: null, size: 'normal', shape: 'square', style: null, className: null, template: null, imageAlt: 'avatar', onImageError: null, onClick: null }); export { Avatar };
src/js/components/tag/articlelist.js
axuebin/react-blog
import React from 'react'; import PropTypes from 'prop-types'; import ArticleListItem from './articlelistitem'; import { COLOR_BLOG_CATEGORY, COLOR_LABEL_CATEGORY } from '../../constants/config'; export default class ArticleList extends React.Component { constructor() { super(); this.getTagData = this.getTagData.bind(this); } getTagData(issues) { const len = issues.length; let name = ''; const articles = {}; for (let i = 0; i < len; i += 1) { const labels = issues[i].labels; for (let j = 0; j < labels.length; j += 1) { if (labels[j].color !== COLOR_BLOG_CATEGORY && labels[j].color !== COLOR_LABEL_CATEGORY) { const tag = labels[j].name; if (name !== tag) { if (!articles[tag]) { articles[tag] = []; } name = tag; } articles[tag].push(issues[i]); } } } return articles; } render() { if (!this.props.issues) { return null; } const articles = this.getTagData(this.props.issues); const articleList = []; Object.keys(articles).forEach((key) => { if (Object.prototype.toString.call(articles[key]) === '[object Array]') { articleList.push(<ArticleListItem key={key} tag={key} items={articles[key]} />); } }); return ( <div className="archive-list-area"> <div className="archive-list"> {articleList} </div> </div> ); } } ArticleList.defaultProps = { issues: null, }; ArticleList.propTypes = { issues: PropTypes.array, };
packages/ringcentral-widgets-docs/src/app/pages/Components/ConversationMessageList/Demo.js
ringcentral/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import ConversationMessageList from 'ringcentral-widgets/components/ConversationMessageList'; const props = {}; props.messages = [ { creationTime: '2017-06-14T07:53:56.000Z', id: 1234, direction: 'Outbound', subject: 'How are you?', }, { creationTime: '2017-06-14T07:54:56.000Z', id: 1235, direction: 'Inbound', subject: "I'm fine.", }, ]; props.dateTimeFormatter = ({ utcTimestamp }) => new Date(utcTimestamp).toString(); /** * A example of `ConversationMessageList` */ const ConversationMessageListDemo = () => ( <ConversationMessageList {...props} /> ); export default ConversationMessageListDemo;
app/index.js
romankhrystynych/raspitron
// @flow import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
ajax/libs/forerunnerdb/2.0.5/fdb-core.js
cdnjs/cdnjs
(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(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {Number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAscIgnoreUndefined(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDescIgnoreUndefined(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAscIgnoreUndefined(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAscIgnoreUndefined(pathVal, from), toResult = this.sortAscIgnoreUndefined(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":25,"./Shared":28}],3:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor * @class */ var Collection = function (name, options) { this.init.apply(this, arguments); }; /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. */ Collection.prototype.init = function (name, options) { // Ensure we have an options object options = options || {}; // Set internals this.sharedPathSolver = sharedPathSolver; this._primaryKey = options.primaryKey || '_id'; this._primaryIndex = new KeyValueStore('primary', {primaryKey: this.primaryKey()}); this._primaryCrc = new KeyValueStore('primaryCrc', {primaryKey: this.primaryKey()}); this._crcLookup = new KeyValueStore('crcLookup', {primaryKey: this.primaryKey()}); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @method Collection.setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @method Collection.setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @method Collection.setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @method Collection.setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @method Collection.setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {*} callback Optional callback function. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @method Collection.setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' 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: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { var i; if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary', {primaryKey: this.primaryKey()}); this._primaryCrc = new KeyValueStore('primaryCrc', {primaryKey: this.primaryKey()}); this._crcLookup = new KeyValueStore('crcLookup', {primaryKey: this.primaryKey()}); // Re-create any existing collection indexes // TODO: This might not be the most efficient way to do this, perhaps just re-creating // the indexes would be faster than calling rebuild? for (i in this._indexByName) { if (this._indexByName.hasOwnProperty(i)) { this._indexByName[i].rebuild(); } } this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * If the document contains a primary key field (based on the * collections's primary key) then the database will search for * an existing document with a matching id. If a matching * document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with * new data. Any keys that do not currently exist on the document * will be added to the document. * * If the document does not contain an id or the id passed does * not match an existing document, an insert is performed instead. * If no id is present a new primary key id is provided for the * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Array} An array containing an object for each operation * performed. Each object contains two keys, "op" contains either "none", * "insert" or "update" depending on the type of operation that was * performed and "result" contains the return data from the operation * used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])[0]); } if (callback) { callback.call(this, returnData); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } if (callback) { callback.call(this, [returnData]); } return [returnData]; } else { if (callback) { callback.call(this, {op: 'none'}); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object=} query The optional query object. * @param {Object=} options Optional options object. If you specify an options object * you MUST also specify a query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. If you * return a modified object from the one passed to it will be included in the results * as the modified version but will not affect the data in the collection at all. * Your function will be called with a single object as the first argument and will * be called once for every document in your initial query result. * @returns {Array} */ Collection.prototype.filter = function (query, options, func) { var temp; if (typeof query === 'function') { func = query; query = {}; options = {}; } if (typeof options === 'function') { if (func) { temp = func; } func = options; options = temp || {}; } return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Detect $replace operations and set flag if (update.$replace) { // Make sure we have an options object options = options || {}; // Set the $replace flag in the options object options.$replace = true; // Move the replacement object out into the main update object update = update.$replace; } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one self._removeFromIndexes(referencedDoc); result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); self._insertIntoIndexes(referencedDoc); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one self._removeFromIndexes(referencedDoc); result = self.updateObject(referencedDoc, update, query, options, ''); self._insertIntoIndexes(referencedDoc); } return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this, updated || []); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } else { if (callback) { callback.call(this, updated || []); } } } else { if (callback) { callback.call(this, updated || []); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base object to alter. * @param {Object} newObj The new object to overwrite the existing one * with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update, options, callback) { var searchObj = {}, wrappedCallback; searchObj[this._primaryKey] = id; if (callback) { wrappedCallback = function (data) { callback(data[0]); }; } return this.update(searchObj, update, options, wrappedCallback)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Check if we have a $replace flag in the options object if (options && options.$replace === true) { operation = true; replaceObj = update; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } // Early exit return updated; } // DEVS PLEASE NOTE -- Early exit could have occurred above and code below will never be reached - Rob Evans - CEO - 05/08/2016 // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (!operation && i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (!operation && this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // Check if the doc key is a date instance if (doc[i] instanceof Date) { // The doc key is a date object, assign the new date this._updateProperty(doc, i, update[i]); updated = true; } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$splicePull': // Check that the target key is not undefined if (doc[i] !== undefined) { // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update[i].$index; if (tempIndex !== undefined) { // Check for in bounds index if (tempIndex < doc[i].length) { this._updateSplicePull(doc[i], tempIndex); updated = true; } } else { throw(this.logIdentifier() + ' Cannot splicePull without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePull from a key that is not an array! (' + i + ')'); } } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark * (a dollar at the end of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search * query key/values. * @param {Object=} query The query identifying the documents to remove. If no * query object is passed, all documents will be removed from the collection. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection.insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * The insert operation's callback. * @name Collection.insertCallback * @callback Collection.insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection.insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {Number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {Array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update (must be * actual reference to original document). * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {Object=} obj Optional options object to modify. * @returns {Object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = [].concat(analysis.indexMatch[0].lookup) || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and * returns an object containing details about the query which * can be used to optimise the search. * * @param {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = [].concat(this._primaryIndex.lookup(query, options, op)); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = [].concat(indexRef.lookup(query, options, op)); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = this.objectId(); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @name collection * @method Db.collection * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @name collection * @method Db.collection * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @name collection * @method Db.collection * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @name collection * @method Db.collection * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @name collection * @method Db.collection * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @name collection * @method Db.collection * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, '$main': function (options) { var self = this, name = options.name; if (!name) { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } return; } if (this._collection[name]) { return this._collection[name]; } if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.deferEmit('create', self._collection[name], 'collection', name); return this._collection[name]; } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or * regular expression to use to match collection names against. * @returns {Array} An array of objects containing details of each * collection the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Condition":4,"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],4:[function(_dereq_,module,exports){ "use strict"; var //Overload = require('./Overload'), Shared, Condition; Shared = _dereq_('./Shared'); /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. * @class * @constructor */ Condition = function () { this.init.apply(this, arguments); }; /** * Class constructor calls this init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. * @param {Collection|View} dataSource The condition's data source. * @param {String} id The id to assign to the new Condition. * @param {Object} clause The query clause. */ Condition.prototype.init = function (dataSource, id, clause) { this._dataSource = dataSource; this._id = id; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'id'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); Shared.synthesize(Condition.prototype, 'debug'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @param {*} initialState Initial state of condition. * @returns {Condition} */ Condition.prototype.start = function (initialState) { if (!this._started) { var self = this; if (arguments.length !== 0) { this._satisfied = initialState; } // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (this._debug) { console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]); } if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; /** * Drops the condition and removes it from memory. * @returns {Condition} */ Condition.prototype.drop = function () { this.stop(); delete this._dataSource.when[this._id]; return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":28}],5:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Shared.mixin(Db.prototype, 'Mixin.Events'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ /*Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; };*/ /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ /*Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; };*/ /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ /*Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; };*/ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {Object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":3,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { lat: lat, lng: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],8:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":25,"./Shared":28}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @param {Object=} options Optional KV store options object. Currently * supports "primaryKey" as a string. * @constructor */ var KeyValueStore = function (name, options) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name, options) { // Ensure we have options options = options || {}; // Set our internal data settings this._name = name; this._data = {}; this._primaryKey = options.primaryKey || '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk] !== undefined && val[pk] !== null) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":28}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":23,"./Shared":28}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Gets / sets the flag that will enable / disable chain reactor sending * from this instance. Chain reactor sending is enabled by default on all * instances. * @param {Boolean} val True or false to enable or disable chain sending. * @returns {*} */ chainEnabled: function (val) { if (val !== undefined) { this._chainDisabled = !val; return this; } return !this._chainDisabled; }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain && !this._chainDisabled); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain && !this._chainDisabled) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(), crcTable; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: JSON.stringify, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {String} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {String} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; }, /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum: function (str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line } }; module.exports = Common; },{"./Overload":24,"./Serialiser":27}],16:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],17:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin * @name Events */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @name on * @method Events.on * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. * @returns {*} */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @name on * @method Events.on * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. * @returns {*} */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ /** * Attach an event listener to the passed event that will be called only once. * @name once * @method Events.once * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. * @returns {*} */ 'string, function': function (event, listener) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(event, internalCallback); listener.apply(self, arguments); fired = true; } }; return this.on(event, internalCallback); }, /** * Attach an event listener to the passed event that will be called only once. * @name once * @method Events.once * @param {String} event The name of the event to listen for. * @param {String} id The document id to match against. * @param {Function} listener The method to call when the event is fired. * @returns {*} */ 'string, *, function': function (event, id, listener) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(event, id, internalCallback); listener.apply(self, arguments); fired = true; } }; return this.on(event, id, internalCallback); } }), off: new Overload({ /** * Cancels all event listeners for the passed event. * @name off * @method Events.off * @param {String} event The name of the event. * @returns {*} */ 'string': function (event) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event); }); } else { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } } return this; }, /** * Cancels the event listener for the passed event and listener function. * @name off * @method Events.off * @param {String} event The event to cancel listener for. * @param {Function} listener The event listener function used in the on() * or once() call to cancel. * @returns {*} */ 'string, function': function (event, listener) { var self = this, arr, index; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, listener); }); } else { if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } } return this; }, /** * Cancels an event listener based on an event name, id and listener function. * @name off * @method Events.off * @param {String} event The event to cancel listener for. * @param {String} id The ID of the event to cancel listening for. * @param {Function} listener The event listener function used in the on() * or once() call to cancel. */ 'string, *, function': function (event, id, listener) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id, listener); }); } else { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } }, /** * Cancels all listeners for an event based on the passed event name and id. * @name off * @method Events.off * @param {String} event The event name to cancel listeners for. * @param {*} id The ID to cancel all listeners for. */ 'string, *': function (event, id) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id); }); } else { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } } }), /** * Emit an event with data. * @name emit * @method Events.emit * @param {String} event The event to emit. * @param {*} data Data to emit with the event. * @returns {*} */ emit: function (event, data) { this._listeners = this._listeners || {}; this._emitting = true; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } this._emitting = false; this._processRemovalQueue(); return this; }, /** * If events are cleared with the off() method while the event emitter is * actively processing any events then the off() calls get added to a * queue to be executed after the event emitter is finished. This stops * errors that might occur by potentially modifying the event queue while * the emitter is running through them. This method is called after the * event emitter is finished processing. * @name _processRemovalQueue * @method Events._processRemovalQueue * @private */ _processRemovalQueue: function () { var i; if (this._eventRemovalQueue && this._eventRemovalQueue.length) { // Execute each removal call for (i = 0; i < this._eventRemovalQueue.length; i++) { this._eventRemovalQueue[i](); } // Clear the removal queue this._eventRemovalQueue = []; } }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @name deferEmit * @method Events.deferEmit * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":24}],18:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$fastIn': if (test instanceof Array) { // Source is a string or number, use indexOf to identify match in array return test.indexOf(source) !== -1; } else { console.log(this.logIdentifier() + ' Cannot use an $fastIn operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': var lookupPath, value, finalDistinctProp; // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { if (typeof test[distinctProp] === 'object') { // Get the path string from the object lookupPath = this.sharedPathSolver.parse(test)[0].path; // Use the path string to find the lookup value from the source data value = this.sharedPathSolver.get(source, lookupPath); finalDistinctProp = lookupPath; } else { value = source[distinctProp]; finalDistinctProp = distinctProp; } options.$rootData['//distinctLookup'][finalDistinctProp] = options.$rootData['//distinctLookup'][finalDistinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][finalDistinctProp][value]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][finalDistinctProp][value] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * Performs a join operation and returns the final joined data. * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function mixinSortingSortAsc (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } if (a === undefined && b !== undefined) { return -1; } if (b === undefined && a !== undefined) { return 1; } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function mixinSortingSortDesc (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } if (a === undefined && b !== undefined) { return 1; } if (b === undefined && a !== undefined) { return -1; } return 0; }, /** * Sorts the passed value a against the passed value b ascending. This variant * of the sortAsc method will not consider undefined values as lower than any * other value. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAscIgnoreUndefined: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. This variant * of the sortDesc method will not consider undefined values as lower than any * other value. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDescIgnoreUndefined: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id, type and phase. * @name addTrigger * @method Triggers.addTrigger * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Triggers.addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * Removes a trigger by id, type and phase. * @name removeTrigger * @method Triggers.removeTrigger * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback Triggers.addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ module.exports = Triggers; },{"./Overload":24}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Removes an item from the passed array at the specified index. * @param {Array} arr The array to remove from. * @param {Number} index The index of the item to remove. * @param {Number} count The number of items to remove. * @private */ _updateSplicePull: function (arr, index, count) { if (!count) { count = 1; } arr.splice(index, count); }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":25,"./Shared":28}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":28}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":28}],27:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '2.0.5', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
test/DropdownSpec.js
bbc/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Dropdown from '../src/Dropdown'; import DropdownMenu from '../src/DropdownMenu'; import MenuItem from '../src/MenuItem'; import { shouldWarn } from './helpers'; import keycode from 'keycode'; class CustomMenu extends React.Component { render() { return ( <div className='custom-menu'> {this.props.children} </div> ); } } describe('Dropdown', () => { let BaseDropdown = Dropdown.ControlledComponent; const dropdownChildren = [ <Dropdown.Toggle> Child Title </Dropdown.Toggle>, <Dropdown.Menu> <MenuItem>Item 1</MenuItem> <MenuItem>Item 2</MenuItem> <MenuItem>Item 3</MenuItem> <MenuItem>Item 4</MenuItem> </Dropdown.Menu> ]; const simpleDropdown = ( <Dropdown id='test-id'> {dropdownChildren} </Dropdown> ); it('renders div with dropdown class', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const node = React.findDOMNode(instance); node.tagName.should.equal('DIV'); node.className.should.match(/\bdropdown\b/); node.className.should.not.match(/\bdropup\b/); }); it('renders div with dropup class', () => { const instance = ReactTestUtils.renderIntoDocument( <Dropdown title='Dropup' dropup id='test-id'> {dropdownChildren} </Dropdown> ); const node = React.findDOMNode(instance); node.tagName.should.equal('DIV'); node.className.should.not.match(/\bdropdown\b/); node.className.should.match(/\bdropup\b/); }); it('renders toggle with Dropdown.Toggle', () => { const instance = ReactTestUtils.renderIntoDocument( simpleDropdown ); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); buttonNode.innerText.should.match(/Child Title/); buttonNode.tagName.should.equal('BUTTON'); buttonNode.className.should.match(/\bbtn[ $]/); buttonNode.className.should.match(/\bbtn-default\b/); buttonNode.className.should.match(/\bdropdown-toggle\b/); buttonNode.getAttribute('type').should.equal('button'); buttonNode.getAttribute('aria-expanded').should.equal('false'); buttonNode.getAttribute('id').should.be.ok; }); it('renders dropdown toggle button caret', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const caretNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'caret')); caretNode.tagName.should.equal('SPAN'); }); it('does not render toggle button caret', () => { const instance = ReactTestUtils.renderIntoDocument( <Dropdown.Toggle noCaret> Child Text </Dropdown.Toggle> ); const caretNode = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'caret'); caretNode.length.should.equal(0); }); it('renders custom menu', () => { const instance = ReactTestUtils.renderIntoDocument( <Dropdown title='Single child' id='test-id'> <Dropdown.Toggle>Child Text</Dropdown.Toggle> <CustomMenu bsRole='menu'> <MenuItem>Item 1</MenuItem> </CustomMenu> </Dropdown> ); ReactTestUtils.scryRenderedComponentsWithType(instance, DropdownMenu).length.should.equal(0); ReactTestUtils.scryRenderedComponentsWithType(instance, CustomMenu).length.should.equal(1); }); it('prop validation with multiple menus', () => { const props = { title: 'herpa derpa', children: [( <Dropdown.Toggle>Child Text</Dropdown.Toggle> ), ( <Dropdown.Menu> <MenuItem>Item 1</MenuItem> </Dropdown.Menu> ), ( <Dropdown.Menu> <MenuItem>Item 1</MenuItem> </Dropdown.Menu> )] }; let err = BaseDropdown.propTypes.children(props, 'children', 'DropdownButton'); err.message.should.match(/Duplicate children.*bsRole: menu/); }); it('only renders one menu', () => { const instance = ReactTestUtils.renderIntoDocument( <Dropdown title='Single child' id='test-id'> <Dropdown.Toggle>Child Text</Dropdown.Toggle> <CustomMenu bsRole='menu'> <MenuItem>Item 1</MenuItem> </CustomMenu> <DropdownMenu> <MenuItem>Item 1</MenuItem> </DropdownMenu> </Dropdown> ); ReactTestUtils.scryRenderedComponentsWithType(instance, DropdownMenu).length.should.equal(0); ReactTestUtils.scryRenderedComponentsWithType(instance, CustomMenu).length.should.equal(1); shouldWarn(/Duplicate children.*bsRole: menu/); }); it('forwards pullRight to menu', () => { const instance = ReactTestUtils.renderIntoDocument( <Dropdown pullRight id='test-id'> {dropdownChildren} </Dropdown> ); const menu = ReactTestUtils.findRenderedComponentWithType(instance, DropdownMenu); menu.props.pullRight.should.be.true; }); // NOTE: The onClick event handler is invoked for both the Enter and Space // keys as well since the component is a button. I cannot figure out how to // get ReactTestUtils to simulate such though. it('toggles open/closed when clicked', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); node.className.should.not.match(/\bopen\b/); buttonNode.getAttribute('aria-expanded').should.equal('false'); ReactTestUtils.Simulate.click(buttonNode); node.className.should.match(/\bopen\b/); buttonNode.getAttribute('aria-expanded').should.equal('true'); ReactTestUtils.Simulate.click(buttonNode); node.className.should.not.match(/\bopen\b/); buttonNode.getAttribute('aria-expanded').should.equal('false'); }); it('opens if dropdown contains no focusable menu item', () => { const instance = ReactTestUtils.renderIntoDocument( <Dropdown title='custom child' id='dropdown'> <Dropdown.Toggle>Toggle</Dropdown.Toggle> <Dropdown.Menu> <li>Some custom nonfocusable content</li> </Dropdown.Menu> </Dropdown> ); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); ReactTestUtils.Simulate.click(buttonNode); node.className.should.match(/\bopen\b/); }); it('when focused and closed toggles open when the key "down" is pressed', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); ReactTestUtils.Simulate.keyDown(buttonNode, { keyCode: keycode('down') }); node.className.should.match(/\bopen\b/); buttonNode.getAttribute('aria-expanded').should.equal('true'); }); it('button has aria-haspopup attribute (As per W3C WAI-ARIA Spec)', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); buttonNode.getAttribute('aria-haspopup').should.equal('true'); }); it('closes when child MenuItem is selected', () => { const instance = ReactTestUtils.renderIntoDocument( simpleDropdown ); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); const menuItem = React.findDOMNode( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]); ReactTestUtils.Simulate.click(buttonNode); node.className.should.match(/\bopen\b/); ReactTestUtils.Simulate.click(menuItem); node.className.should.not.match(/\bopen\b/); }); it('does not close when onToggle is controlled', () => { const handleSelect = () => {}; const instance = ReactTestUtils.renderIntoDocument( <Dropdown open={true} onToggle={handleSelect} id='test-id'> {dropdownChildren} </Dropdown> ); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); const menuItem = React.findDOMNode( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]); ReactTestUtils.Simulate.click(buttonNode); node.className.should.match(/\bopen\b/); ReactTestUtils.Simulate.click(menuItem); node.className.should.match(/\bopen\b/); }); it('is open with explicit prop', () => { class OpenProp extends React.Component { constructor(props) { super(props); this.state = { open: false }; } render() { return ( <div> <button className='outer-button' onClick={() => this.setState({open: !this.state.open})}> Outer button </button> <Dropdown open={this.state.open} onToggle={() => {}} title='Prop open control' id='test-id' > {dropdownChildren} </Dropdown> </div> ); } } const instance = ReactTestUtils.renderIntoDocument(<OpenProp />); const outerToggle = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'outer-button'); const dropdownNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown')); dropdownNode.className.should.not.match(/\bopen\b/); ReactTestUtils.Simulate.click(outerToggle); dropdownNode.className.should.match(/\bopen\b/); ReactTestUtils.Simulate.click(outerToggle); dropdownNode.className.should.not.match(/\bopen\b/); }); it('has aria-labelledby same id as toggle button', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); const menuNode = node.children[1]; buttonNode.getAttribute('id').should.equal(menuNode.getAttribute('aria-labelledby')); }); describe('PropType validation', () => { describe('children', () => { it('menu is exclusive', () => { const props = { children: [ <Dropdown.Toggle/>, <Dropdown.Menu/>, <Dropdown.Menu/> ] }; BaseDropdown.propTypes.children(props, 'children', 'Dropdown') .message.should.match(/Duplicate children.*bsRole: menu/); }); it('menu is required', () => { const props = { children: [ <Dropdown.Toggle/> ] }; BaseDropdown.propTypes.children(props, 'children', 'Dropdown') .message.should.match(/Missing a required child.*bsRole: menu/); }); it('toggles are not exclusive', () => { const props = { children: [ <Dropdown.Toggle/>, <Dropdown.Toggle/>, <Dropdown.Menu/> ] }; expect(BaseDropdown.propTypes.children(props, 'children', 'Dropdown')) .to.not.exist; }); it('toggle is required', () => { const props = { children: [ <Dropdown.Menu/> ] }; BaseDropdown.propTypes.children(props, 'children', 'Dropdown') .message.should.match(/Missing a required child.*bsRole: toggle/); }); }); }); describe('focusable state', () => { let focusableContainer; beforeEach(() => { focusableContainer = document.createElement('div'); document.body.appendChild(focusableContainer); }); afterEach(() => { React.unmountComponentAtNode(focusableContainer); document.body.removeChild(focusableContainer); }); it('when focused and closed sets focus on first menu item when the key "down" is pressed', () => { const instance = React.render(simpleDropdown, focusableContainer); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); buttonNode.focus(); ReactTestUtils.Simulate.keyDown(buttonNode, { keyCode: keycode('down') }); const firstMenuItemAnchor = React.findDOMNode( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]); document.activeElement.should.equal(firstMenuItemAnchor); }); it('when focused and open does not toggle closed when the key "down" is pressed', () => { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); ReactTestUtils.Simulate.click(buttonNode); ReactTestUtils.Simulate.keyDown(buttonNode, { keyCode: keycode('down') }); node.className.should.match(/\bopen\b/); buttonNode.getAttribute('aria-expanded').should.equal('true'); }); // This test is more complicated then it appears to need. This is // because there was an intermittent failure of the test when not structured this way // The failure occured when all tests in the suite were run together, but not a subset of the tests. // // I am fairly confident that the failure is due to a test specific conflict and not an actual bug. it('when open and the key "esc" is pressed the menu is closed and focus is returned to the button', () => { const instance = React.render( <Dropdown defaultOpen role="menuitem" id="test-id"> {dropdownChildren} </Dropdown> , focusableContainer); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); const firstMenuItemAnchor = React.findDOMNode(ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]); document.activeElement.should.equal(firstMenuItemAnchor); ReactTestUtils.Simulate.keyDown(firstMenuItemAnchor, { type: 'keydown', keyCode: keycode('esc') }); document.activeElement.should.equal(buttonNode); }); it('when open and the key "tab" is pressed the menu is closed and focus is progress to the next focusable element', done => { const instance = React.render( <div> {simpleDropdown} <input type='text' id='next-focusable' /> </div>, focusableContainer); const node = ReactTestUtils.findRenderedComponentWithType(instance, Dropdown); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(node, 'BUTTON')); ReactTestUtils.Simulate.click(buttonNode); buttonNode.getAttribute('aria-expanded').should.equal('true'); ReactTestUtils.Simulate.keyDown(buttonNode, { key: keycode('tab'), keyCode: keycode('tab') }); setTimeout(() => { buttonNode.getAttribute('aria-expanded').should.equal('false'); done(); }); // simulating a tab event doesn't actually shift focus. // at least that seems to be the case according to SO. // hence no assert on the input having focus. }); }); });
tests/react_native_tests/test_data/native_code/Component/storybook/stories/UserConnect/index.js
ibhubs/sketch-components
import React from 'react' import { storiesOf } from '@storybook/react-native' import { action } from '@storybook/addon-actions' import { linkTo } from '@storybook/addon-links' import UserConnect from 'app/components/UserConnect' storiesOf('UserConnect', module) .add('default', () => ( <UserConnect buttonName={'CONNECT'} job={'Oceanographer'} name={'Peter'} ></UserConnect>))
src/component/base/label/label.js
babizhu/webApp
/** * Created by liu_k on 2015/11/27. */ import React, { Component } from 'react'; import styles from './label.scss'; class Label extends Component { render() { const dot = this.props.text; return ( <span className="label bg-success-400">{this.props.text}</span> ); } } Label.propTypes = {}; Label.defaultProps = {}; export default Label;
static/src/components/Home/index.js
dternyak/React-Redux-Flask
import React from 'react'; export const Home = () => <section> <div className="container text-center"> <h1>Hello</h1> </div> </section>;
ajax/libs/rxjs/2.2.26/rx.js
bryantrobbins/cdnjs
// 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 // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; 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)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 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 = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[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'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // 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; 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 slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; 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); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; 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, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @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 (exception) { this._onError(exception); }; /** * 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(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); 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 (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; 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)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * 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 AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * 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 Error('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; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * 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) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence 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); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * 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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { 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. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences 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 args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences 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 args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @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 = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @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 (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @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) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (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 (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var 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; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * 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 () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @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(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @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 AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * 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) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto 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) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * 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 Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(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 o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); 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; } }.call(this));
yycomponent/form/Form.js
77ircloud/yycomponent
import React from 'react'; import { Form as _Form, } from 'antd'; const messages = { "default": 'Validation error on field %s', required: '%s不能为空', "enum": '%s must be one of %s', whitespace: '%s不能有空格', date: { format: '%s date %s is invalid for format %s', parse: '%s date could not be parsed, %s is invalid ', invalid: '%s date %s is invalid' }, types: { string: '%s is not a %s', method: '%s is not a %s (function)', array: '%s is not an %s', object: '%s is not an %s', number: '%s不是数字(%s) ', date: '%s is not a %s', "boolean": '%s is not a %s', integer: '%s is not an %s', "float": '%s is not a %s', regexp: '%s is not a valid %s', email: '%s格式不正确', url: '%s is not a valid %s', hex: '%s is not a valid %s' }, string: { len: '%s必须是%s个字符', min: '%s不能少于%s个字符', max: '%s不能大于%s个字符', range: '%s字符长度在%s-%s之间' }, number: { len: '%s必须在%s位数', min: '%s不能小于%s', max: '%s不能大于%s', range: '%s必须在%s-%s之间' }, array: { len: '%s must be exactly %s in length', min: '%s cannot be less than %s in length', max: '%s cannot be greater than %s in length', range: '%s must be between %s and %s in length' }, pattern: { mismatch: '%s值%s不符合%s' }, clone: function clone() { var cloned = JSON.parse(JSON.stringify(this)); cloned.clone = this.clone; return cloned; } } class Form extends React.Component{ constructor(props){ super(props); } static defaultProps={ trigger:[document.body.ontouchstart===undefined?'hover':'click'] } render() { return (<_Form {...this.props}/>); } } Form.defaultProps = { prefixCls: 'ant-form', layout: 'horizontal', hideRequiredMark: false, onSubmit(e) { e.preventDefault(); }, }; /**重写Form create**/ Form._create = _Form.create; Form.create = (options)=> { options = Object.assign({ withRef: true, validateMessages: messages, onFieldsChange:(props,fields)=>{ for(let fieldName in fields){ let field=fields[fieldName]; if(field.value&&field.value.trim){ field.value=field.value.trim(); } let errors=field.errors; if(errors){ errors.forEach((error)=>{ let label = document.querySelector('form.ant-form label[for="' + error.field + '"]');//eslint-disable-line if (label) { error.message = error.message.replace(error.field, label.innerText); if(/email$/.test(error.message)){ error.message=error.message.replace(/email$/,''); } } }); } } } }, options); return Form._create(options); }; Form.mapPropsToFields=(props)=>{ if(props.fields){ let fields={}; for(let name in props.fields){ fields[name]={value:props.fields[name]}; } return fields; } return props; }; export default Form
js/jquery.min.js
Anyway-Design/Anyway-Tab
/*! 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);
src/components/e30.js
prexsa/m3specs
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { Button, Divider, Header, Image, List, Menu } from 'semantic-ui-react'; import Navigation from './Navigation'; import GearRatio from './GearRatio'; import OverView from './overview'; import PressReviews from './pressreviews'; import Diy from './diy'; import MarketValue from './marketvalue'; class e30 extends Component { render() { var spacing = { marginBottom: '10px' } const specs = this.props.specs[0]; const editorials = this.props.editorials[0]; //console.log('Props: ', specs); return ( <div className='car-details-container'> <Navigation /> <Divider hidden={true} /> <div> <div className='center margins'> <List horizontal> <List.Item> <a href='#overview'> <List.Icon name='file text outline' size='big' style={spacing} color='grey'/> <Header as='h4' color='grey' size='tiny'>OVERVIEW</Header> </a> </List.Item> <List.Item> <a href='#gear-ratio'> <List.Icon name='cogs' size='big' style={spacing} color='grey'/> <Header as='h4' color='grey' size='tiny'>GEAR RATIO CALCULATIONS</Header> </a> </List.Item> <List.Item> <a href='#press'> <List.Icon name='newspaper' size='big' style={spacing} color='grey'/> <Header as='h4' color='grey' size='tiny'>PRESS & REVIEWS</Header> </a> </List.Item> <List.Item> <a href='#market-value'> <List.Icon name='dollar' size='big' style={spacing} color='grey'/> <Header as='h4' color='grey' size='tiny'>ESTIMATED MARKET VALUE</Header> </a> </List.Item> <List.Item> <a href='#listings'> <List.Icon name='list' size='big' style={spacing} style={{'marginBottom': '25px'}} color='grey'/> <Header as='h4' color='grey' size='tiny'>DIY (DO IT YOURSELF)</Header> </a> </List.Item> </List> </div> <OverView equipment={specs} /> <GearRatio /> <PressReviews editorials={editorials} /> <MarketValue equipment={specs} /> <Diy /> </div> </div> ) } } function mapStateToProps(state) { return { specs: state.specs, editorials: state.editorials, autotrader: state.autotrader } } export default connect(mapStateToProps)(e30);
src/parseRoutes.js
UgnisSoftware/react-subrouter
import React from 'react'; /** Example: <SubRoute handler={Pending}> <SubRoute name="deposit" handler={Deposit}> // trailingName <SubRoute name="card" handler={Card}/> // default subroute for "deposit" (first in a list) <SubRoute name="bank" handler={Bank}/> </SubRoute> <SubRoute name="status" handler={Status}/> <SubRoute name="info" handler={Info}/> </SubRoute> will be parsed into: { card: [Deposit, Card], bank: [Deposit, Bank], status: [Status], info: [Info] _default: Pending _trailingNames: { card: [deposit], bank: [deposit] } } */ function recursiveParse(child, routes, handlers = [], trailingNames= []){ handlers.push(child.props.handler); if(!child.props.children){ if(!child.props.name) throw new Error('No name on a last route node'); if(routes[child.props.name]) throw new Error('Name duplication: '+child.props.name); routes[child.props.name] = handlers; // add trailing names if(trailingNames.length){ routes._trailingNames[child.props.name] = trailingNames; } } else { if(child.props.name){ trailingNames.push(child.props.name); } for(let kid of child.props.children){ recursiveParse(kid, routes, handlers.slice(), trailingNames.slice()) } } } function parseRoutes(element){ let routes = { _trailingNames: {} }; let children = element.props.children; routes._default = element.props.handler; React.Children.forEach(children, function (child) { recursiveParse(child, routes); }); return routes; } module.exports = parseRoutes;
src/svg-icons/image/texture.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTexture = (props) => ( <SvgIcon {...props}> <path d="M19.51 3.08L3.08 19.51c.09.34.27.65.51.9.25.24.56.42.9.51L20.93 4.49c-.19-.69-.73-1.23-1.42-1.41zM11.88 3L3 11.88v2.83L14.71 3h-2.83zM5 3c-1.1 0-2 .9-2 2v2l4-4H5zm14 18c.55 0 1.05-.22 1.41-.59.37-.36.59-.86.59-1.41v-2l-4 4h2zm-9.71 0h2.83L21 12.12V9.29L9.29 21z"/> </SvgIcon> ); ImageTexture = pure(ImageTexture); ImageTexture.displayName = 'ImageTexture'; ImageTexture.muiName = 'SvgIcon'; export default ImageTexture;
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
dsaved/africhat-platform-0.1
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; import ActorClient from 'utils/ActorClient'; import Inputs from 'utils/Inputs'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import ComposeActionCreators from 'actions/ComposeActionCreators'; import GroupStore from 'stores/GroupStore'; import PreferencesStore from 'stores/PreferencesStore'; import ComposeStore from 'stores/ComposeStore'; import AvatarItem from 'components/common/AvatarItem.react'; import MentionDropdown from 'components/common/MentionDropdown.react'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = () => { return { text: ComposeStore.getText(), profile: ActorClient.getUser(ActorClient.getUid()), sendByEnter: PreferencesStore.sendByEnter, mentions: ComposeStore.getMentions() }; }; @ReactMixin.decorate(PureRenderMixin) class ComposeSection extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired }; static childContextTypes = { muiTheme: React.PropTypes.object }; constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); GroupStore.addChangeListener(this.onChange); ComposeStore.addChangeListener(this.onChange); PreferencesStore.addChangeListener(this.onChange); } componentWillUnmount() { GroupStore.removeChangeListener(this.onChange); ComposeStore.removeChangeListener(this.onChange); PreferencesStore.removeChangeListener(this.onChange); } onChange = () => { this.setState(getStateFromStores()); }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } onMessageChange = event => { let text = event.target.value; ComposeActionCreators.onTyping(this.props.peer, text, this.getCaretPosition()); }; onKeyDown = event => { if (this.state.mentions === null) { if (this.state.sendByEnter === 'true') { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this.sendTextMessage(); } } else { if (event.keyCode === KeyCodes.ENTER && event.metaKey) { event.preventDefault(); this.sendTextMessage(); } } } }; sendTextMessage = () => { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } ComposeActionCreators.cleanText(); }; onSendFileClick = () => { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }; onSendPhotoClick = () => { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }; onFileInputChange = () => { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }; onPhotoInputChange = () => { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }; onPaste = event => { let preventDefault = false; _.forEach(event.clipboardData.items, (item) => { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }; onMentionSelect = (mention) => { ComposeActionCreators.insertMention(this.props.peer, this.state.text, this.getCaretPosition(), mention); this.refs.area.getDOMNode().focus(); }; onMentionClose = () => { ComposeActionCreators.closeMention(); }; getCaretPosition = () => { let el = this.refs.area.getDOMNode(); let selection = Inputs.getInputSelection(el); return selection.start; }; render() { const { text, profile, mentions } = this.state; return ( <section className="compose" onPaste={this.onPaste}> <MentionDropdown mentions={mentions} onSelect={this.onMentionSelect} onClose={this.onMentionClose}/> <AvatarItem className="my-avatar" image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this.onMessageChange} onKeyDown={this.onKeyDown} value={text} ref="area"/> <footer className="compose__footer row"> <button className="button" onClick={this.onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this.onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this.onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this.onPhotoInputChange} type="file"/> </div> </section> ); } } export default ComposeSection;
js/comments.min.js
msoma-ke/msoma-ke.github.io
/* BSD License For React software Copyright (c) 2013-present, Facebook, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name Facebook 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 HOLDER 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. Modernizr 3.0.0pre (Custom Build) | MIT */ webpackJsonp([12],[function(c,b,a){a(3364);a(3363);a(1149);a(1797);a(1006);a(774);a(1005);a(1147);a(1426);a(1449);a(1435);a(1423);a(1287);a(1430);a(1286);a(524);a(604);a(606);a(1429);a(1291);a(1842);a(1436);a(1285);a(1008);a(1007);a(943);a(1010);a(1013);a(1014);a(1009);a(1011);a(1332);a(1827);a(1836);a(1438);a(1145);a(1168);a(1167);a(1333);a(1293);a(1294);a(1012);a(1843);a(1443);a(1162);a(605);a(1439);a(1334);a(1441);a(1440);a(1288);a(1442);a(1444);a(1335);a(1798)},,function(c,b,a){c.exports=a(301)}, function(c,b){c.exports=function(){var a=[];a.toString=function(){for(var a=[],b=0;b<this.length;b++){var d=this[b];d[2]?a.push("@media "+d[2]+"{"+d[1]+"}"):a.push(d[1])}return a.join("")};a.i=function(b,f){"string"===typeof b&&(b=[[null,b,""]]);for(var d={},g=0;g<this.length;g++){var h=this[g][0];"number"===typeof h&&(d[h]=!0)}for(g=0;g<b.length;g++)if(h=b[g],"number"!==typeof h[0]||!d[h[0]])f&&!h[2]?h[2]=f:f&&(h[2]="("+h[2]+") and ("+f+")"),a.push(h)};return a}},,,function(c,b,a){function e(a,d){for(var b= 0;b<a.length;b++){var g=a[b],f=n[g.id];if(f){f.refs++;for(var e=0;e<f.parts.length;e++)f.parts[e](g.parts[e]);for(;e<g.parts.length;e++)f.parts.push(h(g.parts[e],d))}else{f=[];for(e=0;e<g.parts.length;e++)f.push(h(g.parts[e],d));n[g.id]={id:g.id,refs:1,parts:f}}}}function f(a){for(var d=[],b={},g=0;g<a.length;g++){var f=a[g],e=f[0],f={css:f[1],media:f[2],sourceMap:f[3]};b[e]?b[e].parts.push(f):d.push(b[e]={id:e,parts:[f]})}return d}function d(){var a=document.createElement("style"),d=q();a.type="text/css"; d.appendChild(a);return a}function g(){var a=document.createElement("link"),d=q();a.rel="stylesheet";d.appendChild(a);return a}function h(a,b){var f,e,h;if(b.singleton){var p=t++;f=r||(r=d());e=k.bind(null,f,p,!1);h=k.bind(null,f,p,!0)}else a.sourceMap&&"function"===typeof URL&&"function"===typeof URL.createObjectURL&&"function"===typeof URL.revokeObjectURL&&"function"===typeof Blob&&"function"===typeof btoa?(f=g(),e=m.bind(null,f),h=function(){f.parentNode.removeChild(f);f.href&&URL.revokeObjectURL(f.href)}): (f=d(),e=l.bind(null,f),h=function(){f.parentNode.removeChild(f)});e(a);return function(d){d?d.css===a.css&&d.media===a.media&&d.sourceMap===a.sourceMap||e(a=d):h()}}function k(a,d,b,g){b=b?"":g.css;a.styleSheet?a.styleSheet.cssText=p(d,b):(b=document.createTextNode(b),g=a.childNodes,g[d]&&a.removeChild(g[d]),g.length?a.insertBefore(b,g[d]):a.appendChild(b))}function l(a,d){var b=d.css,g=d.media;g&&a.setAttribute("media",g);if(a.styleSheet)a.styleSheet.cssText=b;else{for(;a.firstChild;)a.removeChild(a.firstChild); a.appendChild(document.createTextNode(b))}}function m(a,d){var b=d.css,g=d.sourceMap;g&&(b+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(g))))+" */");b=new Blob([b],{type:"text/css"});g=a.href;a.href=URL.createObjectURL(b);g&&URL.revokeObjectURL(g)}var n={};b=function(a){var d;return function(){"undefined"===typeof d&&(d=a.apply(this,arguments));return d}};var s=b(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}), q=b(function(){return document.head||document.getElementsByTagName("head")[0]}),r=null,t=0;c.exports=function(a,d){d=d||{};"undefined"===typeof d.singleton&&(d.singleton=s());var b=f(a);e(b,d);return function(a){for(var g=[],k=0;k<b.length;k++){var h=n[b[k].id];h.refs--;g.push(h)}a&&(k=f(a),e(k,d));for(k=0;k<g.length;k++)if(h=g[k],0===h.refs){for(a=0;a<h.parts.length;a++)h.parts[a]();delete n[h.id]}}};var p=function(){var a=[];return function(d,b){a[d]=b;return a.filter(Boolean).join("\n")}}()},, ,,function(c,b,a){c.exports=function(a,b,d,g,h,k,l,c){if(!a){if(void 0===b)a=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var n=[d,g,h,k,l,c],s=0;a=Error(b.replace(/%s/g,function(){return n[s++]}));a.name="Invariant Violation"}a.framesToPop=1;throw a;}}},function(c,b,a){function e(){for(var a="",d,b=0;b<arguments.length;b++)if(d=arguments[b])if("string"===typeof d||"number"===typeof d)a+=" "+d;else if("[object Array]"=== Object.prototype.toString.call(d))a+=" "+e.apply(null,d);else if("object"===typeof d)for(var f in d)d.hasOwnProperty(f)&&d[f]&&(a+=" "+f);return a.substr(1)}var f,d;"undefined"!==typeof c&&c.exports&&(c.exports=e);!(f=[],d=function(){return e}.apply(b,f),void 0!==d&&(c.exports=d))},function(c,b,a){b=a(40);c.exports=b},function(c,b,a){b.__esModule=!0;c=a(16);b.default=(c&&c.__esModule?c:{"default":c}).default||function(a){for(var b=1;b<arguments.length;b++){var d=arguments[b],g;for(g in d)Object.prototype.hasOwnProperty.call(d, g)&&(a[g]=d[g])}return a}},function(c,b){var a=Object.prototype.hasOwnProperty,e=Object.prototype.propertyIsEnumerable;c.exports=function(){try{if(!Object.assign)return!1;var a=new String("abc");a[5]="de";if("5"===Object.getOwnPropertyNames(a)[0])return!1;for(var d={},a=0;10>a;a++)d["_"+String.fromCharCode(a)]=a;if("0123456789"!==Object.getOwnPropertyNames(d).map(function(a){return d[a]}).join(""))return!1;var b={};"abcdefghijklmnopqrst".split("").forEach(function(a){b[a]=a});return"abcdefghijklmnopqrst"!== Object.keys(Object.assign({},b)).join("")?!1:!0}catch(e){return!1}}()?Object.assign:function(b,d){var g,h;if(null===b||void 0===b)throw new TypeError("Object.assign cannot be called with null or undefined");h=Object(b);for(var k,l=1;l<arguments.length;l++){g=Object(arguments[l]);for(var c in g)a.call(g,c)&&(h[c]=g[c]);if(Object.getOwnPropertySymbols){k=Object.getOwnPropertySymbols(g);for(var n=0;n<k.length;n++)e.call(g,k[n])&&(h[k[n]]=g[k[n]])}}return h}},,,function(c,b,a){function e(a){for(var d;d= a._renderedComponent;)a=d;return a}function f(a,d){var b=e(a);b._nativeNode=d;d[n]=b}function d(a,d){if(!(a._flags&m.hasCachedChildNodes)){var b=a._renderedChildren,g=d.firstChild,h;a:for(h in b)if(b.hasOwnProperty(h)){var c=b[h],n=e(c)._domID;if(null!=n){for(;null!==g;g=g.nextSibling)if(1===g.nodeType&&g.getAttribute(l)===String(n)||8===g.nodeType&&g.nodeValue===" react-text: "+n+" "||8===g.nodeType&&g.nodeValue===" react-empty: "+n+" "){f(c,g);continue a}k(!1)}}a._flags|=m.hasCachedChildNodes}} function g(a){if(a[n])return a[n];for(var b=[];!a[n];)if(b.push(a),a.parentNode)a=a.parentNode;else return null;for(var g,f;a&&(f=a[n]);a=b.pop())g=f,b.length&&d(f,a);return g}b=a(53);var h=a(192),k=a(10),l=b.ID_ATTRIBUTE_NAME,m=h,n="__reactInternalInstance$"+Math.random().toString(36).slice(2);c.exports={getClosestInstanceFromNode:g,getInstanceFromNode:function(a){var d=g(a);return null!=d&&d._nativeNode===a?d:null},getNodeFromInstance:function(a){void 0===a._nativeNode?k(!1):void 0;if(a._nativeNode)return a._nativeNode; for(var b=[];!a._nativeNode;)b.push(a),!a._nativeParent?k(!1):void 0,a=a._nativeParent;for(;b.length;a=b.pop())d(a,a._nativeNode);return a._nativeNode},precacheChildNodes:d,precacheNode:f,uncacheNode:function(a){var d=a._nativeNode;d&&(delete d[n],a._nativeNode=null)}}},function(c,b){b.__esModule=!0;b.default=function(a,b){var f={},d;for(d in a)0<=b.indexOf(d)||Object.prototype.hasOwnProperty.call(a,d)&&(f[d]=a[d]);return f}},function(c,b,a){c.exports={"default":a(311),__esModule:!0}},,,function(c, b){var a=!!("undefined"!==typeof window&&window.document&&window.document.createElement);c.exports={canUseDOM:a,canUseWorkers:"undefined"!==typeof Worker,canUseEventListeners:a&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:a&&!!window.screen,isInWorker:!a}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,"/**\n* These button styles should be used with composes to style ordinary elements\n* as Squarespace interface buttons. Before turning just anything into a Button,\n* you should consider the Button component, or the ButtonLink componenet as they\n* are already styled appropriately.\n*\n* Usage:\n* .yourClass {\n* composes: primary from 'styles/utils/buttons.less';\n* }\n*\n* Available button flavors:\n* - primary (white text on a black box)\n* - minor (black text on a grey box)\n* - text (black text on a transparent bg)\n* - caution (minor button that turns red when hovered)\n* - recommend (blue button, for recommending options)\n*\n* Also Available:\n* - buttonContainer (add it to an element which holds a bunch of buttons)\n*\n*/\n.buttons-button-3XBmN {\n display: block;\n border: none;\n cursor: pointer;\n outline: none;\n padding: 11px;\n text-align: center;\n transition: background-color 0.1s ease-in-out;\n line-height: 22px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n font-family: inherit;\n font-size: 11px;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n width: 100%;\n color: white;\n background: #3e3e3e;\n text-transform: uppercase;\n font-weight: 500;\n}\n.buttons-button-3XBmN:hover {\n background-color: #252525;\n}\n.buttons-button-3XBmN:disabled {\n color: #a1a1a1;\n}\n.buttons-button-3XBmN:disabled:hover {\n background-color: inherit;\n}\n.buttons-primary-F4ys4 {\n}\n.buttons-primary-F4ys4:disabled,\n.buttons-primary-F4ys4:disabled:hover {\n background-color: #3e3e3e;\n}\n.buttons-recommend-3YqTI {\n background-color: #14aaff;\n}\n.buttons-recommend-3YqTI:hover {\n background-color: #008fe0;\n}\n.buttons-recommend-3YqTI:disabled,\n.buttons-recommend-3YqTI:disabled:hover {\n color: #e6e6e6;\n background-color: #14aaff;\n}\n.buttons-minor-20buK {\n background-color: #e4e4e4;\n color: #3e3e3e;\n}\n.buttons-minor-20buK:hover {\n background-color: #d0d0d0;\n}\n.buttons-minor-20buK:disabled,\n.buttons-minor-20buK:disabled:hover {\n background-color: #e4e4e4;\n}\n.buttons-caution-1Md6C {\n background-color: #f2f2f2;\n color: #3e3e3e;\n}\n.buttons-caution-1Md6C:hover {\n background-color: #f0523d;\n color: #FFF;\n}\n.buttons-caution-1Md6C:disabled,\n.buttons-caution-1Md6C:disabled:hover {\n color: inherit;\n}\n.buttons-inset-2PoTV {\n background-color: #FFF;\n color: #3e3e3e;\n}\n.buttons-inset-2PoTV:hover {\n background-color: #FFF;\n}\n.buttons-inset-2PoTV:disabled,\n.buttons-inset-2PoTV:disabled:hover {\n background-color: #FFF;\n}\n.buttons-text-38SIE {\n background: transparent;\n display: inline-block;\n font-weight: 500;\n font-size: 12px;\n white-space: nowrap;\n line-height: 33px;\n padding: 0 11px;\n transition: all 0.1s ease-in-out;\n color: #3e3e3e !important;\n border-bottom: none;\n outline: none;\n text-align: left;\n}\n.buttons-text-38SIE:hover,\n.buttons-text-38SIE:hover a {\n color: black !important;\n background: transparent;\n}\n.buttons-text-38SIE a {\n border: none;\n display: inline-block;\n outline: none;\n}\n.buttons-buttonContainer-2B8i- {\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n border-top: 1px solid #e4e4e4;\n margin-top: 33px;\n background: transparent;\n}\n.buttons-buttonContainer-2B8i- button {\n border-right: 1px solid #e4e4e4;\n}\n.buttons-buttonContainer-2B8i- button:last-child {\n border-right: none;\n}\n", ""]);b.locals={button:"buttons-button-3XBmN",primary:"buttons-primary-F4ys4 buttons-button-3XBmN",recommend:"buttons-recommend-3YqTI buttons-button-3XBmN",minor:"buttons-minor-20buK buttons-button-3XBmN",caution:"buttons-caution-1Md6C buttons-button-3XBmN",inset:"buttons-inset-2PoTV buttons-button-3XBmN",text:"buttons-text-38SIE buttons-button-3XBmN",buttonContainer:"buttons-buttonContainer-2B8i-"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,'/**\n * Retina-friendly icon creator\n * @param {string} @iconName Name of the icon image; presumes an @2x version.\n * @param {color} [color=transparent] Background color on the icon.\n *\n * Uses named parameters: http://lesscss.org/features/#mixins-parametric-feature-named-parameters\n *\n * If your icon is interactable/clickable, set a :hover rule with opacity: 1\n */\n/**\n * For posterity:\n *\n * .myLocalClass {\n * composes: checkAfter from "styles/utils/icons.less";\n * }\n */\n.icons-search-eAltR {\n background: white url('+ a(507)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-search-eAltR {\n background-image: url("+a(508)+");\n background-size: 16px;\n }\n}\n.icons-add-1Bq-3 {\n background: transparent url("+a(459)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-add-1Bq-3 {\n background-image: url("+ a(460)+");\n background-size: 16px;\n }\n}\n.icons-clear-337pM {\n background: transparent url("+a(479)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-clear-337pM {\n background-image: url("+a(480)+");\n background-size: 16px;\n }\n}\n.icons-clearLight-3rMja {\n background: transparent url("+ a(481)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-clearLight-3rMja {\n background-image: url("+a(482)+");\n background-size: 16px;\n }\n}\n.icons-trash-2Z1EA {\n background: transparent url("+a(513)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-trash-2Z1EA {\n background-image: url("+ a(514)+");\n background-size: 12px 16px;\n }\n}\n.icons-trash-2Z1EA:hover {\n background: transparent url("+a(222)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-trash-2Z1EA:hover {\n background-image: url("+a(223)+");\n background-size: 12px 16px;\n }\n}\n.icons-trashLight-dP-B8 {\n background: transparent url("+ a(515)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-trashLight-dP-B8 {\n background-image: url("+a(516)+");\n background-size: 12px 16px;\n }\n}\n.icons-trashLight-dP-B8:hover {\n background: transparent url("+a(222)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-trashLight-dP-B8:hover {\n background-image: url("+ a(223)+");\n background-size: 12px 16px;\n }\n}\n.icons-check-2QsR6 {\n background: #3e3e3e url("+a(182)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-check-2QsR6 {\n background-image: url("+a(221)+");\n background-size: 9px;\n }\n}\n.icons-checkDark-1z5WA {\n background: transparent url("+ a(470)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-checkDark-1z5WA {\n background-image: url("+a(471)+");\n background-size: 9px;\n }\n}\n.icons-checkAfter-3x9WO:after {\n background: #3e3e3e url("+a(182)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-checkAfter-3x9WO:after {\n background-image: url("+ a(221)+");\n background-size: 9px;\n }\n}\n.icons-upload-dkLdX {\n background: transparent url("+a(517)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-upload-dkLdX {\n background-image: url("+a(518)+");\n background-size: 32px;\n }\n}\n.icons-avatar-1ZP6V {\n background: rgba(0, 0, 0, 0.06) url("+ a(436)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-avatar-1ZP6V {\n background-image: url("+a(465)+");\n background-size: 44px;\n }\n}\n.icons-gearSmall-VjJyS {\n background: transparent url("+a(487)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-gearSmall-VjJyS {\n background-image: url("+ a(488)+");\n background-size: 16px;\n }\n}\n.icons-pencilSmall-2_EYb {\n background: transparent url("+a(485)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-pencilSmall-2_EYb {\n background-image: url("+a(486)+");\n background-size: 16px;\n }\n}\n.icons-trashSmall-3D6DB {\n background: transparent url("+ a(183)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-trashSmall-3D6DB {\n background-image: url("+a(184)+");\n background-size: 9px;\n }\n}\n.icons-trashSmall-3D6DB:hover {\n background: #f0523d url("+a(183)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-trashSmall-3D6DB:hover {\n background-image: url("+ a(184)+");\n background-size: 9px;\n }\n}\n.icons-chevronLight-2U7C8 {\n background: transparent url("+a(472)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-chevronLight-2U7C8 {\n background-image: url("+a(473)+");\n background-size: 16px;\n }\n}\n.icons-chevronRight-2SazZ {\n background: transparent url("+ a(319)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-chevronRight-2SazZ {\n background-image: url("+a(474)+");\n background-size: 16px;\n }\n}\n.icons-chevronDark-gMWfL {\n background: transparent url("+a(167)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-chevronDark-gMWfL {\n background-image: url("+ a(168)+");\n background-size: 16px;\n }\n}\n.icons-circleLogoDark-5pXiw {\n background: transparent url("+a(477)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-circleLogoDark-5pXiw {\n background-image: url("+a(478)+");\n background-size: 16px;\n }\n}\n.icons-gettyLogo-1eoHv {\n background: transparent url("+ a(496)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n opacity: 1.0;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-gettyLogo-1eoHv {\n background-image: url("+a(497)+");\n background-size: 93px;\n }\n}\n.icons-chevronUpDark-WeyFV {\n background: transparent url("+a(475)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-chevronUpDark-WeyFV {\n background-image: url("+ a(476)+");\n background-size: 16px;\n }\n}\n.icons-chevronDownDark-dr5gD {\n background: transparent url("+a(167)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-chevronDownDark-dr5gD {\n background-image: url("+a(168)+");\n background-size: 16px;\n }\n}\n.icons-arrowDark-28pPD {\n background: transparent url("+ a(463)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-arrowDark-28pPD {\n background-image: url("+a(464)+");\n background-size: 16px;\n }\n}\n.icons-file-1zImv {\n background: transparent url("+a(489)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-file-1zImv {\n background-image: url("+ a(490)+");\n background-size: 32px;\n }\n}\n.icons-shoppingCart-1NY0m {\n background: transparent url("+a(509)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-shoppingCart-1NY0m {\n background-image: url("+a(510)+");\n background-size: 16px;\n }\n}\n.icons-squarespace-OCtbv {\n background: transparent url("+ a(503)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-squarespace-OCtbv {\n background-image: url("+a(504)+");\n background-size: 33px;\n }\n}\n.icons-page-1x6xI {\n background: transparent url("+a(505)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-page-1x6xI {\n background-image: url("+ a(506)+");\n background-size: 32px;\n }\n}\n.icons-products-ULgml {\n background: transparent url("+a(483)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-products-ULgml {\n background-image: url("+a(484)+");\n background-size: 32px;\n }\n}\n.icons-splash-page-1IqP- {\n background: transparent url("+ a(511)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-splash-page-1IqP- {\n background-image: url("+a(512)+");\n background-size: 32px;\n }\n}\n.icons-folder-13zDR {\n background: transparent url("+a(491)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-folder-13zDR {\n background-image: url("+ a(492)+");\n background-size: 32px;\n }\n}\n.icons-projects-1ODhi {\n background: transparent url("+a(499)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-projects-1ODhi {\n background-image: url("+a(500)+");\n background-size: 32px;\n }\n}\n.icons-gallery-2X4Na {\n background: transparent url("+ a(493)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-gallery-2X4Na {\n background-image: url("+a(494)+");\n background-size: 32px;\n }\n}\n.icons-calendar-L73vE {\n background: transparent url("+a(468)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-calendar-L73vE {\n background-image: url("+ a(469)+");\n background-size: 32px;\n }\n}\n.icons-album-31bvq {\n background: transparent url("+a(461)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-album-31bvq {\n background-image: url("+a(462)+");\n background-size: 32px;\n }\n}\n.icons-blog-1zZZI {\n background: transparent url("+a(466)+ ") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-blog-1zZZI {\n background-image: url("+a(467)+");\n background-size: 32px;\n }\n}\n.icons-link-1XF_q {\n background: transparent url("+a(501)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-link-1XF_q {\n background-image: url("+ a(502)+");\n background-size: 32px;\n }\n}\n.icons-getty-tzCpZ {\n background: transparent url("+a(345)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-getty-tzCpZ {\n background-image: url("+a(495)+");\n background-size: 32px;\n }\n}\n.icons-image-kM71M {\n background: transparent url("+ a(346)+") center center no-repeat;\n cursor: pointer;\n opacity: 0.76;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .icons-image-kM71M {\n background-image: url("+a(498)+");\n background-size: 32px;\n }\n}\n",""]);b.locals={search:"icons-search-eAltR",add:"icons-add-1Bq-3",clear:"icons-clear-337pM",clearLight:"icons-clearLight-3rMja",trash:"icons-trash-2Z1EA",trashLight:"icons-trashLight-dP-B8", check:"icons-check-2QsR6",checkDark:"icons-checkDark-1z5WA",checkAfter:"icons-checkAfter-3x9WO",upload:"icons-upload-dkLdX",avatar:"icons-avatar-1ZP6V",gearSmall:"icons-gearSmall-VjJyS",pencilSmall:"icons-pencilSmall-2_EYb",trashSmall:"icons-trashSmall-3D6DB",chevronLight:"icons-chevronLight-2U7C8",chevronRight:"icons-chevronRight-2SazZ",chevronDark:"icons-chevronDark-gMWfL",circleLogoDark:"icons-circleLogoDark-5pXiw",gettyLogo:"icons-gettyLogo-1eoHv",chevronUpDark:"icons-chevronUpDark-WeyFV",chevronDownDark:"icons-chevronDownDark-dr5gD", arrowDark:"icons-arrowDark-28pPD",file:"icons-file-1zImv",shoppingCart:"icons-shoppingCart-1NY0m",squarespace:"icons-squarespace-OCtbv",page:"icons-page-1x6xI",products:"icons-products-ULgml","splash-page":"icons-splash-page-1IqP-",folder:"icons-folder-13zDR",projects:"icons-projects-1ODhi",gallery:"icons-gallery-2X4Na",calendar:"icons-calendar-L73vE",album:"icons-album-31bvq",blog:"icons-blog-1zZZI",link:"icons-link-1XF_q",getty:"icons-getty-tzCpZ",image:"icons-image-kM71M"}},,,,function(c,b,a){b= a(2).PropTypes;c.exports=b.oneOf(["damask","midnight","denarius"])},,function(c,b,a){var e={enableMeasure:!1,storedMeasure:function(a,d,b){return b},measureMethods:function(a,d,b){},measure:function(a,d,b){return b},injection:{injectMeasure:function(a){e.storedMeasure=a}}};c.exports=e},,function(c,b,a){Object.defineProperty(b,"__esModule",{value:!0});var e=a(2),f=e&&e.__esModule?e:{"default":e},d=a(276);b["default"]=function(a,b){var e=void 0===b?a:b;return function(){if(!(0,d.isFunction)(a.getStores))throw Error("connectToStores() expects the wrapped component to have a static getStores() method"); if(!(0,d.isFunction)(a.getPropsFromStores))throw Error("connectToStores() expects the wrapped component to have a static getPropsFromStores() method");return f["default"].createClass({displayName:"StoreConnection",getInitialState:function(){return a.getPropsFromStores(this.props,this.context)},componentWillReceiveProps:function(d){this.setState(a.getPropsFromStores(d,this.context))},componentDidMount:function(){var d=this;this.storeListeners=a.getStores(this.props,this.context).map(function(a){return a.listen(d.onChange)}); a.componentDidConnect&&a.componentDidConnect(this.props,this.context)},componentWillUnmount:function(){this.storeListeners.forEach(function(a){return a()})},onChange:function(){this.setState(a.getPropsFromStores(this.props,this.context))},render:function(){return f["default"].createElement(e,(0,d.assign)({},this.props,this.state))}})}()};c.exports=b["default"]},function(c,b,a){c.exports=a(329)},function(c,b,a){var e=a(14),f=a(47);a(12);a(112);var d="function"===typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")|| 60103,g={key:!0,ref:!0,__self:!0,__source:!0},h=function(a,b,g,f,e,h,c){return{$$typeof:d,type:a,key:b,ref:g,props:c,_owner:h}};h.createElement=function(a,d,b){var e,c={},q=null,r=null,t=null,p=null;if(null!=d)for(e in r=void 0===d.ref?null:d.ref,q=void 0===d.key?null:""+d.key,t=void 0===d.__self?null:d.__self,p=void 0===d.__source?null:d.__source,d)d.hasOwnProperty(e)&&!g.hasOwnProperty(e)&&(c[e]=d[e]);var u=arguments.length-2;if(1===u)c.children=b;else if(1<u){for(var v=Array(u),x=0;x<u;x++)v[x]= arguments[x+2];c.children=v}if(a&&a.defaultProps)for(e in u=a.defaultProps,u)void 0===c[e]&&(c[e]=u[e]);return h(a,q,r,t,p,f.current,c)};h.createFactory=function(a){var d=h.createElement.bind(null,a);d.type=a;return d};h.cloneAndReplaceKey=function(a,d){return h(a.type,d,a.ref,a._self,a._source,a._owner,a.props)};h.cloneElement=function(a,d,b){var c,s=e({},a.props),q=a.key,r=a.ref,t=a._self,p=a._source,u=a._owner;if(null!=d){void 0!==d.ref&&(r=d.ref,u=f.current);void 0!==d.key&&(q=""+d.key);var v; a.type&&a.type.defaultProps&&(v=a.type.defaultProps);for(c in d)d.hasOwnProperty(c)&&!g.hasOwnProperty(c)&&(s[c]=void 0===d[c]&&void 0!==v?v[c]:d[c])}c=arguments.length-2;if(1===c)s.children=b;else if(1<c){v=Array(c);for(var x=0;x<c;x++)v[x]=arguments[x+2];s.children=v}return h(a.type,q,r,t,p,u,s)};h.isValidElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===d};c.exports=h},function(c,b,a){function e(){!y.ReactReconcileTransaction||!v?r(!1):void 0}function f(){this.reinitializeTransaction(); this.dirtyComponentsLength=null;this.callbackQueue=k.getPooled();this.reconcileTransaction=y.ReactReconcileTransaction.getPooled(!0)}function d(a,d){return a._mountOrder-d._mountOrder}function g(a){var b=a.dirtyComponentsLength;b!==t.length?r(!1):void 0;t.sort(d);for(var g=0;g<b;g++){var f=t[g],e=f._pendingCallbacks;f._pendingCallbacks=null;var k;m.logTopLevelRenders&&(k=f,f._currentElement.props===f._renderedComponent._currentElement&&(k=f._renderedComponent),k="React update: "+k.getName(),console.time(k)); s.performUpdateIfNecessary(f,a.reconcileTransaction);k&&console.timeEnd(k);if(e)for(var h=0;h<e.length;h++)a.callbackQueue.enqueue(e[h],f.getPublicInstance())}}function h(a){e();v.isBatchingUpdates?t.push(a):v.batchedUpdates(h,a)}b=a(14);var k=a(187),l=a(54),m=a(196),n=a(30),s=a(59),q=a(111),r=a(10),t=[],p=k.getPooled(),u=!1,v=null,x=[{initialize:function(){this.dirtyComponentsLength=t.length},close:function(){this.dirtyComponentsLength!==t.length?(t.splice(0,this.dirtyComponentsLength),w()):t.length= 0}},{initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}}];b(f.prototype,q.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null;k.release(this.callbackQueue);this.callbackQueue=null;y.ReactReconcileTransaction.release(this.reconcileTransaction);this.reconcileTransaction=null},perform:function(a,d,b){return q.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,a,d,b)}}); l.addPoolingTo(f);var w=function(){for(;t.length||u;){if(t.length){var a=f.getPooled();a.perform(g,null,a);f.release(a)}u&&(u=!1,a=p,p=k.getPooled(),a.notifyAll(),k.release(a))}},w=n.measure("ReactUpdates","flushBatchedUpdates",w),y={ReactReconcileTransaction:null,batchedUpdates:function(a,d,b,g,f,k){e();v.batchedUpdates(a,d,b,g,f,k)},enqueueUpdate:h,flushBatchedUpdates:w,injection:{injectReconcileTransaction:function(a){!a?r(!1):void 0;y.ReactReconcileTransaction=a},injectBatchingStrategy:function(a){!a? r(!1):void 0;"function"!==typeof a.batchedUpdates?r(!1):void 0;"boolean"!==typeof a.isBatchingUpdates?r(!1):void 0;v=a}},asap:function(a,d){!v.isBatchingUpdates?r(!1):void 0;p.enqueue(a,d);u=!0}};c.exports=y},,function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(11),g=a(2);b=a(41);var h=a(28),k=a(273),l=a(253);a=g.createClass({displayName:"Field",mixins:[b],propTypes:{errorClassName:g.PropTypes.string,errorMessage:g.PropTypes.string,label:g.PropTypes.string, theme:h.isRequired},getDefaultProps:function(){return{theme:"damask"}},render:function(){var a=this.props,b=a.label,h=a.children,c=a.errorMessage,r=a.className,t=a.errorClassName,p=a.theme,a=(0,f.default)(a,"label children errorMessage className errorClassName theme".split(" ")),r=d(l.container,l[p],"sqs-field",r),t=d(l.errorMessage,"sqs-field-error",t);return g.createElement("div",(0,e.default)({},a,{className:r}),b?g.createElement(k,{theme:p,title:b}):null,h,c&&g.createElement("div",{className:t}, c))}});c.exports=a},,,function(c,b){function a(a){return function(){return a}}var e=function(){};e.thatReturns=a;e.thatReturnsFalse=a(!1);e.thatReturnsTrue=a(!0);e.thatReturnsNull=a(null);e.thatReturnsThis=function(){return this};e.thatReturnsArgument=function(a){return a};c.exports=e},function(c,b,a){c.exports=a(559)},function(c,b,a){b=a(87);a=b({bubbled:null,captured:null});b={topLevelTypes:b({topAbort:null,topAnimationEnd:null,topAnimationIteration:null,topAnimationStart:null,topBlur:null,topCanPlay:null, topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topInvalid:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null, topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topTransitionEnd:null, topVolumeChange:null,topWaiting:null,topWheel:null}),PropagationPhases:a};c.exports=b},function(c,b,a){function e(a,d,b,f){this.dispatchConfig=a;this._targetInst=d;this.nativeEvent=b;a=this.constructor.Interface;for(var e in a)a.hasOwnProperty(e)&&((d=a[e])?this[e]=d(b):"target"===e?this.target=f:this[e]=b[e]);this.isDefaultPrevented=(null!=b.defaultPrevented?b.defaultPrevented:!1===b.returnValue)?g.thatReturnsTrue:g.thatReturnsFalse;this.isPropagationStopped=g.thatReturnsFalse;return this}var f= a(14),d=a(54),g=a(40);a(12);var h="dispatchConfig _targetInst nativeEvent isDefaultPrevented isPropagationStopped _dispatchListeners _dispatchInstances".split(" ");b={type:null,target:null,currentTarget:g.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};f(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue= !1,this.isDefaultPrevented=g.thatReturnsTrue)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():a.cancelBubble=!0,this.isPropagationStopped=g.thatReturnsTrue)},persist:function(){this.isPersistent=g.thatReturnsTrue},isPersistent:g.thatReturnsFalse,destructor:function(){var a=this.constructor.Interface,d;for(d in a)this[d]=null;for(a=0;a<h.length;a++)this[h[a]]=null}});e.Interface=b;e.augmentClass=function(a,b){var g=function(){};g.prototype=this.prototype; g=new g;f(g,a.prototype);a.prototype=g;a.prototype.constructor=a;a.Interface=f({},this.Interface,b);a.augmentClass=this.augmentClass;d.addPoolingTo(a,d.fourArgumentPooler)};d.addPoolingTo(e,d.fourArgumentPooler);c.exports=e},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};a=a(9);b=function(){function a(){(0,e.default)(this,a)}(0,f.default)(a,[{key:"bootstrap",value:function(a){this.dispatch(a)}}]);return a}();a=a.createActions(b);window.StaticActions= a;c.exports=a},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".typography-ellipsis-1791i {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.typography-headline-1705A {\n text-transform: uppercase;\n font-weight: 500;\n}\n.typography-headlineLarge-719Ty {\n line-height: 44px;\n font-size: 16px;\n}\n",""]);b.locals={ellipsis:"typography-ellipsis-1791i",headline:"typography-headline-1705A",headlineLarge:"typography-headlineLarge-719Ty typography-headline-1705A"}},function(c, b,a){c.exports={"default":a(310),__esModule:!0}},function(c,b){c.exports={current:null}},function(c,b){c.exports=function(a){for(var b in a)if(a.hasOwnProperty(b))return b;return null}},function(c,b,a){b=a(224);a=a(229)(b);c.exports=a},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b.__esModule=!0;c=a(307);var f=e(c);c=a(235);var d=e(c);a=a(77);var g=e(a);b.default=function(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+ ("undefined"===typeof b?"undefined":(0,g.default)(b)));a.prototype=(0,d.default)(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(f.default?(0,f.default)(a,b):a.__proto__=b)}},function(c,b,a){b.__esModule=!0;var e=(c=a(77))&&c.__esModule?c:{"default":c};b.default=function(a,d){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return d&&("object"===("undefined"===typeof d?"undefined":(0,e.default)(d))||"function"===typeof d)? d:a}},function(c,b,a){Object.defineProperty(b,"__esModule",{value:!0});var e=(a=a(26))&&a.__esModule?a:{"default":a};b["default"]=function(a){a.config={setState:function(a,b){return this.state=b},getState:function(a){return a},onSerialize:function(a){return a.toJS()},onDeserialize:function(a){return e["default"].fromJS(a)}};return a};c.exports=b["default"]},function(c,b,a){var e=a(10),f={MUST_USE_PROPERTY:1,HAS_SIDE_EFFECTS:2,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32, injectDOMPropertyConfig:function(a){var b=f,k=a.Properties||{},c=a.DOMAttributeNamespaces||{},m=a.DOMAttributeNames||{},n=a.DOMPropertyNames||{},s=a.DOMMutationMethods||{};a.isCustomAttribute&&d._isCustomAttributeFunctions.push(a.isCustomAttribute);for(var q in k){d.properties.hasOwnProperty(q)?e(!1):void 0;a=q.toLowerCase();var r=k[q];a={attributeName:a,attributeNamespace:null,propertyName:q,mutationMethod:null,mustUseProperty:(r&b.MUST_USE_PROPERTY)===b.MUST_USE_PROPERTY,hasSideEffects:(r&b.HAS_SIDE_EFFECTS)=== b.HAS_SIDE_EFFECTS,hasBooleanValue:(r&b.HAS_BOOLEAN_VALUE)===b.HAS_BOOLEAN_VALUE,hasNumericValue:(r&b.HAS_NUMERIC_VALUE)===b.HAS_NUMERIC_VALUE,hasPositiveNumericValue:(r&b.HAS_POSITIVE_NUMERIC_VALUE)===b.HAS_POSITIVE_NUMERIC_VALUE,hasOverloadedBooleanValue:(r&b.HAS_OVERLOADED_BOOLEAN_VALUE)===b.HAS_OVERLOADED_BOOLEAN_VALUE};!a.mustUseProperty&&a.hasSideEffects?e(!1):void 0;!(1>=a.hasBooleanValue+a.hasNumericValue+a.hasOverloadedBooleanValue)?e(!1):void 0;m.hasOwnProperty(q)&&(a.attributeName=m[q]); c.hasOwnProperty(q)&&(a.attributeNamespace=c[q]);n.hasOwnProperty(q)&&(a.propertyName=n[q]);s.hasOwnProperty(q)&&(a.mutationMethod=s[q]);d.properties[q]=a}}},d={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:":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",ATTRIBUTE_NAME_CHAR:":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\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040", properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(a){for(var b=0;b<d._isCustomAttributeFunctions.length;b++)if((0,d._isCustomAttributeFunctions[b])(a))return!0;return!1},injection:f};c.exports=d},function(c,b,a){var e=a(10),f=function(a){if(this.instancePool.length){var d=this.instancePool.pop();this.call(d,a);return d}return new this(a)},d=function(a){!(a instanceof this)?e(!1):void 0;a.destructor();this.instancePool.length<this.poolSize&&this.instancePool.push(a)}; c.exports={addPoolingTo:function(a,b){a.instancePool=[];a.getPooled=b||f;a.poolSize||(a.poolSize=10);a.release=d;return a},oneArgumentPooler:f,twoArgumentPooler:function(a,d){if(this.instancePool.length){var b=this.instancePool.pop();this.call(b,a,d);return b}return new this(a,d)},threeArgumentPooler:function(a,d,b){if(this.instancePool.length){var f=this.instancePool.pop();this.call(f,a,d,b);return f}return new this(a,d,b)},fourArgumentPooler:function(a,d,b,f){if(this.instancePool.length){var e= this.instancePool.pop();this.call(e,a,d,b,f);return e}return new this(a,d,b,f)},fiveArgumentPooler:function(a,d,b,f,e){if(this.instancePool.length){var c=this.instancePool.pop();this.call(c,a,d,b,f,e);return c}return new this(a,d,b,f,e)}}},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(240);var f=e(b);b=a(4);var d=e(b);b=a(7);var g=e(b);b=a(235);b=e(b);var h=a(935),k=a(145),l=/^[A-Z]{3}$/,m=function(){this.name="IncompatibleMoneyError";this.message="Monies are not compatible for arithmetic."; Error.captureStackTrace(this)};m.prototype=(0,b.default)(Error.prototype);var n=function(a){this.name="InvalidCurrencyError";this.message="Invalid currency code: "+a;this.currencyCode=a;Error.captureStackTrace(this)};n.prototype=(0,b.default)(Error.prototype);var s=function(){for(var a=arguments.length,d=Array(a),b=0;b<a;b++)d[b]=arguments[b];var g=d[0].currencyCode;if(k(d,function(a){return a.currencyCode!==g}))throw new m;};a=function(){function a(b,g){(0,d.default)(this,a);if("string"!==typeof g|| !l.test(g))throw new n(g);this.value=new h(b);this.currencyCode=g;(0,f.default)(this)}(0,g.default)(a,[{key:"toJson",value:function(){return{decimalValue:this.value.toString(),currencyCode:this.currencyCode}}},{key:"toFloat",value:function(){return parseFloat(this.value)}},{key:"isPositive",value:function(){return this.value.gt(0)}},{key:"isNegative",value:function(){return this.value.lt(0)}},{key:"isZero",value:function(){return this.value.eq(0)}},{key:"compare",value:function(a){s(this,a);return this.value.cmp(a.value)}}, {key:"divide",value:function(d){return new a(this.value.div(d),this.currencyCode)}},{key:"multiply",value:function(d){return new a(this.value.times(d),this.currencyCode)}},{key:"add",value:function(d){s(this,d);return new a(this.value.plus(d.value),this.currencyCode)}},{key:"subtract",value:function(d){s(this,d);return new a(this.value.minus(d.value),this.currencyCode)}}],[{key:"fromJson",value:function(d){var b=d.decimalValue,g=d.value;d=d.currencyCode;void 0===b&&void 0!==g&&(b=g);return new a(b, d)}}]);return a}();a.IncompatibleMoneyError=m;a.InvalidCurrencyError=n;c.exports=a},function(c,b){var a=Math.max;c.exports=function(b,f){if("function"!=typeof b)throw new TypeError("Expected a function");f=a(void 0===f?b.length-1:+f||0,0);return function(){for(var d=arguments,g=-1,h=a(d.length-f,0),k=Array(h);++g<h;)k[g]=d[f+g];switch(f){case 0:return b.call(this,k);case 1:return b.call(this,d[0],k);case 2:return b.call(this,d[0],d[1],k)}h=Array(f+1);for(g=-1;++g<f;)h[g]=d[g];h[f]=k;return b.apply(this, h)}}},function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2);b=d.PropTypes;var g=a(11),h=a(734);a=d.createClass({displayName:"LoadingSpinner",propTypes:{color:b.oneOf(["light","dark"]),size:b.oneOf("extra-small small default large extra-large xx-large".split(" ")),isCentered:b.bool,delay:b.number},getDefaultProps:function(){return{color:"dark",size:"default",isCentered:!1,delay:0}},getInitialState:function(){return{visible:0===this.props.delay}}, componentDidMount:function(){0<this.props.delay&&this.initDelayTimeout()},componentWillUnmount:function(){this.delayTimer&&clearTimeout(this.delayTimer)},initDelayTimeout:function(){var a=this;this.delayTimer=setTimeout(function(){a.setState({visible:!0})},this.props.delay)},render:function(){var a,b=this.props,c=b.size,n=b.color,s=b.isCentered,q=b.className,b=(0,f.default)(b,["size","color","isCentered","className"]),r=this.state.visible,c=g(q,h.spinner,h[c],h[n],(a={},a[h.centered]=s,a));return r? d.createElement("div",(0,e.default)({},b,{className:c})):null}});c.exports=a},function(c,b,a){function e(a){if(g){var b=a.node,f=a.children;if(f.length)for(a=0;a<f.length;a++)h(b,f[a],null);else null!=a.html?b.innerHTML=a.html:null!=a.text&&d(b,a.text)}}function f(a){return{node:a,children:[],html:null,text:null}}b=a(113);var d=a(213),g="undefined"!==typeof document&&"number"===typeof document.documentMode||"undefined"!==typeof navigator&&"string"===typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent), h=b(function(a,d,b){11===d.node.nodeType?(e(d),a.insertBefore(d.node,b)):(a.insertBefore(d.node,b),e(d))});f.insertTreeBefore=h;f.replaceChildWithTree=function(a,d){a.parentNode.replaceChild(d.node,a);e(d)};f.queueChild=function(a,d){g?a.children.push(d):a.node.appendChild(d.node)};f.queueHTML=function(a,d){g?a.html=d:a.node.innerHTML=d};f.queueText=function(a,b){g?a.text=b:d(a.node,b)};c.exports=f},function(c,b,a){function e(){f.attachRefs(this,this._currentElement)}var f=a(393);a(81);c.exports= {mountComponent:function(a,b,f,k,c){f=a.mountComponent(b,f,k,c);a._currentElement&&null!=a._currentElement.ref&&b.getReactMountReady().enqueue(e,a);return f},getNativeNode:function(a){return a.getNativeNode()},unmountComponent:function(a,b){f.detachRefs(a,a._currentElement);a.unmountComponent(b)},receiveComponent:function(a,b,h,k){var c=a._currentElement;if(!(b===c&&k===a._context)){var m=f.shouldUpdateRefs(c,b);m&&f.detachRefs(a,c);a.receiveComponent(b,h,k);m&&(a._currentElement&&null!=a._currentElement.ref)&& h.getReactMountReady().enqueue(e,a)}},performUpdateIfNecessary:function(a,b){a.performUpdateIfNecessary(b)}}},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(13);var f=e(b);b=a(16);var d=e(b);b=a(18);var g=e(b);b=a(77);var h=e(b),k=a(11),l=a(2),m=a(33),n=a(773);b=l.PropTypes;var s=a(707).alignNodes,q=a(343),r=a(28),t=a(814),p=document.querySelector(".sqs-damask")||document.createElement("div");n.setAppElement(p);b=l.createClass({displayName:"Modal",propTypes:{anchor:q.anchor, isOpen:b.bool.isRequired,onAfterOpen:b.func,onRequestClose:b.func,width:b.oneOfType([b.number,b.string]),testAttr:b.string,height:b.oneOfType([b.number,b.string]),position:q.position,theme:r.isRequired,overlayClassName:l.PropTypes.string},getDefaultProps:function(){return{width:350,anchor:"window",position:"center",height:"auto",onRequestClose:function(){console.log("[Modal.props.onRequestClose] callback not implemented.")},theme:"damask"}},getInitialState:function(){return{}},setCoords:function(){var a= this;setTimeout(function(){a.setState(a.getCoords())},0)},getCoords:function(){var a=this.props,d=a.position,a=a.anchor,b=this.refs.modal;if("object"===("undefined"===typeof a?"undefined":(0,h.default)(a)))a=m.findDOMNode(a);else if("window"===a)return null;(a=s(b,a,d))||console.warn("unsupported configuration used:",d);return a},componentWillReceiveProps:function(a){window.Y&&(!this.props.isOpen&&a.isOpen?window.Y.Squarespace.EscManager.disable():this.props.isOpen&&!a.isOpen&&setTimeout(function(){window.Y.Squarespace.EscManager.enable()}, 150))},componentDidMount:function(){this.props.isOpen&&"window"!==this.props.anchor&&this.setCoords()},componentWillUnmount:function(){window.Y&&window.Y.Squarespace.EscManager.enable()},componentDidUpdate:function(a,d){this.props.isOpen&&(!a.isOpen&&"window"!==this.props.anchor)&&this.setCoords()},render:function(){var a,b=this.props,e=b.anchor,h=b.children,c=b.className,p=b.overlayClassName,m=b.height,s=b.style,r=b.testAttr,q=b.width,O=b.theme,b=(0,g.default)(b,"anchor children className overlayClassName height style testAttr width theme".split(" ")), s=(0,d.default)({width:q,height:m},s),q=this.state,m=q.left,q=q.top,m=m&&q?{content:{left:m,top:q}}:{},q=k(t.content,(a={},a[t.positionToPoint]="window"!==e,a));return l.createElement(n,(0,f.default)({closeTimeoutMS:300,style:m,className:q,overlayClassName:k(t.overlay,p),anchor:e},b),l.createElement("div",{ref:"modal",className:k(t.container,t[O],c),style:s,"data-test":r},h))}});b.Body=a(781);b.Button=a(782);b.Footer=a(783);b.Header=a(784);c.exports=b},,,,function(c,b,a){var e=(b=a(13))&&b.__esModule? b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11),h=a(37),k=a(592),l=a(275),m=a(253);a=a(28);a=d.createClass({displayName:"Input",propTypes:{errorClassName:d.PropTypes.string,errorMessage:d.PropTypes.string,hasErrors:d.PropTypes.bool,className:d.PropTypes.string,inline:d.PropTypes.bool,placeholder:d.PropTypes.string,type:d.PropTypes.oneOf(["text","password","email","number","tel"]),label:d.PropTypes.string,readOnly:d.PropTypes.bool,size:d.PropTypes.oneOf(["large"]),theme:a.isRequired, value:d.PropTypes.any,onBlur:d.PropTypes.func,onFocus:d.PropTypes.func},getDefaultProps:function(){return{type:"text",readOnly:!1,theme:"damask"}},getInitialState:function(){return{isFocused:!1}},focus:function(){var a=this.refs.input;a&&a.focus()},select:function(){this.refs.input.select()},handleFocus:function(a,d){this.setState({isFocused:!0});if(this.props.onFocus)this.props.onFocus(a,d)},handleBlur:function(a,d){this.setState({isFocused:!1});if(this.props.onBlur)this.props.onBlur(a,d)},render:function(){var a, b=this.props,c=b.children,r=b.className,t=b.errorClassName,p=b.errorMessage,u=b.inline,v=b.hasErrors,x=b.readOnly,w=b.size,y=b.theme,B=b.label,A=b.placeholder,b=(0,f.default)(b,"children className errorClassName errorMessage inline hasErrors readOnly size theme label placeholder".split(" ")),z=this.state.isFocused,r=g(k[y],r,(a={"sqs-text":!0,"has-errors":p||v},a[k.errors]=p||v,a[k.readOnly]=x,a[k.large]="large"===w,a[m.inline]=u,a[k.focused]=z,a[k.hasValue]=!!this.props.value,a[k.unlabeled]=!B,a)); a="midnight"===y&&!A?B:A;return d.createElement(h,{label:B,className:r,theme:y,errorClassName:t,errorMessage:p},d.createElement("input",(0,e.default)({className:l.formField,ref:"input"},b,{placeholder:a,onFocus:this.handleFocus,onBlur:this.handleBlur})),c&&d.createElement("div",{className:"description"},c))}});c.exports=a},function(c,b,a){function e(a,b,c,s){s||(s=[]);for(var q=-1,r=a.length;++q<r;){var t=a[q];k(t)&&h(t)&&(c||g(t)||d(t))?b?e(t,b,c,s):f(s,t):c||(s[s.length]=t)}return s}var f=a(352), d=a(161),g=a(27),h=a(62),k=a(73);c.exports=e},function(c,b,a){var e=a(79),f=a(106),d=a(109),g=a(207),h=a(208),k=a(10),l={},m=null,n=function(a,d){a&&(f.executeDispatchesInOrder(a,d),a.isPersistent()||a.constructor.release(a))},s=function(a){return n(a,!0)},q=function(a){return n(a,!1)};c.exports={injection:{injectEventPluginOrder:e.injectEventPluginOrder,injectEventPluginsByName:e.injectEventPluginsByName},putListener:function(a,d,b){"function"!==typeof b?k(!1):void 0;(l[d]||(l[d]={}))[a._rootNodeID]= b;var g=e.registrationNameModules[d];g&&g.didPutListener&&g.didPutListener(a,d,b)},getListener:function(a,d){var b=l[d];return b&&b[a._rootNodeID]},deleteListener:function(a,d){var b=e.registrationNameModules[d];b&&b.willDeleteListener&&b.willDeleteListener(a,d);(b=l[d])&&delete b[a._rootNodeID]},deleteAllListeners:function(a){for(var d in l)if(l[d][a._rootNodeID]){var b=e.registrationNameModules[d];b&&b.willDeleteListener&&b.willDeleteListener(a,d);delete l[d][a._rootNodeID]}},extractEvents:function(a, d,b,f){for(var k,h=e.plugins,c=0;c<h.length;c++){var l=h[c];l&&(l=l.extractEvents(a,d,b,f))&&(k=g(k,l))}return k},enqueueEvents:function(a){a&&(m=g(m,a))},processEventQueue:function(a){var b=m;m=null;a?h(b,s):h(b,q);m?k(!1):void 0;d.rethrowCaughtError()},__purge:function(){l={}},__getListenerBank:function(){return l}}},function(c,b,a){function e(a,b,d){if(b=q(a,d.dispatchConfig.phasedRegistrationNames[b?s.bubbled:s.captured]))d._dispatchListeners=m(d._dispatchListeners,b),d._dispatchInstances=m(d._dispatchInstances, a)}function f(a){a&&a.dispatchConfig.phasedRegistrationNames&&l.traverseTwoPhase(a._targetInst,e,a)}function d(a){if(a&&a.dispatchConfig.phasedRegistrationNames){var d=a._targetInst,d=d?l.getParentInstance(d):null;l.traverseTwoPhase(d,e,a)}}function g(a,d,b){if(b&&b.dispatchConfig.registrationName&&(d=q(a,b.dispatchConfig.registrationName)))b._dispatchListeners=m(b._dispatchListeners,d),b._dispatchInstances=m(b._dispatchInstances,a)}function h(a){a&&a.dispatchConfig.registrationName&&g(a._targetInst, null,a)}b=a(42);var k=a(66),l=a(106),m=a(207),n=a(208);a(12);var s=b.PropagationPhases,q=k.getListener;c.exports={accumulateTwoPhaseDispatches:function(a){n(a,f)},accumulateTwoPhaseDispatchesSkipTarget:function(a){n(a,d)},accumulateDirectDispatches:function(a){n(a,h)},accumulateEnterLeaveDispatches:function(a,d,b,f){l.traverseEnterLeave(b,f,g,a,d)}}},function(c,b,a){function e(a,d,b,e){return f.call(this,a,d,b,e)}var f=a(43),d=a(116);f.augmentClass(e,{view:function(a){if(a.view)return a.view;a=d(a); return null!=a&&a.window===a?a:(a=a.ownerDocument)?a.defaultView||a.parentWindow:window},detail:function(a){return a.detail||0}});c.exports=e},,,function(c,b,a){var e=a(556),f=a(78);c.exports=function(a){return e(a,f(a))}},function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11);b=a(41);var h=a(37),k=a(547);a=d.createClass({displayName:"Button",mixins:[b],propTypes:{isDisabled:d.PropTypes.bool,type:d.PropTypes.oneOf("primary caution minor recommend text inset".split(" ")), className:d.PropTypes.string,containerClassName:d.PropTypes.string,label:d.PropTypes.string,onClick:d.PropTypes.func},getDefaultProps:function(){return{onClick:function(){},className:"",type:"minor",isDisabled:!1}},render:function(){var a=this.props,b=a.className,c=a.containerClassName,s=a.onClick,q=a.label,r=a.children,t=a.type,p=a.isDisabled,a=(0,f.default)(a,"className containerClassName onClick label children type isDisabled".split(" ")),b=g(k.button,"sqs-button",k[t],b);return d.createElement(h, {className:c},d.createElement("button",(0,e.default)({},a,{className:b,onClick:s,disabled:p}),r||q))}});c.exports=a},,,,function(c,b,a){var e=a(65),f=a(100),d=a(244),g=a(245);b=a(56)(function(a,b){return null==a?{}:"function"==typeof b[0]?g(a,f(b[0],b[1],3)):d(a,e(b))});c.exports=b},,,function(c,b,a){function e(){if(g)for(var a in h){var b=h[a],e=g.indexOf(a);!(-1<e)?d(!1):void 0;if(!k.plugins[e]){!b.extractEvents?d(!1):void 0;k.plugins[e]=b;var e=b.eventTypes,c;for(c in e){var q;var r=e[c];q=b;var t= c;k.eventNameDispatchConfigs.hasOwnProperty(t)?d(!1):void 0;k.eventNameDispatchConfigs[t]=r;var p=r.phasedRegistrationNames;if(p){r=void 0;for(r in p)p.hasOwnProperty(r)&&f(p[r],q,t);q=!0}else r.registrationName?(f(r.registrationName,q,t),q=!0):q=!1;!q?d(!1):void 0}}}}function f(a,b,f){k.registrationNameModules[a]?d(!1):void 0;k.registrationNameModules[a]=b;k.registrationNameDependencies[a]=b.eventTypes[f].dependencies}var d=a(10),g=null,h={},k={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{}, registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(a){g?d(!1):void 0;g=Array.prototype.slice.call(a);e()},injectEventPluginsByName:function(a){var b=!1,f;for(f in a)if(a.hasOwnProperty(f)){var g=a[f];if(!h.hasOwnProperty(f)||h[f]!==g)h[f]?d(!1):void 0,h[f]=g,b=!0}b&&e()},getPluginModuleForEvent:function(a){a=a.dispatchConfig;if(a.registrationName)return k.registrationNameModules[a.registrationName]||null;for(var b in a.phasedRegistrationNames)if(a.phasedRegistrationNames.hasOwnProperty(b)){var d= k.registrationNameModules[a.phasedRegistrationNames[b]];if(d)return d}return null},_resetEventPlugins:function(){g=null;for(var a in h)h.hasOwnProperty(a)&&delete h[a];k.plugins.length=0;a=k.eventNameDispatchConfigs;for(var b in a)a.hasOwnProperty(b)&&delete a[b];b=k.registrationNameModules;for(var d in b)b.hasOwnProperty(d)&&delete b[d]}};c.exports=k},function(c,b,a){b=a(14);var e=a(42),f=a(79),d=a(385),g=a(206),h=a(331),k=a(118),l,m={},n=!1,s=0,q={topAbort:"abort",topAnimationEnd:h("animationend")|| "animationend",topAnimationIteration:h("animationiteration")||"animationiteration",topAnimationStart:h("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:h("transitionend")||"transitionend",topVolumeChange:"volumechange", topWaiting:"waiting",topWheel:"wheel"},r="_reactListenersID"+String(Math.random()).slice(2),t=b({},d,{ReactEventListener:null,injection:{injectReactEventListener:function(a){a.setHandleTopLevel(t.handleTopLevel);t.ReactEventListener=a}},setEnabled:function(a){t.ReactEventListener&&t.ReactEventListener.setEnabled(a)},isEnabled:function(){return!(!t.ReactEventListener||!t.ReactEventListener.isEnabled())},listenTo:function(a,b){var d;Object.prototype.hasOwnProperty.call(b,r)||(b[r]=s++,m[b[r]]={});d= m[b[r]];for(var g=f.registrationNameDependencies[a],h=e.topLevelTypes,c=0;c<g.length;c++){var l=g[c];if(!d.hasOwnProperty(l)||!d[l])l===h.topWheel?k("wheel")?t.ReactEventListener.trapBubbledEvent(h.topWheel,"wheel",b):k("mousewheel")?t.ReactEventListener.trapBubbledEvent(h.topWheel,"mousewheel",b):t.ReactEventListener.trapBubbledEvent(h.topWheel,"DOMMouseScroll",b):l===h.topScroll?k("scroll",!0)?t.ReactEventListener.trapCapturedEvent(h.topScroll,"scroll",b):t.ReactEventListener.trapBubbledEvent(h.topScroll, "scroll",t.ReactEventListener.WINDOW_HANDLE):l===h.topFocus||l===h.topBlur?(k("focus",!0)?(t.ReactEventListener.trapCapturedEvent(h.topFocus,"focus",b),t.ReactEventListener.trapCapturedEvent(h.topBlur,"blur",b)):k("focusin")&&(t.ReactEventListener.trapBubbledEvent(h.topFocus,"focusin",b),t.ReactEventListener.trapBubbledEvent(h.topBlur,"focusout",b)),d[h.topBlur]=!0,d[h.topFocus]=!0):q.hasOwnProperty(l)&&t.ReactEventListener.trapBubbledEvent(l,q[l],b),d[l]=!0}},trapBubbledEvent:function(a,b,d){return t.ReactEventListener.trapBubbledEvent(a, b,d)},trapCapturedEvent:function(a,b,d){return t.ReactEventListener.trapCapturedEvent(a,b,d)},ensureScrollValueMonitoring:function(){void 0===l&&(l=document.createEvent&&"pageX"in document.createEvent("MouseEvent"));!l&&!n&&(t.ReactEventListener.monitorScrollValue(g.refreshScrollValues),n=!0)}});c.exports=t},function(c,b,a){b=a(382);c.exports={debugTool:b}},function(c,b,a){c.exports={}},function(c,b,a){b=a(87)({prop:null,context:null,childContext:null});c.exports=b},function(c,b,a){function e(a,b, d,e){return f.call(this,a,b,d,e)}var f=a(68),d=a(206);b={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a(115),button:function(a){var b=a.button;return"which"in a?b:2===b?2:4===b?1:0},buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},pageX:function(a){return"pageX"in a?a.pageX:a.clientX+d.currentScrollLeft},pageY:function(a){return"pageY"in a?a.pageY:a.clientY+ d.currentScrollTop}};f.augmentClass(e,b);c.exports=e},function(c,b){function a(a){return e[a]}var e={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},f=/[&><"']/g;c.exports=function(b){return(""+b).replace(f,a)}},function(c,b,a){c.exports={}},function(c,b,a){var e=a(10);c.exports=function(a){var b={},g;!(a instanceof Object)||Array.isArray(a)?e(!1):void 0;for(g in a)a.hasOwnProperty(g)&&(b[g]=g);return b}},function(c,b,a){var e=a(63),f=a(31),d=a(181);c.exports=function(a,b){var k=(f.Object|| {})[a]||Object[a],c={};c[a]=b(k);e(e.S+e.F*d(function(){k(1)}),"Object",c)}},function(c,b,a){b=a(49);a=a(299)(b);c.exports=a},function(c,b,a){b=c.exports=a(3)();b.push([c.id,"/**\n * Helper utils for positioning content.\n * example:\n * .myClass {\n * composes: center from 'styles/utils/layout.less';\n * }\n *\n * Available helpers:\n * - center: Center the content both vertically and horizontally.\n */\n.layout-center-3PXlj {\n position: absolute;\n top: 50%;\n left: 50%;\n -webkit-transform: translateX(-50%) translateY(-50%);\n -ms-transform: translateX(-50%) translateY(-50%);\n transform: translateX(-50%) translateY(-50%);\n}\n.layout-pillNeue-2iUZn {\n display: inline-block;\n font-size: 9px;\n vertical-align: middle;\n padding: 0 5.5px;\n text-transform: uppercase;\n font-weight: 500;\n background: #e4e4e4;\n color: #3e3e3e;\n border-radius: 2px;\n transition: background-color 0.1s ease-in-out;\n}\n.layout-pillNeueRed-mi2Vc {\n background: #f0523d;\n color: white;\n}\n", ""]);b.locals={center:"layout-center-3PXlj",pillNeue:"layout-pillNeue-2iUZn",pillNeueRed:"layout-pillNeueRed-mi2Vc layout-pillNeue-2iUZn"}},,,function(c,b){var a={globalGrid:22,globalUiPadding:33,globalColumnWidth:264};a.globalMenuWidth=a.globalColumnWidth;a.globalPanelWidth=1.5*a.globalColumnWidth;a.globalWidePanelWidth=2*a.globalColumnWidth;a.animationDurationInMs=500;c.exports=a},,function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d= a(52),g=a(44),h=a(337),k=a(536);a=function(){function a(){(0,e.default)(this,a);this.state=new k;this.bindActions(h);this.bindListeners({onStaticBootstrap:g.BOOTSTRAP});this.exportPublicMethods({save:this.save})}(0,f.default)(a,[{key:"onStaticBootstrap",value:function(a){this.setState(new k(a.websiteSettings))}},{key:"onUpdate",value:function(a){this.setState(this.state.merge(a))}},{key:"save",value:function(a){a=this.getState().mergeDeep(a).toJS();return h.save(a)}}]);return a}();c.exports=b.createStore(d(a), "WebsiteSettingsStore")},,,,,,function(c,b,a){var e=a(11),f=a(2);b=f.PropTypes;var d=a(41),g=a(37),h=a(735);a=f.createClass({displayName:"Check",mixins:[d],propTypes:{className:b.string,isDisabled:b.bool,onChange:b.func.isRequired,title:b.oneOfType([b.element,b.string]),value:b.bool},getDefaultProps:function(){return{isDisabled:!1,value:!1}},handleChange:function(){var a=this.props,b=a.onChange,d=a.value;a.isDisabled||b({target:{value:!d}})},render:function(){var a,b=this.props,d=b.isDisabled,c=b.value, s=b.title,q=b.children,b=e(b.className,h.checkElement,(a={},a[h.active]=c,a[h.isDisabled]=d,a));a=e(h.container);return f.createElement(g,{className:a,onClick:this.handleChange},f.createElement("div",{className:b},s&&f.createElement("div",{className:"title"},s),q&&f.createElement("div",{className:"description"},q)))}});c.exports=a},function(c,b,a){var e=a(11),f=a(2);b=a(41);var d=a(28),g=a(37),h=a(591);a=f.createClass({displayName:"Description",mixins:[b],propTypes:{theme:d.isRequired,title:f.PropTypes.string}, getDefaultProps:function(){return{theme:"damask"}},render:function(){var a=this.props,b=a.title,d=a.children,a=e("sqs-description",h.container,h[a.theme],a.className);return f.createElement(g,{className:a},b&&f.createElement("div",{className:e("title",h.title)},b),d&&f.createElement("div",{className:e("text",h.text)},d))}});c.exports=a},function(c,b){c.exports={WAITING:1,PROCESSING:2,SUCCESS:3,FAILURE:4,CANCELLED:5,SCHEDULED:6}},function(c,b,a){function e(a,b){Array.isArray(b)&&(b=b[1]);return b? b.nextSibling:a.firstChild}function f(a,b,d){for(;;){var f=b.nextSibling;if(f===d)break;else a.removeChild(f)}}var d=a(58),g=a(359),h=a(199);b=a(30);var k=a(113),l=a(119),m=a(213),n=k(function(a,b,d){a.insertBefore(b,d)});a={dangerouslyReplaceNodeWithMarkup:g.dangerouslyReplaceNodeWithMarkup,replaceDelimitedText:function(a,b,d){var g=a.parentNode,e=a.nextSibling;e===b?d&&n(g,document.createTextNode(d),e):d?(m(e,d),f(g,e,b)):f(g,a,b)},processUpdates:function(a,b){for(var g=0;g<b.length;g++){var k= b[g];switch(k.type){case h.INSERT_MARKUP:var c=e(a,k.afterNode);d.insertTreeBefore(a,k.content,c);break;case h.MOVE_EXISTING:var u=a,c=k.fromNode,v=e(a,k.afterNode);if(Array.isArray(c)){k=u;u=c[1];for(c=c[0];;){var x=c.nextSibling;n(k,c,v);if(c===u)break;c=x}}else n(u,c,v);break;case h.SET_MARKUP:l(a,k.content);break;case h.TEXT_CONTENT:m(a,k.content);break;case h.REMOVE_NODE:c=a,k=k.fromNode,Array.isArray(k)&&(u=k[1],k=k[0],f(c,k,u),c.removeChild(u)),c.removeChild(k)}}}};b.measureMethods(a,"DOMChildrenOperations", {replaceDelimitedText:"replaceDelimitedText"});c.exports=a},function(c,b,a){function e(a){if(l.hasOwnProperty(a))return!0;if(k.hasOwnProperty(a))return!1;if(h.test(a))return l[a]=!0;k[a]=!0;void 0;return!1}function f(a,b){return null==b||a.hasBooleanValue&&!b||a.hasNumericValue&&isNaN(b)||a.hasPositiveNumericValue&&1>b||a.hasOverloadedBooleanValue&&!1===b}var d=a(53);a(375);b=a(30);var g=a(412);a(12);var h=RegExp("^["+d.ATTRIBUTE_NAME_START_CHAR+"]["+d.ATTRIBUTE_NAME_CHAR+"]*$"),k={},l={},m={createMarkupForID:function(a){return d.ID_ATTRIBUTE_NAME+ "="+g(a)},setAttributeForID:function(a,b){a.setAttribute(d.ID_ATTRIBUTE_NAME,b)},createMarkupForRoot:function(){return d.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(a){a.setAttribute(d.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(a,b){var e=d.properties.hasOwnProperty(a)?d.properties[a]:null;if(e){if(f(e,b))return"";var k=e.attributeName;return e.hasBooleanValue||e.hasOverloadedBooleanValue&&!0===b?k+'=""':k+"="+g(b)}return d.isCustomAttribute(a)?null==b?"":a+"="+g(b):null}, createMarkupForCustomAttribute:function(a,b){return!e(a)||null==b?"":a+"="+g(b)},setValueForProperty:function(a,b,g){var e=d.properties.hasOwnProperty(b)?d.properties[b]:null;if(e){var k=e.mutationMethod;if(k)k(a,g);else if(f(e,g))this.deleteValueForProperty(a,b);else if(e.mustUseProperty){if(b=e.propertyName,!e.hasSideEffects||""+a[b]!==""+g)a[b]=g}else b=e.attributeName,(k=e.attributeNamespace)?a.setAttributeNS(k,b,""+g):e.hasBooleanValue||e.hasOverloadedBooleanValue&&!0===g?a.setAttribute(b,""): a.setAttribute(b,""+g)}else d.isCustomAttribute(b)&&m.setValueForAttribute(a,b,g)},setValueForAttribute:function(a,b,d){e(b)&&(null==d?a.removeAttribute(b):a.setAttribute(b,""+d))},deleteValueForProperty:function(a,b){var f=d.properties.hasOwnProperty(b)?d.properties[b]:null;if(f){var g=f.mutationMethod;if(g)g(a,void 0);else if(f.mustUseProperty)if(g=f.propertyName,f.hasBooleanValue)a[g]=!1;else{if(!f.hasSideEffects||""!==""+a[g])a[g]=""}else a.removeAttribute(f.attributeName)}else d.isCustomAttribute(b)&& a.removeAttribute(b)}};b.measureMethods(m,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"});c.exports=m},function(c,b,a){function e(a,b,d,g){var e=a.type||"unknown-event";a.currentTarget=l.getNodeFromInstance(g);b?f.invokeGuardedCallbackWithCatch(e,d,a):f.invokeGuardedCallback(e,d,a);a.currentTarget=null}b=a(42);var f=a(109),d=a(10);a(12);var g,h,k=b.topLevelTypes,l={isEndish:function(a){return a=== k.topMouseUp||a===k.topTouchEnd||a===k.topTouchCancel},isMoveish:function(a){return a===k.topMouseMove||a===k.topTouchMove},isStartish:function(a){return a===k.topMouseDown||a===k.topTouchStart},executeDirectDispatch:function(a){var b=a._dispatchListeners,f=a._dispatchInstances;Array.isArray(b)?d(!1):void 0;a.currentTarget=l.getNodeFromInstance(f);b=b?b(a):null;a.currentTarget=null;a._dispatchListeners=null;a._dispatchInstances=null;return b},executeDispatchesInOrder:function(a,b){var d=a._dispatchListeners, f=a._dispatchInstances;if(Array.isArray(d))for(var g=0;g<d.length&&!a.isPropagationStopped();g++)e(a,b,d[g],f[g]);else d&&e(a,b,d,f);a._dispatchListeners=null;a._dispatchInstances=null},executeDispatchesInOrderStopAtTrue:function(a){var b;a:{b=a._dispatchListeners;var d=a._dispatchInstances;if(Array.isArray(b))for(var f=0;f<b.length&&!a.isPropagationStopped();f++){if(b[f](a,d[f])){b=d[f];break a}}else if(b&&b(a,d)){b=d;break a}b=null}a._dispatchInstances=null;a._dispatchListeners=null;return b},hasDispatches:function(a){return!!a._dispatchListeners}, getInstanceFromNode:function(a){return g.getInstanceFromNode(a)},getNodeFromInstance:function(a){return g.getNodeFromInstance(a)},isAncestor:function(a,b){return h.isAncestor(a,b)},getLowestCommonAncestor:function(a,b){return h.getLowestCommonAncestor(a,b)},getParentInstance:function(a){return h.getParentInstance(a)},traverseTwoPhase:function(a,b,d){return h.traverseTwoPhase(a,b,d)},traverseEnterLeave:function(a,b,d,f,g){return h.traverseEnterLeave(a,b,d,f,g)},injection:{injectComponentTree:function(a){g= a},injectTreeTraversal:function(a){h=a}}};c.exports=l},function(c,b,a){function e(a){!(null==a.checkedLink||null==a.valueLink)?h(!1):void 0}function f(a){e(a);!(null==a.value&&null==a.onChange)?h(!1):void 0}function d(a){e(a);!(null==a.checked&&null==a.onChange)?h(!1):void 0}b=a(203);var g=a(83),h=a(10);a(12);var k={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},l={value:function(a,b,d){return!a[b]||k[a.type]||a.onChange||a.readOnly||a.disabled?null: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(a,b,d){return!a[b]||a.onChange||a.readOnly||a.disabled?null: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:b.func},m={};c.exports={checkPropTypes:function(a,b,d){for(var f in l){if(l.hasOwnProperty(f))var e=l[f](b,f,a,g.prop);e instanceof Error&&!(e.message in m)&&(m[e.message]=!0,d&&d.getName(),void 0)}}, getValue:function(a){return a.valueLink?(f(a),a.valueLink.value):a.value},getChecked:function(a){return a.checkedLink?(d(a),a.checkedLink.value):a.checked},executeOnChange:function(a,b){if(a.valueLink)return f(a),a.valueLink.requestChange(b.target.value);if(a.checkedLink)return d(a),a.checkedLink.requestChange(b.target.checked);if(a.onChange)return a.onChange.call(void 0,b)}}},function(c,b,a){var e=a(10),f=!1,d={unmountIDFromEnvironment:null,replaceNodeWithMarkup:null,processChildrenUpdates:null, injection:{injectEnvironment:function(a){f?e(!1):void 0;d.unmountIDFromEnvironment=a.unmountIDFromEnvironment;d.replaceNodeWithMarkup=a.replaceNodeWithMarkup;d.processChildrenUpdates=a.processChildrenUpdates;f=!0}}};c.exports=d},function(c,b,a){function e(a,b,e,k){try{return b(e,k)}catch(c){null===f&&(f=c)}}var f=null;c.exports={invokeGuardedCallback:e,invokeGuardedCallbackWithCatch:e,rethrowCaughtError:function(){if(f){var a=f;f=null;throw a;}}}},function(c,b){c.exports={remove:function(a){a._reactInternalInstance= void 0},get:function(a){return a._reactInternalInstance},has:function(a){return void 0!==a._reactInternalInstance},set:function(a,b){a._reactInternalInstance=b}}},function(c,b,a){var e=a(10),f={Mixin:{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(a, b,f,k,c,m,n,s){this.isInTransaction()?e(!1):void 0;var q,r;try{q=this._isInTransaction=!0,this.initializeAll(0),r=a.call(b,f,k,c,m,n,s),q=!1}finally{try{if(q)try{this.closeAll(0)}catch(t){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return r},initializeAll:function(a){for(var b=this.transactionWrappers;a<b.length;a++){var e=b[a];try{this.wrapperInitData[a]=f.OBSERVED_ERROR,this.wrapperInitData[a]=e.initialize?e.initialize.call(this):null}finally{if(this.wrapperInitData[a]===f.OBSERVED_ERROR)try{this.initializeAll(a+ 1)}catch(k){}}}},closeAll:function(a){!this.isInTransaction()?e(!1):void 0;for(var b=this.transactionWrappers;a<b.length;a++){var c=b[a],k=this.wrapperInitData[a],l;try{l=!0,k!==f.OBSERVED_ERROR&&c.close&&c.close.call(this,k),l=!1}finally{if(l)try{this.closeAll(a+1)}catch(m){}}}this.wrapperInitData.length=0}},OBSERVED_ERROR:{}};c.exports=f},function(c,b,a){c.exports=!1},function(c,b){c.exports=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,f,d,g){MSApp.execUnsafeLocalFunction(function(){return a(b, f,d,g)})}:a}},function(c,b){c.exports=function(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;return 32<=a||13===a?a:0}},function(c,b){function a(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=e[a])?!!b[a]:!1}var e={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};c.exports=function(b){return a}},function(c,b){c.exports=function(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3=== a.nodeType?a.parentNode:a}},function(c,b){var a="function"===typeof Symbol&&Symbol.iterator;c.exports=function(b){b=b&&(a&&b[a]||b["@@iterator"]);if("function"===typeof b)return b}},function(c,b,a){var e=a(22),f;e.canUseDOM&&(f=document.implementation&&document.implementation.hasFeature&&!0!==document.implementation.hasFeature("",""));c.exports=function(a,b){if(!e.canUseDOM||b&&!("addEventListener"in document))return!1;var c="on"+a,k=c in document;k||(k=document.createElement("div"),k.setAttribute(c, "return;"),k="function"===typeof k[c]);!k&&(f&&"wheel"===a)&&(k=document.implementation.hasFeature("Events.wheel","3.0"));return k}},function(c,b,a){b=a(22);var e=/^[ \r\n\t\f]/,f=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;a=a(113)(function(a,b){a.innerHTML=b});b.canUseDOM&&(b=document.createElement("div"),b.innerHTML=" ",""===b.innerHTML&&(a=function(a,b){a.parentNode&&a.parentNode.replaceChild(a,a);if(e.test(b)||"<"===b[0]&&f.test(b)){a.innerHTML=String.fromCharCode(65279)+b;var c=a.firstChild; 1===c.data.length?a.removeChild(c):c.deleteData(0,1)}else a.innerHTML=b}),b=null);c.exports=a},function(c,b){c.exports=function(a,b){var f=null===a||!1===a,d=null===b||!1===b;if(f||d)return f===d;f=typeof a;d=typeof b;return"string"===f||"number"===f?"string"===d||"number"===d:"object"===d&&a.type===b.type&&a.key===b.key}},function(c,b,a){function e(a){return n[a]}function f(a,b){return a&&"object"===typeof a&&null!=a.key?"$"+(""+a.key).replace(s,e):b.toString(36)}function d(a,b,c,p){var n=typeof a; if("undefined"===n||"boolean"===n)a=null;if(null===a||"string"===n||"number"===n||g.isValidElement(a))return c(p,a,""===b?l+f(a,0):b),1;var v,x,w=0;b=""===b?l:b+m;if(Array.isArray(a))for(n=0;n<a.length;n++)v=a[n],x=b+f(v,n),w+=d(v,x,c,p);else if(v=h(a))if(n=v.call(a),v!==a.entries)for(a=0;!(v=n.next()).done;)v=v.value,x=b+f(v,a++),w+=d(v,x,c,p);else for(;!(v=n.next()).done;){if(a=v.value)v=a[1],x=b+("$"+(""+a[0]).replace(s,e))+m+f(v,0),w+=d(v,x,c,p)}else"object"===n&&k(!1);return w}a(47);var g=a(34), h=a(117),k=a(10);a(12);var l=".",m=":",n={"=":"=0",":":"=2"},s=/[=:]/g;c.exports=function(a,b,f){return null==a?0:d(a,"",b,f)}},function(c,b,a){a(14);b=a(40);a(12);c.exports=b},,function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11),h=a(89);b=a(41);var k=a(37),l=a(28),m=a(593);a=d.createClass({displayName:"Select",mixins:[b],statics:{Transforms:{integer:function(a){return parseInt(a,10)},bool:function(a){return"true"===a}}},propTypes:{className:d.PropTypes.string, facadeClassName:d.PropTypes.string,hasErrors:d.PropTypes.bool,defaultValue:d.PropTypes.any,onChange:d.PropTypes.func.isRequired,onBlur:d.PropTypes.func,onFocus:d.PropTypes.func,value:d.PropTypes.any,errorMessage:d.PropTypes.string,label:d.PropTypes.string,title:d.PropTypes.string,placeholder:d.PropTypes.string,description:d.PropTypes.node,theme:l.isRequired,type:d.PropTypes.oneOf(["primary","light","minor"]),transform:d.PropTypes.func},getDefaultProps:function(){return{theme:"damask",transform:function(a){return a}, type:"primary"}},getInitialState:function(){return{isFocused:!1}},getLabel:function(){var a=this.props,b=a.value,d=a.defaultValue,f=b||""===b||0===b||!1===b?b:d;return(a=h([].concat(a.children),function(a){return a.props.value===f||a.props.value===parseInt(f,10)}))?a.props.children:""},handleChange:function(a){var b=this.props,d=b.onChange,b=b.transform;d({target:{value:b(a.target.value)}})},handleFocus:function(a,b){this.setState({isFocused:!0});if(this.props.onFocus)this.props.onFocus(a,b)},handleBlur:function(a, b){this.setState({isFocused:!1});if(this.props.onBlur)this.props.onBlur(a,b)},render:function(){var a,b=this.props,c=b.className,h=b.label,l=b.title,p=b.description,u=b.errorMessage,v=b.facadeClassName,x=b.hasErrors,w=b.theme,y=b.type,B=b.placeholder,A=b.children,b=(0,f.default)(b,"className label title description errorMessage facadeClassName hasErrors theme type placeholder children".split(" "));delete b.transform;var z=this.state.isFocused,c=g(c,m[y],m[w],(a={},a[m.hasErrors]=u||x,a["has-errors"]= u||x,a[m.focused]=z,a[m.unlabeled]=!h,a[m.hasValue]=!!this.props.value,a));return d.createElement(k,{errorMessage:u,label:h,className:c,theme:w},l&&d.createElement("div",{className:"title"},l),d.createElement("div",{className:g(m.selectFacadeFormField,v)},d.createElement("div",{className:m.label},this.getLabel()),d.createElement("select",(0,e.default)({},b,{className:m.selectField,onChange:this.handleChange,onFocus:this.handleFocus,onBlur:this.handleBlur}),A),!!B&&!this.props.value&&d.createElement("div", null,B)),p&&d.createElement("div",{className:"description"},p))}});c.exports=a},function(c,b){c.exports={EXPIRED:1,PASTDUE:2,TRIAL:3,BETA:4,REMOVED:5,INTERNAL:6,COMPED:7,PAID:8,V5_LINKED:11,ACTIVE_PARKING_PAGE:12}},,,,,function(c,b){var a=Object.prototype.hasOwnProperty;c.exports=function(b,f){if(b===f?0!==b||1/b===1/f:b!==b&&f!==f)return!0;if("object"!==typeof b||null===b||"object"!==typeof f||null===f)return!1;var d=Object.keys(b),g=Object.keys(f);if(d.length!==g.length)return!1;for(g=0;g<d.length;g++)if(!a.call(f, d[g])||!(b[d[g]]===f[d[g]]?0!==b[d[g]]||1/b[d[g]]===1/f[d[g]]:b[d[g]]!==b[d[g]]&&f[d[g]]!==f[d[g]]))return!1;return!0}},function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(227))&&b.__esModule?b:{"default":b},d=a(913),g=a(914),h=a(242),k=a(552),l=a(437),m=a(1188),n=a(619),s=a(336),q={},r=function(a,b){var d=q[a];d||(d=q[a]=s(a));return b?(a!==d?"-":"")+n(d):d},t={};c.exports={addClass:function(a,b){if(b&&0<b.length)if("string"===typeof b)a.classList.add(b);else{var d;(d=a.classList).add.apply(d, (0,f.default)(b))}},removeClass:function(a,b){if(b&&0<b.length)if("string"===typeof b)a.classList.remove(b);else{var d;(d=a.classList).remove.apply(d,(0,f.default)(b))}},normalizeStyleProperty:r,loadStyles:function(a,b){t[a]||function(){var f="",g={};h(b,function(b,d){var e=d.replace(/\.([\w\-\$]+)/g,function(b,d){var f=a+"-"+d;g[d]=f;return"."+f});f+=e+" {";h(b,function(a,b){f+=r(m(b),!0)+":";f=-1<b.indexOf("transition")?f+(a.replace(/(^|,|\s)transform/,function(a,b){return b+r("transform",!0)})+ ";"):f+(a+";")});f+="}\n"});t[a]=g;d(f)}();return(0,e.default)({},t[a])},convertTranslateToMatrix:function(a,b){return"matrix("+k(l.apply(void 0,(0,f.default)(g.translate(a,b)))).join(", ")+")"}}},,,,,,,,,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(29);var f=e(b);b=a(4);var d=e(b);b=a(7);var g=e(b);b=a(9);var h=a(434);a=function(){function a(){(0,d.default)(this,a);this.generateActions("insert")}(0,g.default)(a,[{key:"read",value:function(a){var b=this,d=1>=arguments.length|| void 0===arguments[1]?!1:arguments[1],g=arguments[2];this.dispatch(a);return h.read(a,d,g).then(function(a){return b.actions.insert(a.data)}).catch(function(a){a=a.data;return f.default.reject(a.message||a)})}},{key:"readForCollection",value:function(a){var b=this;this.dispatch(a);return h.readForCollection(a).then(function(a){(a=a.data)&&a.results.forEach(function(a){return b.actions.insert(a)});return f.default.resolve(a)}).catch(function(a){a=a.data;return f.default.reject(a.message||a)})}},{key:"update", value:function(a,b){var d=this;this.dispatch(a.id);return a.field?h.updateField(a).then(function(a){return d.actions.insert(a.data.item)}).catch(function(a){a=a.data;return f.default.reject(a.message||a)}):h.update(a,b).then(function(a){a=a.data;d.actions.insert(a);return a}).catch(function(a){a=a.data;return f.default.reject(a.message||a)})}},{key:"updateForCollection",value:function(a,b){var d=this;return h.updateForCollection(a,b).then(function(a){return d.actions.insert(a.data)}).catch(function(a){a= a.data;return f.default.reject(a.message||a)})}},{key:"create",value:function(a,b,d){var g=this;return h.create(a,b,d).then(function(a){a=a.data;g.actions.insert(a);return a}).catch(function(a){a=a.data;return f.default.reject(a.message||a)})}},{key:"createForCollection",value:function(a,b,d){var g=this;return h.createForCollection(a,b,d).then(function(a){a=a.data;g.actions.insert(a);return a}).catch(function(a){a=a.data;return f.default.reject(a.message||a)})}},{key:"delete",value:function(a,b){this.dispatch(a); return h.delete(a,b).catch(function(a){a=a.data;return f.default.reject(a.message||a)})}},{key:"deleteMany",value:function(a){this.dispatch(a);return h.deleteMany(a)}}]);return a}();c.exports=b.createActions(a)},,function(c,b,a){b=c.exports=a(3)();b.i(a(23),void 0);b.push([c.id,'/**\nButton styles for the "midnight" theme\n**/\n.buttons-midnight-primary-3DMlL {\n border-radius: 4px;\n color: #3e3e3e;\n background: #cccccc;\n}\n.buttons-midnight-primary-3DMlL:hover {\n background: #ffffff;\n}\n.buttons-midnight-primary-3DMlL:disabled:hover {\n background: #cccccc;\n}\n.buttons-midnight-minor-1g8VX {\n border-radius: 4px;\n background: #222222;\n color: #cccccc;\n}\n.buttons-midnight-minor-1g8VX:hover {\n background-color: #242424;\n color: #ffffff;\n}\n.buttons-midnight-minor-1g8VX:disabled:hover {\n background: transparent;\n}\n', ""]);b.locals={primary:"buttons-midnight-primary-3DMlL "+a(23).locals.button+"",minor:"buttons-midnight-minor-1g8VX "+a(23).locals.button+""}},,,function(c,b,a){var e=a(771),f=a(38),d=a(523),g=a(27),h=a(39);c.exports=function(a,b,c){var n=g(a)?e:d;c&&h(a,b,c)&&(b=void 0);if("function"!=typeof b||void 0!==c)b=f(b,c,3);return n(a,b)}},function(c,b,a){b.__esModule=!0;var e=(c=a(722))&&c.__esModule?c:{"default":c},f=(a=a(543))&&a.__esModule?a:{"default":a};b.default=function(){return function(a,b){if(Array.isArray(a))return a; if((0,e.default)(Object(a))){var c=[],k=!0,l=!1,m=void 0;try{for(var n=(0,f.default)(a),s;!(k=(s=n.next()).done)&&!(c.push(s.value),b&&c.length===b);k=!0);}catch(q){l=!0,m=q}finally{try{if(!k&&n["return"])n["return"]()}finally{if(l)throw m;}}return c}throw new TypeError("Invalid attempt to destructure non-iterable instance");}}()},function(c,b,a){var e=a(148),f=a(151),d=a(27),g=a(39),h=a(92),k=a(246),l=a(71),m=Math.max;c.exports=function(a,b,c,r){var t=a?f(a):0;h(t)||(a=l(a),t=a.length);c="number"!= typeof c||r&&g(b,c,r)?0:0>c?m(t+c,0):c||0;return"string"==typeof a||!d(a)&&k(a)?c<=t&&-1<a.indexOf(b,c):!!t&&-1<e(a,b,c)}},function(c,b,a){var e=a(746);c.exports=function(a,b,g){if(b!==b)return e(a,g);g-=1;for(var c=a.length;++g<c;)if(a[g]===b)return g;return-1}},,,,,,function(c,b,a){c.exports={"default":a(794),__esModule:!0}},,,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(29);var f=e(b);b=a(4);var d=e(b);b=a(7);var g=e(b);b=a(26);var h=b.Map,k=b.fromJS;b=a(9);var l=a(140); a=a(52);var m=function(){function a(){(0,d.default)(this,a);this.state=h();this.bindActions(l);this.exportPublicMethods({fetch:this.fetch,fetchForCollection:this.fetchForCollection,getForCollection:this.getForCollection})}(0,g.default)(a,[{key:"onInsert",value:function(a){this.setState(this.state.set(a.id,k(a)))}},{key:"onDelete",value:function(a){this.setState(this.state.delete(a))}},{key:"onDeleteMany",value:function(a){this.setState(this.state.filter(function(b,d){return-1===a.indexOf(d)}))}}, {key:"fetch",value:function(a){var b=this,d=1>=arguments.length||void 0===arguments[1]?!1:arguments[1],g=arguments[2];if(!a)return f.default.resolve();var e=this.getState().get(a);return e?f.default.resolve(e):l.read(a,d,g).then(function(){return b.getState().get(a)})}},{key:"fetchForCollection",value:function(a){var b=this,d=this.getForCollection(a);return 0<d.size?f.default.resolve(d):l.readForCollection(a).then(function(){return b.getForCollection(a)})}},{key:"getForCollection",value:function(a){return this.getState().filter(function(b){return b.get("collectionId")=== a})}}]);return a}();c.exports=b.createStore(a(m),"ContentItemStore")},function(c,b,a){b.__esModule=!0;var e=(c=a(46))&&c.__esModule?c:{"default":c},f=(a=a(306))&&a.__esModule?a:{"default":a};b.default=function g(a,b,c){null===a&&(a=Function.prototype);var m=(0,f.default)(a,b);if(void 0===m)return a=(0,e.default)(a),null===a?void 0:g(a,b,c);if("value"in m)return m.value;b=m.get;return void 0===b?void 0:b.call(c)}},function(c,b){c.exports=function(a,b){for(var f=-1,d=a.length,g=Array(d);++f<d;)g[f]= b(a[f],f,a);return g}},function(c,b,a){var e=a(38),f=a(49),d=a(27);c.exports=function(a,b){return function(c,l,m){var n=b?b():{};l=e(l,m,3);if(d(c)){m=-1;for(var s=c.length;++m<s;){var q=c[m];a(n,q,l(q,m,c),c)}}else f(c,function(b,d,f){a(n,b,l(b,d,f),f)});return n}}},,function(c,b){c.exports={AUTHENTICATED:0,CONFIG:1,ADMIN:2,CONFIG_CONTENT_MANAGER:11,CONFIG_SETTINGS:12,CONFIG_ACTIVITY:13,CONFIG_COMMERCE:14,CONFIG_NEWSLETTER:15,CONFIG_DAMASK:17,CONFIG_CHANGE_STRUCTURE:1110,CONFIG_TRUSTED_COMMENTER:1111, CONFIG_SETTINGS_GENERAL:1210,CONFIG_SETTINGS_LOCALE:1211,CONFIG_SETTINGS_SOCIAL_ACCOUNT:1212,CONFIG_SETTINGS_FACEBOOK:1213,CONFIG_SETTINGS_SOCIAL_SETTINGS:1214,CONFIG_SETTINGS_MEMBER_ACCOUNTS:1215,CONFIG_SETTINGS_DOMAIN:1216,CONFIG_SETTINGS_TEMPLATE:1217,CONFIG_SETTINGS_IMPORT:1218,CONFIG_SETTINGS_CODEINJECT:1219,CONFIG_SETTINGS_ADVANCED:1220,CONFIG_SETTINGS_DEVELOPER:1221,CONFIG_SETTINGS_SESSIONS:1222,CONFIG_SETTINGS_MOBILE:1223,CONFIG_SETTINGS_BILLING:1224,CONFIG_SETTINGS_SUPPORT:1225,CONFIG_SETTINGS_SITE:1226, CONFIG_SETTINGS_LABS:1227,CONFIG_SETTINGS_ADVERTISING:1228,CONFIG_ACTIVITY_STATS:1310,CONFIG_ACTIVITY_COMMENTS:1311,CONFIG_COMMERCE_ORDERS:1410,CONFIG_COMMERCE_STORE_SETTINGS:1411,CONFIG_COMMERCE_SHIPPING:1412,CONFIG_COMMERCE_COUPONS:1413,CONFIG_COMMERCE_TAXES:1414,CONFIG_COMMERCE_EMAIL_NOTIFICATIONS:1415,CONFIG_COMMERCE_INVENTORY:1416,CONFIG_COMMERCE_DONATIONS:1417,CONFIG_COMMERCE_ACCOUNTING:1418,CONFIG_COMMERCE_DISCOUNTS:1419,CONFIG_NEWSLETTER_READ_SUBSCRIBER:1510,CONFIG_NEWSLETTER_WRITE_SUBSCRIBER:1511, CONFIG_NEWSLETTER_READ_GROUP:1512,CONFIG_NEWSLETTER_WRITE_GROUP:1513,CONFIG_NEWSLETTER_READ_MESSAGE:1514,CONFIG_NEWSLETTER_WRITE_MESSAGE:1515,CONFIG_NEWSLETTER_READ_SETTINGS:1516,CONFIG_NEWSLETTER_WRITE_SETTINGS:1517,CONFIG_ACCEPT_TOS:1610,CONFIG_DOMAINS_REMOVE:1611,CONFIG_DOMAINS_ADD:1612,ADMIN_GRANT_ACCESS:2010,ADMIN_BILLING_READ:2011,ADMIN_BILLING_WRITE:2012,ADMIN_READ_CUSTOMER_DATA:2013,ADMIN_WRITE_CUSTOMER_DATA:2014,ADMIN_DEV_SETTINGS:2015,ADMIN_MARKETING_READ:2016,ADMIN_MARKETING_WRITE:2017, ADMIN_LOGINAS:2018,ADMIN_TEMPLATE_SETTINGS:2019,ADMIN_SYSTEM_JSON_VIEW:2020,ADMIN_TAXONOMY:2021,ADMIN_CHANGE_USER_EMAIL:2022,ADMIN_ADD_NOTE:2023,ADMIN_EDIT_OTHER_NOTES:2024,ADMIN_EXTEND_TRIAL:2025,ADMIN_BIZPIPE_STATS_MOBILE_ACCESS:2026,ADMIN_REFERRALS:2027,ADMIN_BILLING_REFUND:2028,ADMIN_BILLING_APPLY_EDU_DISCOUNT:2029,ADMIN_DEACTIVATE_SQUARESPACE_ACCOUNT:2030,ADMIN_BILLING_EXPIRE:2031,ADMIN_CHANGE_MAX_COMPS:2032,ADMIN_CHANGE_GUILDS:2033,ADMIN_DOMAIN_WRITE:2034,ADMIN_GOOGLE_APPS_WRITE:2035,ADMIN_ADD_CONTRIBUTER:2036, ADMIN_CHANGE_WEBSITE_OWNER:2037,ADMIN_REMOVE_CONTRIBUTER:2038,ADMIN_TAXATION_READ:2039,ADMIN_SUSPEND:2040,ADMIN_TAXATION_WRITE:2041,ADMIN_LOGINAS_PUBLIC:2042,ADMIN_MASS_REMOVAL:2043,ADMIN_REMOVE_SITE:2044}},,function(c,b,a){function e(a){return{url:L[a.action].replace("{collectionId}",a.collectionId),isFallback:!0}}function f(a){return{url:N[a.collectionType][a.action].replace("{collectionId}",a.collectionId).replace("{parentId}",a.parentId),isFallback:!1}}function d(){var a=0>=arguments.length|| void 0===arguments[0]?{}:arguments[0];if(!a.collectionId)return{url:F[a.action],isFallback:!0};if(a.parentId)return a.collectionType===I.PRODUCTS?f(a):e(a);var b=O[a.collectionOrdering];if(!b)return e(a);b=b[a.recordType];return!b?e(a):{url:b[a.action].replace("{collectionId}",a.collectionId),isFallback:!1}}var g=(b=a(13))&&b.__esModule?b:{"default":b},h,k,l,m,n,s,q,r,t,p,u,v,x,w,y,B,A,z=a(173),C=a(96);b=a(163);var I=a(36),O=(t={},t[b.CHRONOLOGICAL]=(m={},m[C.TEXT]=(h={},h[z.GET]="/api/content/blogs/{collectionId}/text-posts/{id}", h[z.POST]="/api/content/blogs/{collectionId}/text-posts",h[z.PUT]="/api/content/blogs/{collectionId}/text-posts/{id}",h[z.DELETE]="/api/content/blogs/{collectionId}/text-posts/{id}",h),m[C.IMAGE]=(k={},k[z.GET]="/api/content/blogs/{collectionId}/image-posts/{id}",k[z.POST]="/api/content/blogs/{collectionId}/image-posts",k[z.PUT]="/api/content/blogs/{collectionId}/image-posts/{id}",k[z.DELETE]="/api/content/blogs/{collectionId}/image-posts/{id}",k),m[C.VIDEO]=(l={},l[z.GET]="/api/content/blogs/{collectionId}/video-posts/{id}", l[z.POST]="/api/content/blogs/{collectionId}/video-posts",l[z.PUT]="/api/content/blogs/{collectionId}/video-posts/{id}",l[z.DELETE]="/api/content/blogs/{collectionId}/video-posts/{id}",l),m),t[b.CALENDAR]=(s={},s[C.EVENT]=(n={},n[z.GET]="/api/content/calendars/{collectionId}/events/{id}",n[z.POST]="/api/content/calendars/{collectionId}/events",n[z.PUT]="/api/content/calendars/{collectionId}/events/{id}",n[z.DELETE]="/api/content/calendars/{collectionId}/events/{id}",n),s),t[b.USER]=(r={},r[C.STORE_ITEM]= (q={},q[z.GET]="/api/content/product-pages/{collectionId}/products/{id}",q[z.POST]="/api/content/product-pages/{collectionId}/products",q[z.PUT]="/api/content/product-pages/{collectionId}/products/{id}",q[z.DELETE]="/api/content/product-pages/{collectionId}/products/{id}",q),r),t),N=(u={},u[I.PRODUCTS]=(p={},p[z.GET]="/api/content/product-pages/{collectionId}/products/{parentId}/images/{id}",p[z.POST]="/api/content/product-pages/{collectionId}/products/{parentId}/images",p[z.PUT]="/api/content/product-pages/{collectionId}/products/{parentId}/images/{id}", p[z.DELETE]="/api/content/product-pages/{collectionId}/products/{parentId}/images/{id}",p),u),D=(y={},y[b.CHRONOLOGICAL]=(v={},v[I.COLLECTION_TYPE_GENERIC]="/api/content/blogs/{collectionId}/posts",v),y[b.CALENDAR]=(x={},x[I.COLLECTION_TYPE_GENERIC]="/api/content/calendars/{collectionId}/events",x),y[b.USER]=(w={},w[I.PRODUCTS]="/api/content/product-pages/{collectionId}/products",w),y),L=(B={},B[z.GET]="/api/content-collections/{collectionId}/content-items/{id}",B[z.POST]="/api/content-collections/{collectionId}/content-items", B[z.PUT]="/api/content-collections/{collectionId}/content-items/{id}",B[z.DELETE]="/api/content-collections/{collectionId}/content-items/{id}",B),F=(A={},A[z.GET]="/api/content-items/{id}",A[z.POST]="/api/content-items",A[z.PUT]="/api/content-items/{id}",A[z.DELETE]="/api/content-items/{id}",A);c.exports={getTemplateForSingleItem:function(){return d(0>=arguments.length||void 0===arguments[0]?{}:arguments[0]).url},getTemplateForCollectionItems:function(a,b){if(!a)return"/api/content-collections/{collectionId}/content-items"; var d=void 0;D.hasOwnProperty(a)&&(d=D[a][b]);return!d?"/api/content-collections/{collectionId}/content-items":d},getMainImageUploadUrl:function(){var a=0>=arguments.length||void 0===arguments[0]?{}:arguments[0],a=d((0,g.default)({},a,{action:z.DELETE}));return a.isFallback?"/api/commondata/SaveMedia":a.url+"/main-image"},getMainImageDeletionUrl:function(){var a=0>=arguments.length||void 0===arguments[0]?{}:arguments[0],a=d((0,g.default)({},a,{action:z.DELETE}));return a.isFallback?"/api/commondata/ClearEmbeddedAsset": a.url+"/main-image"},getChildImageUploadUrl:function(){var a=0>=arguments.length||void 0===arguments[0]?{}:arguments[0];return a.recordType===C.STORE_ITEM?f({collectionType:I.PRODUCTS,recordType:C.STORE_ITEM,action:z.POST,parentId:a.parentId,collectionId:a.collectionId}).url:"/api/commondata/SaveMedia"}}},,function(c,b,a){b=c.exports=a(3)();b.push([c.id,".FieldUtils-formField-1F4bT {\n box-sizing: border-box;\n position: relative;\n background-color: #ffffff;\n padding: 11px;\n line-height: 22px;\n height: 44px;\n width: 100%;\n color: #3e3e3e;\n border: none;\n}\n.FieldUtils-formField-1F4bT:focus {\n outline: none;\n}\n.FieldUtils-inlineFields-2tbfI {\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n}\n.FieldUtils-inlineFields-2tbfI .FieldUtils-field-zgU0m {\n padding-right: 11px;\n width: 100%;\n}\n.FieldUtils-inlineFields-2tbfI .FieldUtils-field-zgU0m:last-child {\n padding-right: 0;\n}\n", ""]);b.locals={formField:"FieldUtils-formField-1F4bT",inlineFields:"FieldUtils-inlineFields-2tbfI",field:"FieldUtils-field-zgU0m"}},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh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bmQ9InIiPz6jBZ57AAAA4UlEQVR42uyWYQqDMAyF69gZvIDH0Kk7xjyFqDjY/Xaizl8TXAIRykiltkr/5MEDwTTvo7a1ybIsKqYuKrIEQAAEQAAUnoSc/5R5tM6cchwAGvAX3O4Ib2lMEwrwAM84ntw5hHdG/Uw9vABS8MdotrrfCO+ZeuyR+s7AHTwxTQcmfGDqJuoRtAZqC8Ro1IyW8PqIRYiqLJ/jSeamvTpqF6wqLRBceOm83XcAoG5gvRGuqUadBYAqLBCa3qmzATiIzfAzAFC5AZD7HvnXgN/IG/wynr2UyLVcAARAAGID/AQYAJVlDqdJW3OVAAAAAElFTkSuQmCC"}, ,,function(c,b){c.exports={GET:1,POST:2,PUT:3,DELETE:4}},,function(c,b,a){b=c.exports=a(3)();b.push([c.id,"@-webkit-keyframes shiver {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 25% {\n -webkit-transform: translateX(11px);\n transform: translateX(11px);\n }\n 75% {\n -webkit-transform: translateX(-11px);\n transform: translateX(-11px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@keyframes shiver {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 25% {\n -webkit-transform: translateX(11px);\n transform: translateX(11px);\n }\n 75% {\n -webkit-transform: translateX(-11px);\n transform: translateX(-11px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@-webkit-keyframes shimmy {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 50% {\n -webkit-transform: translateX(-33px);\n transform: translateX(-33px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@keyframes shimmy {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 50% {\n -webkit-transform: translateX(-33px);\n transform: translateX(-33px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@-webkit-keyframes spin {\n from {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes spin {\n from {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@-webkit-keyframes bounceIn {\n 0% {\n opacity: 0;\n -webkit-transform: scale(0.3);\n transform: scale(0.3);\n }\n 50% {\n opacity: 1;\n -webkit-transform: scale(1.05);\n transform: scale(1.05);\n }\n 70% {\n -webkit-transform: scale(0.9);\n transform: scale(0.9);\n }\n 100% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}\n@keyframes bounceIn {\n 0% {\n opacity: 0;\n -webkit-transform: scale(0.3);\n transform: scale(0.3);\n }\n 50% {\n opacity: 1;\n -webkit-transform: scale(1.05);\n transform: scale(1.05);\n }\n 70% {\n -webkit-transform: scale(0.9);\n transform: scale(0.9);\n }\n 100% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}\n@-webkit-keyframes pulseBadgeOpacity {\n 0% {\n opacity: 1;\n }\n 85% {\n opacity: .6;\n }\n 100% {\n opacity: 1;\n }\n}\n@keyframes pulseBadgeOpacity {\n 0% {\n opacity: 1;\n }\n 85% {\n opacity: .6;\n }\n 100% {\n opacity: 1;\n }\n}\n@-webkit-keyframes fadeout {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n}\n@keyframes fadeout {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n}\n@-webkit-keyframes riseandfadein {\n 0% {\n -webkit-transform: translateY(22px);\n transform: translateY(22px);\n opacity: 0;\n }\n 100% {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n opacity: 1;\n }\n}\n@keyframes riseandfadein {\n 0% {\n -webkit-transform: translateY(22px);\n transform: translateY(22px);\n opacity: 0;\n }\n 100% {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n opacity: 1;\n }\n}\n/**\n * Jiggles the container back and forth slowly. Used to draw attention of a user\n * back to the item. For instance, if a user attempts to click out of a modal\n * that is not completed.\n */\n.animations-shake-2XVu4 {\n -webkit-animation-name: shiver;\n animation-name: shiver;\n -webkit-animation-duration: 0.2s;\n animation-duration: 0.2s;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n/**\n * Shake the item back and forth very quickly. Used to indicate that an action\n * is improper or impossible, such as saving a form with errors or deleting an\n * item without sufficient permissions.\n */\n.animations-shiver-3EpDG {\n -webkit-animation-name: shiver;\n animation-name: shiver;\n -webkit-animation-duration: 0.1s;\n animation-duration: 0.1s;\n -webkit-animation-iteration-count: 2;\n animation-iteration-count: 2;\n -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n/**\n * Gently rocks the animated item to the left. Used to gently remind the user\n * that an action cannot happen, such as when reaching the end of a list, or\n * trying slide something farther than it can go.\n */\n.animations-shimmy-19m3O {\n -webkit-animation-name: shimmy;\n animation-name: shimmy;\n -webkit-animation-duration: 0.3s;\n animation-duration: 0.3s;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n/**\n * Spin your heart out!\n */\n.animations-spin-9W5em {\n -webkit-animation-name: spin;\n animation-name: spin;\n -webkit-animation-duration: 1s;\n animation-duration: 1s;\n -webkit-animation-iteration-count: infinite;\n animation-iteration-count: infinite;\n -webkit-animation-timing-function: linear;\n animation-timing-function: linear;\n}\n.animations-pulseBadgeOpacity-1JjaV {\n -webkit-animation-name: pulseBadgeOpacity;\n animation-name: pulseBadgeOpacity;\n -webkit-animation-duration: 4s;\n animation-duration: 4s;\n -webkit-animation-iteration-count: infinite;\n animation-iteration-count: infinite;\n -webkit-animation-timing-function: ease-in-out;\n animation-timing-function: ease-in-out;\n}\n.animations-fadeout-2nYta {\n -webkit-animation-name: fadeout;\n animation-name: fadeout;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n}\n.animations-fadein-1tXTZ {\n -webkit-animation-name: fadein;\n animation-name: fadein;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n}\n.animations-riseandfadein-2pBEs {\n -webkit-animation-name: riseandfadein;\n animation-name: riseandfadein;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n}\n", ""]);b.locals={shake:"animations-shake-2XVu4",shiver:"animations-shiver-3EpDG",shimmy:"animations-shimmy-19m3O",spin:"animations-spin-9W5em",pulseBadgeOpacity:"animations-pulseBadgeOpacity-1JjaV",fadeout:"animations-fadeout-2nYta",fadein:"animations-fadein-1tXTZ",riseandfadein:"animations-riseandfadein-2pBEs"}},function(c,b,a){var e=a(521),f=a(38),d=a(522),g=a(27),h=a(39);c.exports=function(a,b,c){var n=g(a)?e:d;c&&h(a,b,c)&&(b=void 0);if("function"!=typeof b||void 0!==c)b=f(b,c,3);return n(a,b)}}, ,,,function(c,b){var a=function(a){return 9===a.keyCode},e=function(a){a=a.keyCode;return 48<=a&&57>=a};c.exports={isNumericKey:e,isAlphanumericKey:function(a){a=a.keyCode;return e(a)||65<=a&&90>=a},isArrowDownKey:function(b){return 40===b.keyCode||!b.shiftKey&&a(b)},isArrowUpKey:function(b){return 38===b.keyCode||b.shiftKey&&a(b)},isArrowLeftKey:function(a){return 37===a.keyCode},isArrowRightKey:function(a){return 39===a.keyCode},isBackspaceKey:function(a){return 8===a.keyCode},isCommaKey:function(a){return 188=== a.keyCode},isDeleteKey:function(a){return 46===a.keyCode},isEnterKey:function(a){return 13===a.keyCode},isEscapeKey:function(a){return 27===a.keyCode},isTabKey:a,isTabKeyWithShift:function(a){return 9===a.keyCode&&a.shiftKey}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VzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5l6/qHAAAAUUlEQVR42mL8//8/AxaAVRAJMKILMDFQCbAQayMhQFUX/aeGQVR1ESNaTBEbPijqqeYiJgI2/sfDp00YjRo0ahAtyyNseY5xwFz0f0DDCCDAAGfrDDEBDSZGAAAAAElFTkSuQmCC"}, ,function(c,b){var a={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},e=["Webkit","ms","Moz","O"];Object.keys(a).forEach(function(b){e.forEach(function(d){a[d+b.charAt(0).toUpperCase()+b.substring(1)]=a[b]})});c.exports={isUnitlessNumber:a,shorthandPropertyExpansions:{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}}}},function(c,b,a){function e(){this._contexts=this._callbacks=null}b=a(14);var f=a(54),d=a(10);b(e.prototype, {enqueue:function(a,b){this._callbacks=this._callbacks||[];this._contexts=this._contexts||[];this._callbacks.push(a);this._contexts.push(b)},notifyAll:function(){var a=this._callbacks,b=this._contexts;if(a){a.length!==b.length?d(!1):void 0;this._contexts=this._callbacks=null;for(var f=0;f<a.length;f++)a[f].call(b[f]);a.length=0;b.length=0}},checkpoint:function(){return this._callbacks?this._callbacks.length:0},rollback:function(a){this._callbacks&&(this._callbacks.length=a,this._contexts.length=a)}, reset:function(){this._contexts=this._callbacks=null},destructor:function(){this.reset()}});f.addPoolingTo(e);c.exports=e},function(c,b,a){function e(a,b){this.func=a;this.context=b;this.count=0}function f(a,b,d){a.func.call(a.context,b,a.count++)}function d(a,b,d,f){this.result=a;this.keyPrefix=b;this.func=d;this.context=f;this.count=0}function g(a,b,d){var f=a.result,g=a.keyPrefix;a=a.func.call(a.context,b,a.count++);Array.isArray(a)?h(a,f,d,m.thatReturnsArgument):null!=a&&(l.isValidElement(a)&& (a=l.cloneAndReplaceKey(a,g+(a.key&&(!b||b.key!==a.key)?(""+a.key).replace(q,"$&/")+"/":"")+d)),f.push(a))}function h(a,b,f,e,c){var k="";null!=f&&(k=(""+f).replace(q,"$&/")+"/");b=d.getPooled(b,k,e,c);n(a,g,b);d.release(b)}function k(a,b,d){return null}b=a(54);var l=a(34),m=a(40),n=a(121);a=b.twoArgumentPooler;var s=b.fourArgumentPooler,q=/\/+/g;e.prototype.destructor=function(){this.context=this.func=null;this.count=0};b.addPoolingTo(e,a);d.prototype.destructor=function(){this.context=this.func= this.keyPrefix=this.result=null;this.count=0};b.addPoolingTo(d,s);c.exports={forEach:function(a,b,d){if(null==a)return a;b=e.getPooled(b,d);n(a,f,b);e.release(b)},map:function(a,b,d){if(null==a)return a;var f=[];h(a,f,null,b,d);return f},mapIntoWithKeyPrefixInternal:h,count:function(a,b){return n(a,k,null)},toArray:function(a){var b=[];h(a,b,null,m.thatReturnsArgument);return b}}},function(c,b,a){function e(a,b){if(b){"function"===typeof b?n(!1):void 0;k.isValidElement(b)?n(!1):void 0;var f=a.prototype, e=f.__reactAutoBindPairs;b.hasOwnProperty(r)&&v.mixins(a,b.mixins);for(var c in b)if(b.hasOwnProperty(c)&&c!==r){var h=b[c],p=f.hasOwnProperty(c),l=p,m=c,s=u.hasOwnProperty(m)?u[m]:null;x.hasOwnProperty(m)&&(s!==t.OVERRIDE_BASE?n(!1):void 0);l&&(!(s===t.DEFINE_MANY||s===t.DEFINE_MANY_MERGED)?n(!1):void 0);if(v.hasOwnProperty(c))v[c](a,h);else l=u.hasOwnProperty(c),"function"===typeof h&&!l&&!p&&!1!==b.autobind?(e.push(c,h),f[c]=h):p?(p=u[c],!l||!(p===t.DEFINE_MANY_MERGED||p===t.DEFINE_MANY)?n(!1): void 0,p===t.DEFINE_MANY_MERGED?f[c]=d(f[c],h):p===t.DEFINE_MANY&&(f[c]=g(f[c],h))):f[c]=h}}}function f(a,b){!a||!b||!("object"===typeof a&&"object"===typeof b)?n(!1):void 0;for(var d in b)b.hasOwnProperty(d)&&(void 0!==a[d]?n(!1):void 0,a[d]=b[d]);return a}function d(a,b){return function(){var d=a.apply(this,arguments),g=b.apply(this,arguments);if(null==d)return g;if(null==g)return d;var e={};f(e,d);f(e,g);return e}}function g(a,b){return function(){a.apply(this,arguments);b.apply(this,arguments)}} var h=a(14);b=a(190);var k=a(34);a(83);a(82);var l=a(202),m=a(86),n=a(10),s=a(87),q=a(48);a(12);var r=q({mixins:null}),t=s({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),p=[],u={mixins:t.DEFINE_MANY,statics:t.DEFINE_MANY,propTypes:t.DEFINE_MANY,contextTypes:t.DEFINE_MANY,childContextTypes:t.DEFINE_MANY,getDefaultProps:t.DEFINE_MANY_MERGED,getInitialState:t.DEFINE_MANY_MERGED,getChildContext:t.DEFINE_MANY_MERGED,render:t.DEFINE_ONCE,componentWillMount:t.DEFINE_MANY, componentDidMount:t.DEFINE_MANY,componentWillReceiveProps:t.DEFINE_MANY,shouldComponentUpdate:t.DEFINE_ONCE,componentWillUpdate:t.DEFINE_MANY,componentDidUpdate:t.DEFINE_MANY,componentWillUnmount:t.DEFINE_MANY,updateComponent:t.OVERRIDE_BASE},v={displayName:function(a,b){a.displayName=b},mixins:function(a,b){if(b)for(var d=0;d<b.length;d++)e(a,b[d])},childContextTypes:function(a,b){a.childContextTypes=h({},a.childContextTypes,b)},contextTypes:function(a,b){a.contextTypes=h({},a.contextTypes,b)},getDefaultProps:function(a, b){a.getDefaultProps=a.getDefaultProps?d(a.getDefaultProps,b):b},propTypes:function(a,b){a.propTypes=h({},a.propTypes,b)},statics:function(a,b){if(b)for(var d in b){var f=b[d];b.hasOwnProperty(d)&&(d in v?n(!1):void 0,d in a?n(!1):void 0,a[d]=f)}},autobind:function(){}},x={replaceState:function(a,b){this.updater.enqueueReplaceState(this,a);b&&this.updater.enqueueCallback(this,b,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},w=function(){};h(w.prototype,b.prototype,x); c.exports={createClass:function(a){var b=function(a,b,d){if(this.__reactAutoBindPairs.length)for(var f=this.__reactAutoBindPairs,g=0;g<f.length;g+=2){var e=f[g],c=f[g+1].bind(this);this[e]=c}this.props=a;this.context=b;this.refs=m;this.updater=d||l;this.state=null;a=this.getInitialState?this.getInitialState():null;"object"!==typeof a||Array.isArray(a)?n(!1):void 0;this.state=a};b.prototype=new w;b.prototype.constructor=b;b.prototype.__reactAutoBindPairs=[];p.forEach(e.bind(null,b));e(b,a);b.getDefaultProps&& (b.defaultProps=b.getDefaultProps());!b.prototype.render?n(!1):void 0;for(var d in u)b.prototype[d]||(b.prototype[d]=null);return b},injection:{injectMixin:function(a){p.push(a)}}}},function(c,b,a){function e(a,b,g){this.props=a;this.context=b;this.refs=d;this.updater=g||f}var f=a(202);a(81);a(112);var d=a(86),g=a(10);a(12);e.prototype.isReactComponent={};e.prototype.setState=function(a,b){!("object"===typeof a||"function"===typeof a||null==a)?g(!1):void 0;this.updater.enqueueSetState(this,a);b&& this.updater.enqueueCallback(this,b,"setState")};e.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this);a&&this.updater.enqueueCallback(this,a,"forceUpdate")};c.exports=e},function(c,b,a){b=a(104);var e=a(373);a=a(30);b={processChildrenUpdates:e.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkup:b.dangerouslyReplaceNodeWithMarkup,unmountIDFromEnvironment:function(a){}};a.measureMethods(b,"ReactComponentBrowserEnvironment",{replaceNodeWithMarkup:"replaceNodeWithMarkup"});c.exports= b},function(c,b){c.exports={hasCachedChildNodes:1}},function(c,b,a){function e(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var a=this._currentElement.props,b=h.getValue(a);null!=b&&f(this,Boolean(a.multiple),b)}}function f(a,b,d){var f;a=k.getNodeFromInstance(a).options;if(b){b={};for(f=0;f<d.length;f++)b[""+d[f]]=!0;for(f=0;f<a.length;f++)d=b.hasOwnProperty(a[f].value),a[f].selected!==d&&(a[f].selected=d)}else{b=""+d;for(f=0;f<a.length;f++)if(a[f].value=== b){a[f].selected=!0;return}a.length&&(a[0].selected=!0)}}function d(a){a=h.executeOnChange(this._currentElement.props,a);this._rootNodeID&&(this._wrapperState.pendingUpdate=!0);l.asap(e,this);return a}var g=a(14),h=a(107),k=a(17),l=a(35);a(12);var m=!1;c.exports={getNativeProps:function(a,b){return g({},b,{onChange:a._wrapperState.onChange,value:void 0})},mountWrapper:function(a,b){var f=h.getValue(b);a._wrapperState={pendingUpdate:!1,initialValue:null!=f?f:b.defaultValue,listeners:null,onChange:d.bind(a), wasMultiple:Boolean(b.multiple)};void 0!==b.value&&(void 0!==b.defaultValue&&!m)&&(void 0,m=!0)},getSelectValueContext:function(a){return a._wrapperState.initialValue},postUpdateWrapper:function(a){var b=a._currentElement.props;a._wrapperState.initialValue=void 0;var d=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=Boolean(b.multiple);var g=h.getValue(b);null!=g?(a._wrapperState.pendingUpdate=!1,f(a,Boolean(b.multiple),g)):d!==Boolean(b.multiple)&&(null!=b.defaultValue?f(a,Boolean(b.multiple), b.defaultValue):f(a,Boolean(b.multiple),b.multiple?[]:""))}}},function(c,b,a){function e(){if(l.current){var a=l.current.getName();if(a)return" Check the render method of `"+a+"`."}return""}function f(a,b){if(a._store&&!(a._store.validated||null!=a.key)){a._store.validated=!0;var d;d=e();if(!d){var f="string"===typeof b?b:b.displayName||b.name;f&&(d=" Check the top-level render call using <"+f+">.")}f=s.uniqueKey||(s.uniqueKey={});f[d]?d=null:(f[d]=!0,d={parentOrOwner:d,url:" See https://fb.me/react-warning-keys for more information.", childOwner:null},a&&(a._owner&&a._owner!==l.current)&&(d.childOwner=" It was passed a child from "+a._owner.getName()+"."));null!==d&&void 0}}function d(a,b){if("object"===typeof a)if(Array.isArray(a))for(var d=0;d<a.length;d++){var g=a[d];h.isValidElement(g)&&f(g,b)}else if(h.isValidElement(a))a._store&&(a._store.validated=!0);else if(a&&(d=m(a))&&d!==a.entries)for(d=d.call(a);!(g=d.next()).done;)h.isValidElement(g.value)&&f(g.value,b)}function g(a){var b=a.type;if("function"===typeof b){var d=b.displayName|| b.name;if(b.propTypes){var f=b.propTypes;a=a.props;var g=k.prop,c;for(c in f)if(f.hasOwnProperty(c)){var h;try{"function"!==typeof f[c]?n(!1):void 0,h=f[c](a,c,d,g)}catch(l){h=l}void 0;h instanceof Error&&!(h.message in q)&&(q[h.message]=!0,e(),void 0)}}"function"===typeof b.getDefaultProps&&void 0}}var h=a(34),k=a(83);a(82);var l=a(47);a(112);var m=a(117),n=a(10);a(12);var s={},q={},r={createElement:function(a,b,f){var e="string"===typeof a||"function"===typeof a;void 0;var c=h.createElement.apply(this, arguments);if(null==c)return c;if(e)for(e=2;e<arguments.length;e++)d(arguments[e],a);g(c);return c},createFactory:function(a){var b=r.createElement.bind(null,a);b.type=a;return b},cloneElement:function(a,b,f){for(var e=h.cloneElement.apply(this,arguments),c=2;c<arguments.length;c++)d(arguments[c],e.type);g(e);return e}};c.exports=r},function(c,b){var a;c.exports={create:function(b){return a(b)},injection:{injectEmptyComponentFactory:function(b){a=b}}}},function(c,b){c.exports={logTopLevelRenders:!1}}, function(c,b,a){var e=a(377),f=a(416),d=a(215),g=a(216),h={hasSelectionCapabilities:function(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&"text"===a.type||"textarea"===b||"true"===a.contentEditable)},getSelectionInformation:function(){var a=g();return{focusedElem:a,selectionRange:h.hasSelectionCapabilities(a)?h.getSelection(a):null}},restoreSelection:function(a){var b=g(),e=a.focusedElem;a=a.selectionRange;b!==e&&f(document.documentElement,e)&&(h.hasSelectionCapabilities(e)&& h.setSelection(e,a),d(e))},getSelection:function(a){var b;if("selectionStart"in a)b={start:a.selectionStart,end:a.selectionEnd};else if(document.selection&&a.nodeName&&"input"===a.nodeName.toLowerCase()){var d=document.selection.createRange();d.parentElement()===a&&(b={start:-d.moveStart("character",-a.value.length),end:-d.moveEnd("character",-a.value.length)})}else b=e.getOffsets(a);return b||{start:0,end:0}},setSelection:function(a,b){var d=b.start,f=b.end;void 0===f&&(f=d);if("selectionStart"in a)a.selectionStart=d,a.selectionEnd=Math.min(f,a.value.length);else if(document.selection&&a.nodeName&&"input"===a.nodeName.toLowerCase()){var g=a.createTextRange();g.collapse(!0);g.moveStart("character",d);g.moveEnd("character",f-d);g.select()}else e.setOffsets(a,b)}};c.exports=h},function(c,b,a){function e(a){return!a?null:a.nodeType===N?a.documentElement:a.firstChild}function f(a,b,d,f,g){var e;t.logTopLevelRenders&&(e=a._currentElement.props.type,e="React mount: "+("string"===typeof e?e:e.displayName|| e.name),console.time(e));g=v.mountComponent(a,d,null,s(a,b),g);e&&console.timeEnd(e);a._renderedComponent._topLevelWrapper=a;K._mountImageIntoNode(g,b,a,f,d)}function d(a,b,d,g){var e=w.ReactReconcileTransaction.getPooled(!d&&q.useCreateElement);e.perform(f,null,a,b,e,d,g);w.ReactReconcileTransaction.release(e)}function g(a,b,d){v.unmountComponent(a,d);b.nodeType===N&&(b=b.documentElement);for(;b.lastChild;)b.removeChild(b.lastChild)}function h(a){if(a=e(a))return a=n.getInstanceFromNode(a),!(!a|| !a._nativeParent)}function k(a){return(a=(a=(a=e(a))&&n.getInstanceFromNode(a))&&!a._nativeParent?a:null)?a._nativeContainerInfo._topLevelWrapper:null}var l=a(58);b=a(53);var m=a(80);a(47);var n=a(17),s=a(368),q=a(372),r=a(34),t=a(196);a(81);var p=a(389),u=a(30),v=a(59),x=a(204),w=a(35),y=a(86),B=a(211),A=a(10),z=a(119),C=a(120);a(12);var I=b.ID_ATTRIBUTE_NAME,O=b.ROOT_ATTRIBUTE_NAME,N=9,D={},L=1,F=function(){this.rootID=L++};F.prototype.isReactComponent={};F.prototype.render=function(){return this.props}; var K={TopLevelWrapper:F,_instancesByReactRootID:D,scrollMonitor:function(a,b){b()},_updateRootComponent:function(a,b,d,f){K.scrollMonitor(d,function(){x.enqueueElementInternal(a,b);f&&x.enqueueCallbackInternal(a,f)});return a},_renderNewRootComponent:function(a,b,f,g){void 0;!b||!(1===b.nodeType||b.nodeType===N||11===b.nodeType)?A(!1):void 0;m.ensureScrollValueMonitoring();a=B(a);w.batchedUpdates(d,a,b,f,g);return D[a._instance.rootID]=a},renderSubtreeIntoContainer:function(a,b,d,f){!(null!=a&&null!= a._reactInternalInstance)?A(!1):void 0;return K._renderSubtreeIntoContainer(a,b,d,f)},_renderSubtreeIntoContainer:function(a,b,d,f){x.validateCallback(f,"ReactDOM.render");!r.isValidElement(b)?A(!1):void 0;void 0;var g=r(F,null,null,null,null,null,b),c=k(d);if(c){if(C(c._currentElement.props,b)){var p=c._renderedComponent.getPublicInstance();K._updateRootComponent(c,g,d,f&&function(){f.call(p)});return p}K.unmountComponentAtNode(d)}b=(b=e(d))&&!(!b.getAttribute||!b.getAttribute(I));var l=h(d);a=K._renderNewRootComponent(g, d,b&&!c&&!l,null!=a?a._reactInternalInstance._processChildContext(a._reactInternalInstance._context):y)._renderedComponent.getPublicInstance();f&&f.call(a);return a},render:function(a,b,d){return K._renderSubtreeIntoContainer(null,a,b,d)},unmountComponentAtNode:function(a){void 0;!a||!(1===a.nodeType||a.nodeType===N||11===a.nodeType)?A(!1):void 0;var b=k(a);if(!b)return h(a),1===a.nodeType&&a.hasAttribute(O),!1;delete D[b._instance.rootID];w.batchedUpdates(g,b,a,!1);return!0},_mountImageIntoNode:function(a, b,d,f,g){!b||!(1===b.nodeType||b.nodeType===N||11===b.nodeType)?A(!1):void 0;if(f){var c=e(b);if(p.canReuseMarkup(a,c)){n.precacheNode(d,c);return}var k=c.getAttribute(p.CHECKSUM_ATTR_NAME);c.removeAttribute(p.CHECKSUM_ATTR_NAME);f=c.outerHTML;c.setAttribute(p.CHECKSUM_ATTR_NAME,k);a:{c=Math.min(a.length,f.length);for(k=0;k<c;k++)if(a.charAt(k)!==f.charAt(k)){c=k;break a}c=a.length===f.length?-1:c}a.substring(c-20,c+20);f.substring(c-20,c+20);b.nodeType===N?A(!1):void 0}b.nodeType===N?A(!1):void 0; if(g.useCreateElement){for(;b.lastChild;)b.removeChild(b.lastChild);l.insertTreeBefore(b,a,null)}else z(b,a),n.precacheNode(d,b.firstChild)}};u.measureMethods(K,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"});c.exports=K},function(c,b,a){b=a(87)({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});c.exports=b},function(c,b,a){var e=a(14),f=a(10),d=null,g={},h=null;c.exports={getComponentClassForElement:function(a){if("function"=== typeof a.type)return a.type;a=a.type;var b=g[a];null==b&&(g[a]=b=null(a));return b},createInternalComponent:function(a){!d?f(!1):void 0;return new d(a)},createInstanceForText:function(a){return new h(a)},isTextComponent:function(a){return a instanceof h},injection:{injectGenericComponentClass:function(a){d=a},injectTextComponentClass:function(a){h=a},injectComponentClasses:function(a){e(g,a)}}}},function(c,b,a){var e=a(34),f=a(10),d={NATIVE:0,COMPOSITE:1,EMPTY:2,getType:function(a){if(null===a||!1=== a)return d.EMPTY;if(e.isValidElement(a))return"function"===typeof a.type?d.COMPOSITE:d.NATIVE;f(!1)}};c.exports=d},function(c,b,a){a(12);c.exports={isMounted:function(a){return!1},enqueueCallback:function(a,b){},enqueueForceUpdate:function(a){},enqueueReplaceState:function(a,b){},enqueueSetState:function(a,b){}}},function(c,b,a){function e(a){function b(d,f,g,e,c,h){e=e||m;h=h||g;return null==f[g]?(f=k[c],d?Error("Required "+f+" `"+h+"` was not specified in "+("`"+e+"`.")):null):a(f,g,e,c,h)}var d= b.bind(null,!1);d.isRequired=b.bind(null,!0);return d}function f(a){return e(function(b,d,f,e,c){b=b[d];if(g(b)!==a){e=k[e];a:{d=g(b);if("object"===d)if(b instanceof Date){b="date";break a}else if(b instanceof RegExp){b="regexp";break a}b=d}return Error("Invalid "+e+" `"+c+"` of type "+("`"+b+"` supplied to `"+f+"`, expected ")+("`"+a+"`."))}return null})}function d(a){switch(typeof a){case "number":case "string":case "undefined":return!0;case "boolean":return!a;case "object":if(Array.isArray(a))return a.every(d); if(null===a||h.isValidElement(a))return!0;var b=l(a);if(b){var f=b.call(a);if(b!==a.entries)for(;!(a=f.next()).done;){if(!d(a.value))return!1}else for(;!(a=f.next()).done;)if((a=a.value)&&!d(a[1]))return!1}else return!1;return!0;default:return!1}}function g(a){var b=typeof a;return Array.isArray(a)?"array":a instanceof RegExp?"object":b}var h=a(34),k=a(82);b=a(40);var l=a(117),m="<<anonymous>>";a={array:f("array"),bool:f("boolean"),func:f("function"),number:f("number"),object:f("object"),string:f("string"), any:e(b.thatReturns(null)),arrayOf:function(a){return e(function(b,d,f,e,c){if("function"!==typeof a)return Error("Property `"+c+"` of component `"+f+"` has invalid PropType notation inside arrayOf.");b=b[d];if(!Array.isArray(b))return e=k[e],b=g(b),Error("Invalid "+e+" `"+c+"` of type "+("`"+b+"` supplied to `"+f+"`, expected an array."));for(d=0;d<b.length;d++){var h=a(b,d,f,e,c+"["+d+"]");if(h instanceof Error)return h}return null})},element:function(){return e(function(a,b,d,f,g){return!h.isValidElement(a[b])? Error("Invalid "+k[f]+" `"+g+"` supplied to "+("`"+d+"`, expected a single ReactElement.")):null})}(),instanceOf:function(a){return e(function(b,d,f,g,e){if(!(b[d]instanceof a)){g=k[g];var c=a.name||m;b=b[d];b=!b.constructor||!b.constructor.name?m:b.constructor.name;return Error("Invalid "+g+" `"+e+"` of type "+("`"+b+"` supplied to `"+f+"`, expected ")+("instance of `"+c+"`."))}return null})},node:function(){return e(function(a,b,f,g,e){return!d(a[b])?Error("Invalid "+k[g]+" `"+e+"` supplied to "+ ("`"+f+"`, expected a ReactNode.")):null})}(),objectOf:function(a){return e(function(b,d,f,e,c){if("function"!==typeof a)return Error("Property `"+c+"` of component `"+f+"` has invalid PropType notation inside objectOf.");b=b[d];d=g(b);if("object"!==d)return Error("Invalid "+k[e]+" `"+c+"` of type "+("`"+d+"` supplied to `"+f+"`, expected an object."));for(var h in b)if(b.hasOwnProperty(h)&&(d=a(b,h,f,e,c+"."+h),d instanceof Error))return d;return null})},oneOf:function(a){return!Array.isArray(a)? e(function(){return Error("Invalid argument supplied to oneOf, expected an instance of array.")}):e(function(b,d,f,g,e){b=b[d];for(d=0;d<a.length;d++){var c;c=a[d];c=b===c?0!==b||1/b===1/c:b!==b&&c!==c;if(c)return null}g=k[g];d=JSON.stringify(a);return Error("Invalid "+g+" `"+e+"` of value `"+b+"` "+("supplied to `"+f+"`, expected one of "+d+"."))})},oneOfType:function(a){return!Array.isArray(a)?e(function(){return Error("Invalid argument supplied to oneOfType, expected an instance of array.")}): e(function(b,d,f,g,e){for(var c=0;c<a.length;c++)if(null==(0,a[c])(b,d,f,g,e))return null;return Error("Invalid "+k[g]+" `"+e+"` supplied to "+("`"+f+"`."))})},shape:function(a){return e(function(b,d,f,e,c){b=b[d];d=g(b);if("object"!==d)return Error("Invalid "+k[e]+" `"+c+"` of type `"+d+"` "+("supplied to `"+f+"`, expected `object`."));for(var h in a)if(d=a[h])if(d=d(b,h,f,e,c+"."+h))return d;return null})}};c.exports=a},function(c,b,a){function e(a,b){var d=f.get(a);return!d?null:d}a(47);var f= a(110),d=a(35),g=a(10);a(12);var h={isMounted:function(a){return(a=f.get(a))?!!a._renderedComponent:!1},enqueueCallback:function(a,b,f){h.validateCallback(b,f);a=e(a);if(!a)return null;a._pendingCallbacks?a._pendingCallbacks.push(b):a._pendingCallbacks=[b];d.enqueueUpdate(a)},enqueueCallbackInternal:function(a,b){a._pendingCallbacks?a._pendingCallbacks.push(b):a._pendingCallbacks=[b];d.enqueueUpdate(a)},enqueueForceUpdate:function(a){if(a=e(a,"forceUpdate"))a._pendingForceUpdate=!0,d.enqueueUpdate(a)}, enqueueReplaceState:function(a,b){var f=e(a,"replaceState");f&&(f._pendingStateQueue=[b],f._pendingReplaceState=!0,d.enqueueUpdate(f))},enqueueSetState:function(a,b){var f=e(a,"setState");f&&((f._pendingStateQueue||(f._pendingStateQueue=[])).push(b),d.enqueueUpdate(f))},enqueueElementInternal:function(a,b){a._pendingElement=b;d.enqueueUpdate(a)},validateCallback:function(a,b){a&&"function"!==typeof a?g(!1):void 0}};c.exports=h},function(c,b){c.exports="15.0.1"},function(c,b){var a={currentScrollLeft:0, currentScrollTop:0,refreshScrollValues:function(b){a.currentScrollLeft=b.x;a.currentScrollTop=b.y}};c.exports=a},function(c,b,a){var e=a(10);c.exports=function(a,b){null==b?e(!1):void 0;if(null==a)return b;var g=Array.isArray(a),c=Array.isArray(b);return g&&c?(a.push.apply(a,b),a):g?(a.push(b),a):c?[a].concat(b):[a,b]}},function(c,b){c.exports=function(a,b,f){Array.isArray(a)?a.forEach(b,f):a&&b.call(f,a)}},function(c,b,a){var e=a(201);c.exports=function(a){for(var b;(b=a._renderedNodeType)===e.COMPOSITE;)a= a._renderedComponent;if(b===e.NATIVE)return a._renderedComponent;if(b===e.EMPTY)return null}},function(c,b,a){var e=a(22),f=null;c.exports=function(){!f&&e.canUseDOM&&(f="textContent"in document.documentElement?"textContent":"innerText");return f}},function(c,b,a){function e(a){var b;null===a||!1===a?b=d.create(e):"object"===typeof a?(!a||!("function"===typeof a.type||"string"===typeof a.type)?h(!1):void 0,b="string"===typeof a.type?g.createInternalComponent(a):"function"===typeof a.type&&"undefined"!== typeof a.type.prototype&&"function"===typeof a.type.prototype.mountComponent&&"function"===typeof a.type.prototype.receiveComponent?new a.type(a):new k(a)):"string"===typeof a||"number"===typeof a?b=g.createInstanceForText(a):h(!1);b._mountIndex=0;b._mountImage=null;return b}b=a(14);var f=a(365),d=a(195),g=a(200),h=a(10);a(12);var k=function(a){this.construct(a)};b(k.prototype,f.Mixin,{_instantiateReactComponent:e});c.exports=e},function(c,b){var a={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};c.exports=function(b){var f=b&&b.nodeName&&b.nodeName.toLowerCase();return f&&("input"===f&&a[b.type]||"textarea"===f)}},function(c,b,a){b=a(22);var e=a(85),f=a(119);a=function(a,b){a.textContent=b};b.canUseDOM&&("textContent"in document.documentElement||(a=function(a,b){f(a,e(b))}));c.exports=a},function(c,b,a){var e=a(40);c.exports={listen:function(a,b,g){if(a.addEventListener)return a.addEventListener(b, g,!1),{remove:function(){a.removeEventListener(b,g,!1)}};if(a.attachEvent)return a.attachEvent("on"+b,g),{remove:function(){a.detachEvent("on"+b,g)}}},capture:function(a,b,g){return a.addEventListener?(a.addEventListener(b,g,!0),{remove:function(){a.removeEventListener(b,g,!0)}}):{remove:e}},registerDefault:function(){}}},function(c,b){c.exports=function(a){try{a.focus()}catch(b){}}},function(c,b){c.exports=function(){if("undefined"===typeof document)return null;try{return document.activeElement|| document.body}catch(a){return document.body}}},function(c,b,a){b=a(22);var e=a(10),f=b.canUseDOM?document.createElement("div"):null,d={};a=[1,'<select multiple="true">',"</select>"];b=[1,"<table>","</table>"];var g=[3,"<table><tbody><tr>","</tr></tbody></table>"],h=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],k={"*":[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:a,option:a,caption:b,colgroup:b,tbody:b,tfoot:b,thead:b,td:g,th:g};"circle clipPath defs ellipse g image line linearGradient mask path pattern polygon polyline radialGradient rect stop text tspan".split(" ").forEach(function(a){k[a]=h;d[a]=!0});c.exports=function(a){!f?e(!1):void 0;k.hasOwnProperty(a)||(a="*");d.hasOwnProperty(a)||(f.innerHTML="*"===a?"<link />":"<"+a+"></"+a+">",d[a]=!f.firstChild);return d[a]?k[a]:null}},function(c,b,a){b=a(947); a=a(948);c.exports=b;c.exports.BundleType=a},function(c,b,a){b=a(72);var e=a(101),f=a(102),d=a(526),g=a(64),h=a(273),k=a(455),l=a(608),m=a(282),n=a(124),s=a(709),q=a(710);a=a(787);c.exports={Button:b,Check:e,Description:f,FlatSelect:d,Input:g,Label:h,RadioGroup:k,Range:l,Search:m,Select:n,TextArea:s,Toggle:q,File:a}},,function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NDkx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c,l){var m=c?e(c):0;if(!f(m))return a(c,l);for(var n=b?m:-1,s=d(c);(b?n--:++n<m)&&!1!==l(s[n],n,s););return c}}},function(c,b,a){var e=a(73),f=Object.prototype.toString;c.exports=function(a){return"number"==typeof a||e(a)&&"[object Number]"==f.call(a)}},function(c,b,a){b=a(452);var e=a(906);a=a(912);c.exports={TransitionGroup:b,CSSTransitionGroup:e,CSSTransitionGroupPresets:a}},,function(c,b){c.exports={DEFAULT:1, DOMAIN_FIRST:2,GOOGLE_DOMAINS:3}},function(c,b,a){var e=(b=a(16))&&b.__esModule?b:{"default":b},f=a(93).globalGrid,d=a(586),g=function(a){return{left:a.x,top:a.y}},h=function(a){return a===d.BOTTOM_RIGHT||a===d.CENTER_RIGHT||a===d.TOP_RIGHT},k=function(a){return a===d.BOTTOM_CENTER||a===d.BOTTOM_LEFT||a===d.BOTTOM_RIGHT},l=function(a){return a===d.BOTTOM_CENTER||a===d.CENTER_CENTER||a===d.TOP_CENTER},m=function(a){return a===d.CENTER_CENTER||a===d.CENTER_LEFT||a===d.CENTER_RIGHT},n=function(a,b){var d= window,g=d.innerHeight,d=d.innerWidth,c=(0,e.default)({},a);a.x+b.width>d-f&&(c.x=d-b.width-f);a.x<f&&(c.x=f);a.y+b.height>g-f&&(c.y=g-b.height-f);a.y<f&&(c.y=f);return c};c.exports={centerOnMouse:function(a){var b=window.Y.Squarespace.Mouse;a={width:a.offsetWidth,height:a.offsetHeight};b=n({x:b.lastX-Math.floor(a.width/2),y:b.lastY-Math.floor(a.height/2)},a);return g({x:b.x,y:b.y})},fromStyleCoords:function(a){return{x:a.left,y:a.top}},toStyleCoords:g,constrainToWindow:n,translatePointToCorner:function(a, b,d){a=(0,e.default)({x:0,y:0},a);b=(0,e.default)({width:0,height:0},b);h(d)&&(a.x+=b.width);l(d)&&(a.x+=Math.floor(b.width/2));m(d)&&(a.y+=Math.floor(b.height/2));k(d)&&(a.y+=b.height);return a},translateJoinOffset:function(a,b){var d=a.offsetX,f=a.offsetY;h(b)&&(d*=-1);k(b)&&(f*=-1);return{offsetX:d,offsetY:f}},isCenteredVertically:m,isCenteredHorizontally:l,isRight:h,isLeft:function(a){return a===d.BOTTOM_LEFT||a===d.CENTER_LEFT||a===d.TOP_LEFT},isTop:function(a){return a===d.TOP_CENTER||a===d.TOP_LEFT|| a===d.TOP_RIGHT},isBottom:k,positions:d}},function(c,b,a){c.exports={"default":a(308),__esModule:!0}},,function(c,b,a){var e=a(296);c.exports=function(a){return(a=e(a))&&a.charAt(0).toUpperCase()+a.slice(1)}},,,function(c,b,a){c.exports={"default":a(793),__esModule:!0}},function(c,b,a){var e=a(257),f=a(38),d=a(442),g=a(27);c.exports=function(a,b,c){var m=g(a)?e:d;b=f(b,c,3);return m(a,b)}},function(c,b,a){b=a(580);var e=a(49);a=a(446)(b,e);c.exports=a},function(c,b,a){var e=a(159),f=a(38),d=a(259), g=a(27);c.exports=function(a,b,c){var m=g(a)?e:d;b=f(b,c,3);return m(a,b)}},function(c,b,a){var e=a(132);c.exports=function(a,b){a=e(a);for(var g=-1,c=b.length,k={};++g<c;){var l=b[g];l in a&&(k[l]=a[l])}return k}},function(c,b,a){var e=a(271);c.exports=function(a,b){var g={};e(a,function(a,f,e){b(a,f,e)&&(g[f]=a)});return g}},function(c,b,a){var e=a(73),f=Object.prototype.toString;c.exports=function(a){return"string"==typeof a||e(a)&&"[object String]"==f.call(a)}},,function(c,b,a){var e=a(159),f= a(581),d=a(65),g=a(100),h=a(128),k=a(244),l=a(245);b=a(56)(function(a,b){if(null==a)return{};if("function"!=typeof b[0])return b=e(d(b),String),k(a,f(h(a),b));var c=g(b[0],b[1],3);return l(a,function(a,b,d){return!c(a,b,d)})});c.exports=b},,,,function(c,b,a){b=c.exports=a(3)();b.i(a(166),void 0);b.i(a(45),void 0);b.push([c.id,".Select-selectFacadeFormField-2O0lP {\n background-color: #e4e4e4;\n transition: background-color 0.2s ease-in-out;\n}\n.Select-selectFacadeFormField-2O0lP:hover {\n background-color: #d0d0d0;\n}\n.Select-selectFacadeFormField-2O0lP:after {\n content: '';\n display: block;\n position: absolute;\n top: 0;\n right: 0;\n width: 44px;\n height: 100%;\n cursor: pointer;\n background: transparent url("+ a(169)+") center center no-repeat;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .Select-selectFacadeFormField-2O0lP:after {\n background-image: url("+a(170)+");\n background-size: 16px;\n }\n}\n.Select-light-2JEZZ .Select-selectFacadeFormField-2O0lP {\n background-color: #ffffff;\n color: #3e3e3e;\n}\n.Select-light-2JEZZ .Select-selectFacadeFormField-2O0lP:after {\n background: transparent url("+ a(169)+") center center no-repeat;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .Select-light-2JEZZ .Select-selectFacadeFormField-2O0lP:after {\n background-image: url("+a(170)+");\n background-size: 16px;\n }\n}\n.Select-minor-1itOb .Select-selectFacadeFormField-2O0lP {\n background-color: #e4e4e4;\n color: #3e3e3e;\n}\n.Select-minor-1itOb .Select-selectFacadeFormField-2O0lP:hover {\n background-color: #d0d0d0;\n}\n.Select-minor-1itOb .Select-selectFacadeFormField-2O0lP:after {\n background: transparent url("+ a(169)+") center center no-repeat;\n}\n@media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n .Select-minor-1itOb .Select-selectFacadeFormField-2O0lP:after {\n background-image: url("+a(170)+");\n background-size: 16px;\n }\n}\n.Select-hasErrors-8bTfc .Select-selectFacadeFormField-2O0lP {\n box-shadow: inset 0 0 0 2px #f0523d;\n}\n.Select-selectField-2RJbZ {\n position: absolute;\n top: 0;\n left: 0;\n background: #fff;\n opacity: 0;\n height: 100%;\n width: 100%;\n border-radius: 0;\n cursor: pointer;\n z-index: 2;\n}\n.Select-label-1m-8R {\n box-sizing: border-box;\n padding-right: 33px;\n width: 100%;\n}\n.Select-midnight-q3lAl {\n padding: 0;\n margin-top: 0;\n font-weight: 400;\n}\n.Select-midnight-q3lAl .Select-selectFacadeFormField-2O0lP {\n border-bottom: 1px solid #888888;\n color: #ffffff;\n background: transparent;\n font-size: 16px;\n padding-left: 0;\n}\n.Select-midnight-q3lAl.Select-focused-2ngrh .Select-selectFacadeFormField-2O0lP {\n border-color: #ffffff;\n}\n.Select-midnight-q3lAl.Select-hasErrors-8bTfc .Select-selectFacadeFormField-2O0lP {\n border-color: #f0523d;\n box-shadow: none;\n}\n.Select-denarius-34PvG {\n position: relative;\n}\n.Select-denarius-34PvG .FieldLabel {\n font-size: 12px;\n position: absolute;\n top: 15px;\n left: 11px;\n color: #a1a1a1;\n font-weight: 300;\n}\n.Select-denarius-34PvG.Select-hasValue-3oQyS .FieldLabel {\n font-size: 9px;\n float: left;\n font-weight: 500;\n text-transform: uppercase;\n position: absolute;\n top: 9px;\n left: 11px;\n color: #a1a1a1;\n letter-spacing: .4px;\n}\n.Select-denarius-34PvG .Select-selectFacadeFormField-2O0lP {\n border: 1px solid #e4e4e4;\n border-radius: 3px;\n font-size: 12px;\n height: 44px;\n box-sizing: border-box;\n padding: 17px 9px 0px 9px;\n background: transparent;\n}\n.Select-denarius-34PvG.Select-focused-2ngrh .Select-selectFacadeFormField-2O0lP {\n border-color: #a1a1a1;\n}\n.Select-denarius-34PvG.Select-unlabeled-3Ub8x .Select-selectFacadeFormField-2O0lP {\n font-weight: 500;\n padding-top: 12px;\n font-size: 11px;\n text-transform: uppercase;\n}\n", ""]);b.locals={selectFacadeFormField:"Select-selectFacadeFormField-2O0lP "+a(166).locals.formField+"",light:"Select-light-2JEZZ",minor:"Select-minor-1itOb",hasErrors:"Select-hasErrors-8bTfc",selectField:"Select-selectField-2RJbZ",label:"Select-label-1m-8R "+a(45).locals.ellipsis+"",midnight:"Select-midnight-q3lAl",focused:"Select-focused-2ngrh",denarius:"Select-denarius-34PvG",hasValue:"Select-hasValue-3oQyS",unlabeled:"Select-unlabeled-3Ub8x"}},function(c,b,a){b=a(545);"string"===typeof b&&(b=[[c.id, b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,function(c,b,a){b=a(860);var e=a(49);a=a(447)(b,e);c.exports=a},,function(c,b){c.exports=function(a,b){for(var f=-1,d=a.length,g=-1,c=[];++f<d;){var k=a[f];b(k,f,a)&&(c[++g]=k)}return c}},function(c,b,a){b=a(323);a=a(229)(b,!0);c.exports=a},function(c,b,a){var e=a(49),f=a(62);c.exports=function(a,b){var c=-1,k=f(a)?Array(a.length):[];e(a,function(a,d,f){k[++c]=b(a,d,f)});return k}},function(c,b,a){var e=a(62),f=a(70),d=a(71);c.exports=function(a){return null== a?[]:!e(a)?d(a):f(a)?a:Object(a)}},,,function(c,b,a){b=c.exports=a(3)();b.push([c.id,".fieldMargins-smallMargin-gMwlV {\n margin-top: 11px;\n}\n.fieldMargins-largeMargin-8fv0Y {\n margin-top: 33px;\n}\n",""]);b.locals={smallMargin:"fieldMargins-smallMargin-gMwlV",largeMargin:"fieldMargins-largeMargin-8fv0Y"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".shadows-windowShadow-uN5yx {\n box-shadow: 0 4px 33px rgba(0,0,0,.22), 0 0 0 1px rgba(0,0,0,.04);\n}\n",""]);b.locals={windowShadow:"shadows-windowShadow-uN5yx"}}, ,,function(c,b){c.exports={APPLICATION:1,LINKED:2,SQUARESPACE:3,GOOGLE:4}},,,,function(c,b,a){var e=a(597),f=a(128);c.exports=function(a,b){return e(a,b,f)}},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(29);var f=e(b);b=a(4);var d=e(b);b=a(7);var g=e(b);b=a(9);var h=a(921);a=function(){function a(){(0,d.default)(this,a);this.generateActions("updateSuccess","updateFailure")}(0,g.default)(a,[{key:"update",value:function(a){var b=this;this.dispatch(a);return h.update(a).then(function(a){b.actions.updateSuccess(a); return f.default.resolve(a)}).catch(function(a){console.error(a);return f.default.reject(a.data)})}},{key:"markTutorialCompleted",value:function(a){if("string"!==typeof a)throw Error("Tutorial needs to be a string");this.dispatch(a);return h.markTutorialCompleted(a).then(function(a){return f.default.resolve(a)}).catch(function(a){console.error(a);return f.default.reject(a)})}},{key:"sendVerificationEmail",value:function(a){return h.sendVerificationEmail(a)}}]);return a}();c.exports=b.createActions(a)}, function(c,b,a){var e=a(2),f=a(11),d=a(548);b=a(28);b=e.createClass({displayName:"Label",propTypes:{title:e.PropTypes.string.isRequired,theme:b.isRequired},getDefaultProps:function(){return{theme:"damask"}},render:function(){var a=this.props,b=a.title;return e.createElement("div",{className:f("FieldLabel",d[a.theme])},e.createElement("label",{className:"FieldLabel-text"},b))}});c.exports=b},,function(c,b,a){b=a(166);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)}, ,,,function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b},d=a(26).Map;b=a(9);var g=a(52),h=a(272),k=a(44),l=a(565);a=function(){function a(){(0,e.default)(this,a);this.state=d();this.bindListeners({onStaticBootstrap:k.BOOTSTRAP,onUpdateAuthorSuccess:l.updateAuthorSuccess,onUpdate:h.update,onMarkTutorialCompleted:h.markTutorialCompleted});this.exportPublicMethods({isTutorialCompleted:this.isTutorialCompleted,markTutorialCompleted:this.markTutorialCompleted})} (0,f.default)(a,[{key:"onStaticBootstrap",value:function(a){this.setState(this.state.merge(a.authenticatedAccount))}},{key:"onUpdate",value:function(a){this.setState(this.state.merge(a))}},{key:"onUpdateAuthorSuccess",value:function(a){a.id===this.state.get("id")&&this.setState(this.state.merge(a))}},{key:"onMarkTutorialCompleted",value:function(a){var b;this.setState(this.state.mergeDeep({tutorialsCompleted:(b={},b[a]=!0,b)}))}},{key:"isTutorialCompleted",value:function(a){var b=this.getState().get("tutorialsCompleted"); return!!b&&!!b.get(a)}},{key:"markTutorialCompleted",value:function(a){var b=this.getState().get("tutorialsCompleted");(!b||!b.get(a))&&h.markTutorialCompleted(a)}}]);return a}();c.exports=b.createStore(g(a),"AuthenticatedAccountStore")},,,function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11),h=a(37),k=a(246),l=a(737);a=d.createClass({displayName:"Search",propTypes:{className:d.PropTypes.string,disabled:d.PropTypes.bool,errorMessage:d.PropTypes.string, hideSearchIcon:d.PropTypes.bool,label:d.PropTypes.string,onBlur:d.PropTypes.func,onFocus:d.PropTypes.func,onChange:d.PropTypes.func,onReset:d.PropTypes.func,placeholder:d.PropTypes.string,value:d.PropTypes.string.isRequired},getDefaultProps:function(){return{disabled:!1,onChange:function(){},onReset:function(){},value:""}},focus:function(){this.refs.input.focus()},blur:function(){this.refs.input.blur()},handleReset:function(){this.props.onChange({target:{value:""}});this.props.onReset()},render:function(){var a, b,c,q=this.props,r=q.className,t=q.errorMessage,p=q.label,u=q.value,v=q.hideSearchIcon,x=q.disabled,q=(0,f.default)(q,"className errorMessage label value hideSearchIcon disabled".split(" ")),w=""===u.trim(),r=g(r,l.container,(a={},a[l.hasErrors]=k(t),a));a=g(l.btnClear,"btn-clear",(b={hidden:!k(u)||w},b[l.hidden]=!k(u)||w,b));b=g(l.searchInput,(c={},c[l.hiddenSearchIcon]=v,c));return d.createElement(h,{className:r,errorMessage:t,label:p},d.createElement("input",(0,e.default)({className:b,ref:"input", type:"text",value:u,disabled:x},q)),!v&&d.createElement("div",{className:l.searchIcon}),!x&&d.createElement("div",{className:a,onClick:this.handleReset}))}});c.exports=a},,,,,,,,,,,function(c,b){c.exports={FOURSQUARE:1,FACEBOOK:2,FLICKR:3,TWITTER:4,GOOGLE:5,GOOGLE_SPREADSHEET:6,TUMBLR:8,DROPBOX:9,INSTAGRAM:10,YOUTUBE:11,VIMEO:12,MAILCHIMP:13,LINKEDIN:14,STRIPE:15,FIVEHUNDREDPIX:16,SMUGMUG:17,DRIBBBLE:18,PINTEREST:19,EMAIL:20,GOOGLEAUTH2:21,GOOGLEDOCS2:22,GITHUB:23,XERO:24,SOUNDCLOUD:25,SPOTIFY:26, ITUNES:27,GOOGLEPLAY:28,BANDSINTOWN:29,BEHANCE:30,CODEPEN:31,MEDIUM:32,MEETUP:33,RDIO:34,TWITCH:35,VEVO:36,VINE:37,VSCO:38,YELP:39,DROPBOX2:40,PAYPAL:41,HOUZZ:42,REDDIT:43,STUMBLEUPON:44}},,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(286);var f=e(b);b=a(77);var d=e(b);a=a(19);var g=e(a);c.exports=function(a){var b={};(0,g.default)(a).map(function(g){var e=a[g];"object"===("undefined"===typeof e?"undefined":(0,d.default)(e))?b[g]=(0,f.default)(e):void 0!==e&&(b[g]=e)}); return b}},,function(c,b,a){var e=a(70);c.exports=function(a,b){var g=a.data;return("string"==typeof b||e(b)?g.set.has(b):g.hash[b])?0:-1}},function(c,b,a){(function(b){var f=a(743),d=a(300),g=d(b,"Set"),h=d(Object,"create");c.exports=function(a){return h&&g?new f(a):null}}).call(b,function(){return this}())},function(c,b,a){var e=a(38),f=a(322),d=a(553),g=a(27);c.exports=function(a,b){return function(c,m,n){m=e(m,n,3);return g(c)?(m=d(c,m,b),-1<m?c[m]:void 0):f(c,m,a)}}},,function(c,b,a){b=a(14); var e=a(188),f=a(190),d=a(189),g=a(371),h=a(34);a(194);var k=a(203),l=a(205),m=a(332);a(12);c.exports={Children:{map:e.map,forEach:e.forEach,count:e.count,toArray:e.toArray,only:m},Component:f,createElement:h.createElement,cloneElement:h.cloneElement,isValidElement:h.isValidElement,PropTypes:k,createClass:d.createClass,createFactory:h.createFactory,createMixin:function(a){return a},DOM:g,version:l,__spread:b}},,,function(c,b){c.exports={ADMIN:"admin",API:"api",AUTH:"auth",BLOG:"blog",CDN:"cdn",CIRCLE:"circle", COMMERCE:"commerce",CUSTOMERCARE:"customercare",CUSTOMERSUPPORT:"customersupport",DEVELOPERS:"developers",INSTAGRAM:"instagram",LOGIN:"login",MASTER:"master",MOBILE:"mobile",MAIL:"mail",NEW:"new",OAUTH:"oauth",SECURE:"secure",SPECIALISTS:"specialists",STATIC:"static",STATIC1:"static1",STORE:"store",SYSTEM:"system",TEMPLATE_MASTER:"template-master",VERIFY:"verify",WEB_HOOKS:"web-hooks",WW:"ww",WWW:"www",WWWW:"wwww",WWWWW:"wwwww"}},,function(c,b,a){c.exports={"default":a(309),__esModule:!0}},function(c, b,a){c.exports={"default":a(312),__esModule:!0}},function(c,b,a){a(314);var e=a(31).Object;c.exports=function(a,b){return e.create(a,b)}},function(c,b,a){a(315);var e=a(31).Object;c.exports=function(a,b){return e.getOwnPropertyDescriptor(a,b)}},function(c,b,a){a(316);c.exports=a(31).Object.getPrototypeOf},function(c,b,a){a(317);c.exports=a(31).Object.keys},function(c,b,a){a(318);c.exports=a(31).Object.setPrototypeOf},function(c,b,a){var e=a(134),f=a(138),d=function(a,b){f(a);if(!e(b)&&null!==b)throw TypeError(b+ ": can't set as prototype!");};c.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(b,f,e){try{e=a(220)(Function.call,a(250).f(Object.prototype,"__proto__").set,2),e(b,[]),f=!(b instanceof Array)}catch(c){f=!0}return function(a,b){d(a,b);f?a.__proto__=b:e(a,b);return a}}({},!1):void 0),check:d}},function(c,b,a){c=a(63);c(c.S,"Object",{create:a(435)})},function(c,b,a){var e=a(139),f=a(250).f;a(88)("getOwnPropertyDescriptor",function(){return function(a,b){return f(e(a),b)}})},function(c, b,a){var e=a(155),f=a(614);a(88)("getPrototypeOf",function(){return function(a){return f(e(a))}})},function(c,b,a){var e=a(155),f=a(165);a(88)("keys",function(){return function(a){return f(e(a))}})},function(c,b,a){c=a(63);c(c.S,"Object",{setPrototypeOf:a(313).set})},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSU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Mzg0RDVBQTE3NEVBNzU2ODgiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5Gfs/SAAAAfklEQVR42mL8//8/AyWAiYFCgNUARkZGEBaA0nBMqgs8gViAoBNAYYCOgSAOJAXEp4CYH69aHAaAwB2oISfJNQAE7iIbQo4BskiGnMCmllA0/gTiH1A2FymBCANXoLZfJscLl5E1k2pAOlTzFYKuxeOCLGK8yzg4MxMpACDAAGQ6Cc0ksCBvAAAAAElFTkSuQmCC"}, ,,function(c,b){c.exports=function(a,b,f,d){var g;f(a,function(a,f,c){if(b(a,f,c))return g=d?f:a,!1});return g}},function(c,b,a){var e=a(554),f=a(78);c.exports=function(a,b){return e(a,b,f)}},,,,,,function(c,b,a){var e=a(17),f=a(384);b=a(198);var d=a(30),g=a(59),h=a(35),k=a(205),l=a(409),m=a(209),n=a(413);a(12);f.inject();a=d.measure("React","render",b.render);a={findDOMNode:l,render:a,unmountComponentAtNode:b.unmountComponentAtNode,version:k,unstable_batchedUpdates:h.batchedUpdates,unstable_renderSubtreeIntoContainer:n}; "undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:e.getClosestInstanceFromNode,getNodeFromInstance:function(a){a._renderedComponent&&(a=m(a));return a?e.getNodeFromInstance(a):null}},Mount:b,Reconciler:g});c.exports=a},function(c,b,a){function e(a,b,f){void 0===a[f]&&null!=b&&(a[f]=b)}var f=a(121);a(12);c.exports=function(a){if(null==a)return a;var b={};f(a, e,b);return b}},function(c,b,a){function e(a,b){var d={};d[a.toLowerCase()]=b.toLowerCase();d["Webkit"+a]="webkit"+b;d["Moz"+a]="moz"+b;d["ms"+a]="MS"+b;d["O"+a]="o"+b.toLowerCase();return d}b=a(22);var f={animationend:e("Animation","AnimationEnd"),animationiteration:e("Animation","AnimationIteration"),animationstart:e("Animation","AnimationStart"),transitionend:e("Transition","TransitionEnd")},d={},g={};b.canUseDOM&&(g=document.createElement("div").style,"AnimationEvent"in window||(delete f.animationend.animation, delete f.animationiteration.animation,delete f.animationstart.animation),"TransitionEvent"in window||delete f.transitionend.transition);c.exports=function(a){if(d[a])return d[a];if(!f[a])return a;var b=f[a],e;for(e in b)if(b.hasOwnProperty(e)&&e in g)return d[a]=b[e];return""}},function(c,b,a){var e=a(34),f=a(10);c.exports=function(a){!e.isValidElement(a)?f(!1):void 0;return a}},function(c,b,a){var e=a(130);c.exports=function(a,b,g){return!e(a.props,b)||!e(a.state,g)}},,,function(c,b){var a=["Moz", "Webkit","Khtml","O","ms"];c.exports=function(b){var f=(document.documentElement||document.body).style;if("string"!==typeof f[b]){b=b.charAt(0).toUpperCase()+b.slice(1);for(var d=0,g=a.length;d<g;d++){var c=""+a[d]+b;if("string"===typeof f[c])return c}}return b}},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d=a(25);a=function(){function a(){(0,e.default)(this,a);this.generateActions("update")}(0,f.default)(a,[{key:"save",value:function(a){var b= this;return d.put("/api/settings",a).then(function(a){return b.actions.update(a.data)})}}]);return a}();c.exports=b.createActions(a)},,function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};a=a(9);b=function(){function a(){(0,e.default)(this,a);this.generateActions("showWebsiteSelector","initialize","bootstrap","search")}(0,f.default)(a,[{key:"createParkingPage",value:function(){this.actions.redirect("/config/authenticated-signup/parking-page")}},{key:"redirect", value:function(a){location.href=a;this.dispatch()}}]);return a}();c.exports=a.createActions(b)},,function(c,b){c.exports={CIRCLE_USER:1}},function(c,b,a){var e=a(94);c.exports={getDomainsRoot:function(){var a=0>=arguments.length||void 0===arguments[0]?window.Static.SQUARESPACE_CONTEXT.website.websiteType:arguments[0];return a===e.COVER_PAGE?"/domains/":a===e.PARKING_PAGE?"/":"/settings/domains/"},getGoogleAppsRoot:function(){return(0>=arguments.length||void 0===arguments[0]?window.Static.SQUARESPACE_CONTEXT.website.websiteType: arguments[0])===e.PARKING_PAGE?"/":"/settings/"},getBillingRoot:function(){return(0>=arguments.length||void 0===arguments[0]?window.Static.SQUARESPACE_CONTEXT.website.websiteType:arguments[0])===e.PARKING_PAGE?"/billing/billing/":"/settings/billing/billing/"},getSwitchProductsRoot:function(){return(0>=arguments.length||void 0===arguments[0]?window.Static.SQUARESPACE_CONTEXT.website.websiteType:arguments[0])===e.PARKING_PAGE?"/upgrade/":"/settings/billing/switch-products/"}}},function(c,b,a){var e= a(2);a=e.PropTypes;b=a.oneOfType([a.instanceOf(Node),a.oneOf(["window","mousepointer"]),a.shape({top:a.number,left:a.number})]);e=a.shape({x:e.PropTypes.number,y:e.PropTypes.number});a=a.oneOfType([a.oneOf(["left","right","center","top","bottom"]),a.shape({join:a.string,to:a.string})]);c.exports={anchor:b,coords:e,position:a}},,function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAXOWlDQ1BJQ0MgUHJvZmlsZQAAaIHtm3dQFN+Wx28POYcZZkgDQ84555xzzmHIIDnnIEkRyQIGckYRJIOiqCAGUEGiIiIqmBAVRILCtvrb97Z291Xt/rFbu/W4XT3326fP9L3dM1X3U+ecBkDKGR8aGoigBSAoODLcUk8TZ+/giCN5DsjgjQJwAEa8Z0Sohrm5MfiHbXsWQL/6JyK/rvWP/f7TRu3lHeEJACQM6zivCM8gWDfD2t4zNDwSAMQvH+6YyNBfmhvWqHB4grCW/6V9/+hfc0N5/NHuv32sLbVgDX+HlNLjtyZP/aV9f2v63F862tMXPs9cDvuLB3v5B8P6LgCMqp5+eC8ApEhhu3BQUMgvLQ1r/j/z/N3Yrf2igr28wz1CAiNx2v4RoYH4OJwWPtDfIxwf6e3133wC/4UWFBj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ng8JgAAAABJRU5ErkJggg=="}, ,,,,,function(c,b){c.exports=function(a,b){for(var f=-1,d=b.length,g=a.length;++f<d;)a[g+f]=b[f];return a}},function(c,b,a){var e=a(748),f="undefined"===typeof window?{}:window;b=["moz","webkit"];var d=f.requestAnimationFrame,g=f.cancelAnimationFrame||f.cancelRequestAnimationFrame;for(a=0;a<b.length&&!d;a++)d=f[b[a]+"RequestAnimationFrame"],g=f[b[a]+"CancelAnimationFrame"]||f[b[a]+"CancelRequestAnimationFrame"];if(!d||!g)var h=0,k=0,l=[],m=1E3/60,d=function(a){if(0===l.length){var b=e(),d=Math.max(0, m-(b-h));h=d+b;setTimeout(function(){for(var a=l.slice(0),b=l.length=0;b<a.length;b++)if(!a[b].cancelled)try{a[b].callback(h)}catch(d){setTimeout(function(){throw d;},0)}},Math.round(d))}l.push({handle:++k,callback:a,cancelled:!1});return k},g=function(a){for(var b=0;b<l.length;b++)l[b].handle===a&&(l[b].cancelled=!0)};c.exports=function(a){return d.call(f,a)};c.exports.cancel=function(){g.apply(f,arguments)}},function(c,b,a){var e=a(17),f=a(215);c.exports={focusDOMComponent:function(){f(e.getNodeFromInstance(this))}}}, function(c,b,a){function e(){var a=window.opera;return"object"===typeof a&&"function"===typeof a.version&&12>=parseInt(a.version(),10)}function f(a,b){switch(a){case y.topKeyUp:return-1!==q.indexOf(b.keyCode);case y.topKeyDown:return b.keyCode!==r;case y.topKeyPress:case y.topMouseDown:case y.topBlur:return!0;default:return!1}}function d(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}function g(a,b){switch(a){case y.topCompositionEnd:return d(b);case y.topKeyPress:if(b.which!==x)return null; A=!0;return w;case y.topTextInput:var f=b.data;return f===w&&A?null:f;default:return null}}function h(a,b){if(z){if(a===y.topCompositionEnd||f(a,b)){var d=z.getData();m.release(z);z=null;return d}return null}switch(a){case y.topPaste:return null;case y.topKeyPress:return b.which&&(!b.ctrlKey&&!b.altKey&&!b.metaKey||b.ctrlKey&&b.altKey)?String.fromCharCode(b.which):null;case y.topCompositionEnd:return v?null:b.data;default:return null}}b=a(42);var k=a(67),l=a(22),m=a(362),n=a(399),s=a(402);a=a(48); var q=[9,13,27,32],r=229,t=l.canUseDOM&&"CompositionEvent"in window,p=null;l.canUseDOM&&"documentMode"in document&&(p=document.documentMode);var u=l.canUseDOM&&"TextEvent"in window&&!p&&!e(),v=l.canUseDOM&&(!t||p&&8<p&&11>=p),x=32,w=String.fromCharCode(x),y=b.topLevelTypes,B={beforeInput:{phasedRegistrationNames:{bubbled:a({onBeforeInput:null}),captured:a({onBeforeInputCapture:null})},dependencies:[y.topCompositionEnd,y.topKeyPress,y.topTextInput,y.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:a({onCompositionEnd:null}), captured:a({onCompositionEndCapture:null})},dependencies:[y.topBlur,y.topCompositionEnd,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:a({onCompositionStart:null}),captured:a({onCompositionStartCapture:null})},dependencies:[y.topBlur,y.topCompositionStart,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:a({onCompositionUpdate:null}),captured:a({onCompositionUpdateCapture:null})},dependencies:[y.topBlur, y.topCompositionUpdate,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]}},A=!1,z=null;c.exports={eventTypes:B,extractEvents:function(a,b,e,c){var p;var l;if(t)b:{switch(a){case y.topCompositionStart:l=B.compositionStart;break b;case y.topCompositionEnd:l=B.compositionEnd;break b;case y.topCompositionUpdate:l=B.compositionUpdate;break b}l=void 0}else z?f(a,e)&&(l=B.compositionEnd):a===y.topKeyDown&&e.keyCode===r&&(l=B.compositionStart);l?(v&&(!z&&l===B.compositionStart?z=m.getPooled(c):l===B.compositionEnd&& z&&(p=z.getData())),l=n.getPooled(l,b,e,c),p?l.data=p:(p=d(e),null!==p&&(l.data=p)),k.accumulateTwoPhaseDispatches(l),p=l):p=null;(a=u?g(a,e):h(a,e))?(b=s.getPooled(B.beforeInput,b,e,c),b.data=a,k.accumulateTwoPhaseDispatches(b)):b=null;return[p,b]}}},function(c,b,a){var e=a(186),f=a(22);b=a(30);a(415);var d=a(408),g=a(421),h=a(425);a(12);var k=h(function(a){return g(a)}),l=!1,m="cssFloat";if(f.canUseDOM){a=document.createElement("div").style;try{a.font=""}catch(n){l=!0}void 0===document.documentElement.style.cssFloat&& (m="styleFloat")}a={createMarkupForStyles:function(a,b){var f="",g;for(g in a)if(a.hasOwnProperty(g)){var e=a[g];null!=e&&(f+=k(g)+":",f+=d(g,e,b)+";")}return f||null},setValueForStyles:function(a,b,f){a=a.style;for(var g in b)if(b.hasOwnProperty(g)){var c=d(g,b[g],f);if("float"===g||"cssFloat"===g)g=m;if(c)a[g]=c;else if(c=l&&e.shorthandPropertyExpansions[g])for(var h in c)a[h]="";else a[g]=""}}};b.measureMethods(a,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"});c.exports=a},function(c, b,a){function e(a){a=x.getPooled(z.change,I,a,w(a));t.accumulateTwoPhaseDispatches(a);v.batchedUpdates(f,a)}function f(a){r.enqueueEvents(a);r.processEventQueue(!1)}function d(){C&&(C.detachEvent("onchange",e),I=C=null)}function g(a,b){if(a===A.topChange)return b}function h(a,b,f){a===A.topFocus?(d(),C=b,I=f,C.attachEvent("onchange",e)):a===A.topBlur&&d()}function k(){C&&(delete C.value,C.detachEvent?C.detachEvent("onpropertychange",l):C.removeEventListener("propertychange",l,!1),N=O=I=C=null)}function l(a){if("value"=== a.propertyName){var b=a.srcElement.value;b!==O&&(O=b,e(a))}}function m(a,b){if(a===A.topInput)return b}function n(a,b,d){a===A.topFocus?(k(),C=b,I=d,O=b.value,N=Object.getOwnPropertyDescriptor(b.constructor.prototype,"value"),Object.defineProperty(C,"value",F),C.attachEvent?C.attachEvent("onpropertychange",l):C.addEventListener("propertychange",l,!1)):a===A.topBlur&&k()}function s(a,b){if((a===A.topSelectionChange||a===A.topKeyUp||a===A.topKeyDown)&&C&&C.value!==O)return O=C.value,I}function q(a, b){if(a===A.topClick)return b}b=a(42);var r=a(66),t=a(67),p=a(22),u=a(17),v=a(35),x=a(43),w=a(116),y=a(118),B=a(212);a=a(48);var A=b.topLevelTypes,z={change:{phasedRegistrationNames:{bubbled:a({onChange:null}),captured:a({onChangeCapture:null})},dependencies:[A.topBlur,A.topChange,A.topClick,A.topFocus,A.topInput,A.topKeyDown,A.topKeyUp,A.topSelectionChange]}},C=null,I=null,O=null,N=null,D=!1;p.canUseDOM&&(D=y("change")&&(!("documentMode"in document)||8<document.documentMode));var L=!1;p.canUseDOM&& (L=y("input")&&(!("documentMode"in document)||11<document.documentMode));var F={get:function(){return N.get.call(this)},set:function(a){O=""+a;N.set.call(this,a)}};c.exports={eventTypes:z,extractEvents:function(a,b,d,f){var e=b?u.getNodeFromInstance(b):window,c,k,p=e.nodeName&&e.nodeName.toLowerCase();if("select"===p||"input"===p&&"file"===e.type)D?c=g:k=h;else if(B(e))L?c=m:(c=s,k=n);else if(e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type))c=q;if(c&&(c=c(a, b)))return a=x.getPooled(z.change,c,d,f),a.type="change",t.accumulateTwoPhaseDispatches(a),a;k&&k(a,e,b)}}},function(c,b){c.exports={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}},function(c,b,a){var e=a(58),f=a(22),d=a(418),g=a(40),h=a(217),k=a(10),l=/^(<[^ \/>]+)/;c.exports={dangerouslyRenderMarkup:function(a){!f.canUseDOM?k(!1):void 0;for(var b,e={},c=0;c<a.length;c++)!a[c]?k(!1):void 0,b=a[c].substring(1,a[c].indexOf(" ")),b= h(b)?b:"*",e[b]=e[b]||[],e[b][c]=a[c];var c=[],r=0;for(b in e)if(e.hasOwnProperty(b)){var t=e[b],p;for(p in t)t.hasOwnProperty(p)&&(t[p]=t[p].replace(l,'$1 data-danger-index="'+p+'" '));for(var t=d(t.join(""),g),u=0;u<t.length;++u){var v=t[u];v.hasAttribute&&v.hasAttribute("data-danger-index")&&(p=+v.getAttribute("data-danger-index"),v.removeAttribute("data-danger-index"),c.hasOwnProperty(p)?k(!1):void 0,c[p]=v,r+=1)}}r!==c.length?k(!1):void 0;c.length!==a.length?k(!1):void 0;return c},dangerouslyReplaceNodeWithMarkup:function(a, b){!f.canUseDOM?k(!1):void 0;!b?k(!1):void 0;"HTML"===a.nodeName?k(!1):void 0;if("string"===typeof b){var c=d(b,g)[0];a.parentNode.replaceChild(c,a)}else e.replaceChildWithTree(a,b)}}},function(c,b,a){b=a(48);b=[b({ResponderEventPlugin:null}),b({SimpleEventPlugin:null}),b({TapEventPlugin:null}),b({EnterLeaveEventPlugin:null}),b({ChangeEventPlugin:null}),b({SelectEventPlugin:null}),b({BeforeInputEventPlugin:null})];c.exports=b},function(c,b,a){b=a(42);var e=a(67),f=a(17),d=a(84);a=a(48);var g=b.topLevelTypes, h={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[g.topMouseOut,g.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[g.topMouseOut,g.topMouseOver]}};c.exports={eventTypes:h,extractEvents:function(a,b,c,n){if(a===g.topMouseOver&&(c.relatedTarget||c.fromElement)||a!==g.topMouseOut&&a!==g.topMouseOver)return null;var s;s=n.window===n?n:(s=n.ownerDocument)?s.defaultView||s.parentWindow:window;a===g.topMouseOut?(a=b,b=(b=c.relatedTarget||c.toElement)?f.getClosestInstanceFromNode(b): null):a=null;if(a===b)return null;var q=null==a?s:f.getNodeFromInstance(a);s=null==b?s:f.getNodeFromInstance(b);var r=d.getPooled(h.mouseLeave,a,c,n);r.type="mouseleave";r.target=q;r.relatedTarget=s;c=d.getPooled(h.mouseEnter,b,c,n);c.type="mouseenter";c.target=s;c.relatedTarget=q;e.accumulateEnterLeaveDispatches(r,c,a,b);return[r,c]}}},function(c,b,a){function e(a){this._root=a;this._startText=this.getText();this._fallbackText=null}b=a(14);var f=a(54),d=a(210);b(e.prototype,{destructor:function(){this._fallbackText= this._startText=this._root=null},getText:function(){return"value"in this._root?this._root.value:this._root[d()]},getData:function(){if(this._fallbackText)return this._fallbackText;var a,b=this._startText,d=b.length,f,e=this.getText(),c=e.length;for(a=0;a<d&&b[a]===e[a];a++);var s=d-a;for(f=1;f<=s&&b[d-f]===e[c-f];f++);return this._fallbackText=e.slice(a,1<f?1-f:void 0)}});f.addPoolingTo(e);c.exports=e},function(c,b,a){b=a(53);a=b.injection.MUST_USE_PROPERTY;var e=b.injection.HAS_BOOLEAN_VALUE,f=b.injection.HAS_SIDE_EFFECTS, d=b.injection.HAS_NUMERIC_VALUE,g=b.injection.HAS_POSITIVE_NUMERIC_VALUE,h=b.injection.HAS_OVERLOADED_BOOLEAN_VALUE;b={isCustomAttribute:RegExp.prototype.test.bind(RegExp("^(data|aria)-["+b.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:e,allowTransparency:0,alt:0,async:e,autoComplete:0,autoPlay:e,capture:e,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:a|e,cite:0,classID:0,className:0,cols:g,colSpan:0,content:0,contentEditable:0,contextMenu:0, controls:e,coords:0,crossOrigin:0,data:0,dateTime:0,"default":e,defer:e,dir:0,disabled:e,download:h,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:e,formTarget:0,frameBorder:0,headers:0,height:0,hidden:e,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:e,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:a| e,muted:a|e,name:0,nonce:0,noValidate:e,open:e,optimum:0,pattern:0,placeholder:0,poster:0,preload:0,profile:0,radioGroup:0,readOnly:e,rel:0,required:e,reversed:e,role:0,rows:g,rowSpan:d,sandbox:0,scope:0,scoped:e,scrolling:0,seamless:e,selected:a|e,shape:0,size:g,sizes:0,span:g,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:d,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:a|f,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:e,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};c.exports=b},function(c,b,a){function e(a,b,f){var g=void 0===a[f];null!=b&&g&&(a[f]=d(b))}var f=a(59),d=a(211),g=a(120),h=a(121);a(12);c.exports={instantiateChildren:function(a,b,d){if(null==a)return null;b={};h(a,e,b);return b}, updateChildren:function(a,b,e,c,h){if(b||a){var q,r;for(q in b)if(b.hasOwnProperty(q)){var t=(r=a&&a[q])&&r._currentElement,p=b[q];null!=r&&g(t,p)?f.receiveComponent(r,p,c,h):(r&&(e[q]=f.getNativeNode(r),f.unmountComponent(r,!1)),r=d(p));b[q]=r}for(q in a)if(a.hasOwnProperty(q)&&(!b||!b.hasOwnProperty(q)))r=a[q],e[q]=f.getNativeNode(r),f.unmountComponent(r,!1)}},unmountChildren:function(a,b){for(var d in a)a.hasOwnProperty(d)&&f.unmountComponent(a[d],b)}}},function(c,b,a){function e(a){}var f=a(14), d=a(108),g=a(47),h=a(34),k=a(109),l=a(110);a(81);var m=a(201);b=a(30);a(83);a(82);var n=a(59),s=a(204),q=a(86),r=a(10),t=a(120);a(12);e.prototype.render=function(){var a=l.get(this)._currentElement.type;return a(this.props,this.context,this.updater)};var p=1;a={construct:function(a){this._currentElement=a;this._pendingStateQueue=this._pendingElement=this._nativeContainerInfo=this._nativeParent=this._instance=this._rootNodeID=null;this._pendingForceUpdate=this._pendingReplaceState=!1;this._context= this._renderedComponent=this._renderedNodeType=null;this._mountOrder=0;this._pendingCallbacks=this._topLevelWrapper=null},mountComponent:function(a,b,d,f){this._context=f;this._mountOrder=p++;this._nativeParent=b;this._nativeContainerInfo=d;var g=this._processProps(this._currentElement.props),c=this._processContext(f),k=this._currentElement.type,m,t;if(k.prototype&&k.prototype.isReactComponent)m=new k(g,c,s);else if(m=k(g,c,s),null==m||null==m.render)t=m,!(null===m||!1===m||h.isValidElement(m))?r(!1): void 0,m=new e(k);m.props=g;m.context=c;m.refs=q;m.updater=s;this._instance=m;l.set(m,this);g=m.state;void 0===g&&(m.state=g=null);"object"!==typeof g||Array.isArray(g)?r(!1):void 0;this._pendingStateQueue=null;this._pendingForceUpdate=this._pendingReplaceState=!1;b=m.unstable_handleError?this.performInitialMountWithErrorHandling(t,b,d,a,f):this.performInitialMount(t,b,d,a,f);m.componentDidMount&&a.getReactMountReady().enqueue(m.componentDidMount,m);return b},performInitialMountWithErrorHandling:function(a, b,d,f,g){var e,c=f.checkpoint();try{e=this.performInitialMount(a,b,d,f,g)}catch(h){f.rollback(c),this._instance.unstable_handleError(h),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),c=f.checkpoint(),this._renderedComponent.unmountComponent(!0),f.rollback(c),e=this.performInitialMount(a,b,d,f,g)}return e},performInitialMount:function(a,b,d,f,g){var e=this._instance;e.componentWillMount&&(e.componentWillMount(),this._pendingStateQueue&& (e.state=this._processPendingState(e.props,e.context)));void 0===a&&(a=this._renderValidatedComponent());this._renderedNodeType=m.getType(a);this._renderedComponent=this._instantiateReactComponent(a);return n.mountComponent(this._renderedComponent,f,b,d,this._processChildContext(g))},getNativeNode:function(){return n.getNativeNode(this._renderedComponent)},unmountComponent:function(a){if(this._renderedComponent){var b=this._instance;if(b.componentWillUnmount)if(a){var d=this.getName()+".componentWillUnmount()"; k.invokeGuardedCallback(d,b.componentWillUnmount.bind(b))}else b.componentWillUnmount();this._renderedComponent&&(n.unmountComponent(this._renderedComponent,a),this._instance=this._renderedComponent=this._renderedNodeType=null);this._pendingStateQueue=null;this._pendingForceUpdate=this._pendingReplaceState=!1;this._topLevelWrapper=this._rootNodeID=this._context=this._pendingElement=this._pendingCallbacks=null;l.remove(b)}},_maskContext:function(a){var b=this._currentElement.type.contextTypes;if(!b)return q; var d={},f;for(f in b)d[f]=a[f];return d},_processContext:function(a){return this._maskContext(a)},_processChildContext:function(a){var b=this._currentElement.type,d=this._instance;if(d=d.getChildContext&&d.getChildContext()){"object"!==typeof b.childContextTypes?r(!1):void 0;for(var g in d)!(g in b.childContextTypes)?r(!1):void 0;return f({},a,d)}return a},_processProps:function(a){return a},_checkPropTypes:function(a,b,d){var f=this.getName(),g;for(g in a)if(a.hasOwnProperty(g)){var e;try{"function"!== typeof a[g]?r(!1):void 0,e=a[g](b,g,f,d)}catch(c){e=c}if(e instanceof Error){var h=this._currentElement._owner||null;h&&h.getName();void 0}}},receiveComponent:function(a,b,d){var f=this._currentElement,g=this._context;this._pendingElement=null;this.updateComponent(b,f,a,g,d)},performUpdateIfNecessary:function(a){null!=this._pendingElement&&n.receiveComponent(this,this._pendingElement,a,this._context);(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(a,this._currentElement, this._currentElement,this._context,this._context)},updateComponent:function(a,b,d,f,g){f=this._instance;var e=!1,c;this._context===g?c=f.context:(c=this._processContext(g),e=!0);b===d?b=d.props:(b=this._processProps(d.props),e=!0);e&&f.componentWillReceiveProps&&f.componentWillReceiveProps(b,c);e=this._processPendingState(b,c);this._pendingForceUpdate||!f.shouldComponentUpdate||f.shouldComponentUpdate(b,e,c)?(this._pendingForceUpdate=!1,this._performComponentUpdate(d,b,e,c,a,g)):(this._currentElement= d,this._context=g,f.props=b,f.state=e,f.context=c)},_processPendingState:function(a,b){var d=this._instance,g=this._pendingStateQueue,e=this._pendingReplaceState;this._pendingReplaceState=!1;this._pendingStateQueue=null;if(!g)return d.state;if(e&&1===g.length)return g[0];for(var c=f({},e?g[0]:d.state),e=e?1:0;e<g.length;e++){var h=g[e];f(c,"function"===typeof h?h.call(d,c,a,b):h)}return c},_performComponentUpdate:function(a,b,d,f,g,e){var c=this._instance,h=Boolean(c.componentDidUpdate),k,p,l;h&& (k=c.props,p=c.state,l=c.context);c.componentWillUpdate&&c.componentWillUpdate(b,d,f);this._currentElement=a;this._context=e;c.props=b;c.state=d;c.context=f;this._updateRenderedComponent(g,e);h&&g.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,k,p,l),c)},_updateRenderedComponent:function(a,b){var d=this._renderedComponent,f=d._currentElement,g=this._renderValidatedComponent();t(f,g)?n.receiveComponent(d,g,a,this._processChildContext(b)):(f=n.getNativeNode(d),n.unmountComponent(d,!1),this._renderedNodeType= m.getType(g),this._renderedComponent=this._instantiateReactComponent(g),d=n.mountComponent(this._renderedComponent,a,this._nativeParent,this._nativeContainerInfo,this._processChildContext(b)),this._replaceNodeWithMarkup(f,d))},_replaceNodeWithMarkup:function(a,b){d.replaceNodeWithMarkup(a,b)},_renderValidatedComponentWithoutOwnerOrContext:function(){return this._instance.render()},_renderValidatedComponent:function(){var a;g.current=this;try{a=this._renderValidatedComponentWithoutOwnerOrContext()}finally{g.current= null}!(null===a||!1===a||h.isValidElement(a))?r(!1):void 0;return a},attachRef:function(a,b){var d=this.getPublicInstance();null==d?r(!1):void 0;var f=b.getPublicInstance();(d.refs===q?d.refs={}:d.refs)[a]=f},detachRef:function(a){delete this.getPublicInstance().refs[a]},getName:function(){var a=this._currentElement.type,b=this._instance&&this._instance.constructor;return a.displayName||b&&b.displayName||a.name||b&&b.name||null},getPublicInstance:function(){var a=this._instance;return a instanceof e?null:a},_instantiateReactComponent:null};b.measureMethods(a,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});c.exports={Mixin:a}},function(c,b){var a={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0};c.exports={getNativeProps:function(b,f){if(!f.disabled)return f;var d= {},g;for(g in f)f.hasOwnProperty(g)&&!a[g]&&(d[g]=f[g]);return d}}},function(c,b,a){function e(a,b){b&&(W[a._tag]&&(!(null==b.children&&null==b.dangerouslySetInnerHTML)?F(!1):void 0),null!=b.dangerouslySetInnerHTML&&(null!=b.children?F(!1):void 0,!("object"===typeof b.dangerouslySetInnerHTML&&U in b.dangerouslySetInnerHTML)?F(!1):void 0),null==b.style||"object"===typeof b.style?void 0:F(!1))}function f(a,b,f,g){var e=a._nativeContainerInfo._ownerDocument;e&&(S(b,e),g.getReactMountReady().enqueue(d, {inst:a,registrationName:b,listener:f}))}function d(){v.putListener(this.inst,this.registrationName,this.listener)}function g(){C.postMountWrapper(this)}function h(){!this._rootNodeID?F(!1):void 0;var a=H(this);!a?F(!1):void 0;switch(this._tag){case "iframe":case "object":this._wrapperState.listeners=[x.trapBubbledEvent(u.topLevelTypes.topLoad,"load",a)];break;case "video":case "audio":this._wrapperState.listeners=[];for(var b in R)R.hasOwnProperty(b)&&this._wrapperState.listeners.push(x.trapBubbledEvent(u.topLevelTypes[b], R[b],a));break;case "img":this._wrapperState.listeners=[x.trapBubbledEvent(u.topLevelTypes.topError,"error",a),x.trapBubbledEvent(u.topLevelTypes.topLoad,"load",a)];break;case "form":this._wrapperState.listeners=[x.trapBubbledEvent(u.topLevelTypes.topReset,"reset",a),x.trapBubbledEvent(u.topLevelTypes.topSubmit,"submit",a)];break;case "input":case "select":case "textarea":this._wrapperState.listeners=[x.trapBubbledEvent(u.topLevelTypes.topInvalid,"invalid",a)]}}function k(){I.postUpdateWrapper(this)} function l(a){var b=a.type;Y.call(X,b)||(!P.test(b)?F(!1):void 0,X[b]=!0);this._currentElement=a;this._tag=b.toLowerCase();this._topLevelWrapper=this._wrapperState=this._nativeContainerInfo=this._domID=this._rootNodeID=this._nativeParent=this._nativeNode=this._previousStyleCopy=this._previousStyle=this._renderedChildren=this._namespaceURI=null;this._flags=0}var m=a(14),n=a(354),s=a(356),q=a(58),r=a(358),t=a(53),p=a(105),u=a(42),v=a(66);b=a(79);var x=a(80),w=a(191),y=a(366),B=a(192),A=a(17),z=a(374), C=a(376),I=a(193),O=a(379),N=a(390),D=a(30),L=a(85),F=a(10);a(118);var K=a(48);a(130);a(122);a(12);var T=v.deleteListener,H=A.getNodeFromInstance,S=x.listenTo,Q=b.registrationNameModules,J={string:!0,number:!0},E=K({style:null}),U=K({__html:null}),M={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},R={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"},G={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},V={listing:!0, pre:!0,textarea:!0},W=m({menuitem:!0},G),P=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,X={},Y={}.hasOwnProperty,Z=1;l.displayName="ReactDOMComponent";l.Mixin={mountComponent:function(a,b,d,f){this._rootNodeID=Z++;this._domID=d._idCounter++;this._nativeParent=b;this._nativeContainerInfo=d;var c=this._currentElement.props;switch(this._tag){case "iframe":case "object":case "img":case "form":case "video":case "audio":this._wrapperState={listeners:null};a.getReactMountReady().enqueue(h,this);break;case "button":c=y.getNativeProps(this, c,b);break;case "input":z.mountWrapper(this,c,b);c=z.getNativeProps(this,c);a.getReactMountReady().enqueue(h,this);break;case "option":C.mountWrapper(this,c,b);c=C.getNativeProps(this,c);break;case "select":I.mountWrapper(this,c,b);c=I.getNativeProps(this,c);a.getReactMountReady().enqueue(h,this);break;case "textarea":O.mountWrapper(this,c,b),c=O.getNativeProps(this,c),a.getReactMountReady().enqueue(h,this)}e(this,c);var k,l;null!=b?(k=b._namespaceURI,l=b._tag):d._tag&&(k=d._namespaceURI,l=d._tag); if(null==k||k===r.svg&&"foreignobject"===l)k=r.html;k===r.html&&("svg"===this._tag?k=r.svg:"math"===this._tag&&(k=r.mathml));this._namespaceURI=k;a.useCreateElement?(b=d._ownerDocument,k===r.html?"script"===this._tag?(k=b.createElement("div"),b=this._currentElement.type,k.innerHTML="<"+b+"></"+b+">",k=k.removeChild(k.firstChild)):k=b.createElement(this._currentElement.type):k=b.createElementNS(k,this._currentElement.type),A.precacheNode(this,k),this._flags|=B.hasCachedChildNodes,this._nativeParent|| p.setAttributeForRoot(k),this._updateDOMProperties(null,c,a),k=q(k),this._createInitialChildren(a,c,f,k),f=k):(k=this._createOpenTagMarkupAndPutListeners(a,c),f=this._createContentMarkup(a,c,f),f=!f&&G[this._tag]?k+"/>":k+">"+f+"</"+this._currentElement.type+">");switch(this._tag){case "button":case "input":case "select":case "textarea":c.autoFocus&&a.getReactMountReady().enqueue(n.focusDOMComponent,this);break;case "option":a.getReactMountReady().enqueue(g,this)}return f},_createOpenTagMarkupAndPutListeners:function(a, b){var d="<"+this._currentElement.type,g;for(g in b)if(b.hasOwnProperty(g)){var e=b[g];if(null!=e)if(Q.hasOwnProperty(g))e&&f(this,g,e,a);else{g===E&&(e&&(e=this._previousStyleCopy=m({},b.style)),e=s.createMarkupForStyles(e,this));var c=null;null!=this._tag&&(0<=this._tag.indexOf("-")||null!=b.is)?M.hasOwnProperty(g)||(c=p.createMarkupForCustomAttribute(g,e)):c=p.createMarkupForProperty(g,e);c&&(d+=" "+c)}}if(a.renderToStaticMarkup)return d;this._nativeParent||(d+=" "+p.createMarkupForRoot());return d+= " "+p.createMarkupForID(this._domID)},_createContentMarkup:function(a,b,d){var f="",g=b.dangerouslySetInnerHTML;null!=g?null!=g.__html&&(f=g.__html):(g=J[typeof b.children]?b.children:null,b=null!=g?null:b.children,null!=g?f=L(g):null!=b&&(f=this.mountChildren(b,a,d).join("")));return V[this._tag]&&"\n"===f.charAt(0)?"\n"+f:f},_createInitialChildren:function(a,b,d,f){var g=b.dangerouslySetInnerHTML;if(null!=g)null!=g.__html&&q.queueHTML(f,g.__html);else if(g=J[typeof b.children]?b.children:null,b= null!=g?null:b.children,null!=g)q.queueText(f,g);else if(null!=b){a=this.mountChildren(b,a,d);for(d=0;d<a.length;d++)q.queueChild(f,a[d])}},receiveComponent:function(a,b,d){var f=this._currentElement;this._currentElement=a;this.updateComponent(b,f,a,d)},updateComponent:function(a,b,d,f){b=b.props;d=this._currentElement.props;switch(this._tag){case "button":b=y.getNativeProps(this,b);d=y.getNativeProps(this,d);break;case "input":z.updateWrapper(this);b=z.getNativeProps(this,b);d=z.getNativeProps(this, d);break;case "option":b=C.getNativeProps(this,b);d=C.getNativeProps(this,d);break;case "select":b=I.getNativeProps(this,b);d=I.getNativeProps(this,d);break;case "textarea":O.updateWrapper(this),b=O.getNativeProps(this,b),d=O.getNativeProps(this,d)}e(this,d);this._updateDOMProperties(b,d,a);this._updateDOMChildren(b,d,a,f);"select"===this._tag&&a.getReactMountReady().enqueue(k,this)},_updateDOMProperties:function(a,b,d){var g,e,c;for(g in a)if(!b.hasOwnProperty(g)&&a.hasOwnProperty(g)&&null!=a[g])if(g=== E){var h=this._previousStyleCopy;for(e in h)h.hasOwnProperty(e)&&(c=c||{},c[e]="");this._previousStyleCopy=null}else Q.hasOwnProperty(g)?a[g]&&T(this,g):(t.properties[g]||t.isCustomAttribute(g))&&p.deleteValueForProperty(H(this),g);for(g in b){var h=b[g],k=g===E?this._previousStyleCopy:null!=a?a[g]:void 0;if(b.hasOwnProperty(g)&&!(h===k||null==h&&null==k))if(g===E)if(h?h=this._previousStyleCopy=m({},h):this._previousStyleCopy=null,k){for(e in k)if(k.hasOwnProperty(e)&&(!h||!h.hasOwnProperty(e)))c= c||{},c[e]="";for(e in h)h.hasOwnProperty(e)&&k[e]!==h[e]&&(c=c||{},c[e]=h[e])}else c=h;else if(Q.hasOwnProperty(g))h?f(this,g,h,d):k&&T(this,g);else if(0<=this._tag.indexOf("-")||null!=b.is)M.hasOwnProperty(g)||p.setValueForAttribute(H(this),g,h);else if(t.properties[g]||t.isCustomAttribute(g))k=H(this),null!=h?p.setValueForProperty(k,g,h):p.deleteValueForProperty(k,g)}c&&s.setValueForStyles(H(this),c,this)},_updateDOMChildren:function(a,b,d,f){var g=J[typeof a.children]?a.children:null,e=J[typeof b.children]? b.children:null,c=a.dangerouslySetInnerHTML&&a.dangerouslySetInnerHTML.__html,h=b.dangerouslySetInnerHTML&&b.dangerouslySetInnerHTML.__html;b=null!=e?null:b.children;var k=null!=g||null!=c,p=null!=e||null!=h;null!=(null!=g?null:a.children)&&null==b?this.updateChildren(null,d,f):k&&!p&&this.updateTextContent("");null!=e?g!==e&&this.updateTextContent(""+e):null!=h?c!==h&&this.updateMarkup(""+h):null!=b&&this.updateChildren(b,d,f)},getNativeNode:function(){return H(this)},unmountComponent:function(a){switch(this._tag){case "iframe":case "object":case "img":case "form":case "video":case "audio":var b= this._wrapperState.listeners;if(b)for(var d=0;d<b.length;d++)b[d].remove();break;case "html":case "head":case "body":F(!1)}this.unmountChildren(a);A.uncacheNode(this);v.deleteAllListeners(this);w.unmountIDFromEnvironment(this._rootNodeID);this._wrapperState=this._domID=this._rootNodeID=null},getPublicInstance:function(){return H(this)}};D.measureMethods(l.Mixin,"ReactDOMComponent",{mountComponent:"mountComponent",receiveComponent:"receiveComponent"});m(l.prototype,l.Mixin,N.Mixin);c.exports=l},function(c, b,a){a(122);c.exports=function(a,b){return{_topLevelWrapper:a,_idCounter:1,_ownerDocument:b?9===b.nodeType?b:b.ownerDocument:null,_tag:b?b.nodeName.toLowerCase():null,_namespaceURI:b?b.namespaceURI:null}}},function(c,b,a){b=a(381);a(12);var e=[];a={addDevtool:function(a){e.push(a)},removeDevtool:function(a){for(var b=0;b<e.length;b++)e[b]===a&&(e.splice(b,1),b--)},onCreateMarkupForProperty:function(a,b){},onSetValueForProperty:function(a,b,g){},onDeleteValueForProperty:function(a,b){}};a.addDevtool(b); c.exports=a},function(c,b,a){b=a(14);var e=a(58),f=a(17);a=function(a){this._domID=this._nativeContainerInfo=this._nativeParent=this._nativeNode=this._currentElement=null};b(a.prototype,{mountComponent:function(a,b,c,k){this._domID=c._idCounter++;this._nativeParent=b;this._nativeContainerInfo=c;b=" react-empty: "+this._domID+" ";return a.useCreateElement?(a=c._ownerDocument.createComment(b),f.precacheNode(this,a),e(a)):a.renderToStaticMarkup?"":"\x3c!--"+b+"--\x3e"},receiveComponent:function(){}, getNativeNode:function(){return f.getNodeFromInstance(this)},unmountComponent:function(){f.uncacheNode(this)}});c.exports=a},function(c,b,a){var e=a(34);a(194);b=a(424)({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del", details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta", meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time", title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},function(a){return e.createFactory(a)});c.exports=b},function(c,b){c.exports={useCreateElement:!0}},function(c,b, a){var e=a(104),f=a(17);b={dangerouslyProcessChildrenUpdates:function(a,b){var c=f.getNodeFromInstance(a);e.processUpdates(c,b)}};a(30).measureMethods(b,"ReactDOMIDOperations",{dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"});c.exports=b},function(c,b,a){function e(){this._rootNodeID&&n.updateWrapper(this)}function f(a){var b=this._currentElement.props;a=h.executeOnChange(b,a);l.asap(e,this);var d=b.name;if("radio"===b.type&&null!=d){for(var f=b=k.getNodeFromInstance(this);f.parentNode;)f= f.parentNode;d=f.querySelectorAll("input[name="+JSON.stringify(""+d)+'][type="radio"]');for(f=0;f<d.length;f++){var g=d[f];g===b||g.form!==b.form||(g=k.getInstanceFromNode(g),!g?m(!1):void 0,l.asap(e,g))}}return a}var d=a(14),g=a(105),h=a(107),k=a(17),l=a(35),m=a(10);a(12);var n={getNativeProps:function(a,b){var f=h.getValue(b),g=h.getChecked(b);return d({type:void 0},b,{defaultChecked:void 0,defaultValue:void 0,value:null!=f?f:a._wrapperState.initialValue,checked:null!=g?g:a._wrapperState.initialChecked, onChange:a._wrapperState.onChange})},mountWrapper:function(a,b){var d=b.defaultValue;a._wrapperState={initialChecked:b.defaultChecked||!1,initialValue:null!=d?d:null,listeners:null,onChange:f.bind(a)}},updateWrapper:function(a){var b=a._currentElement.props,d=b.checked;null!=d&&g.setValueForProperty(k.getNodeFromInstance(a),"checked",d||!1);b=h.getValue(b);null!=b&&g.setValueForProperty(k.getNodeFromInstance(a),"value",""+b)}};c.exports=n},function(c,b,a){b=a(369);c.exports={debugTool:b}},function(c, b,a){var e=a(14),f=a(188),d=a(17),g=a(193);a(12);c.exports={mountWrapper:function(a,b,d){var f=null;null!=d&&"select"===d._tag&&(f=g.getSelectValueContext(d));d=null;if(null!=f)if(d=!1,Array.isArray(f))for(var e=0;e<f.length;e++){if(""+f[e]===""+b.value){d=!0;break}}else d=""+f===""+b.value;a._wrapperState={selected:d}},postMountWrapper:function(a){var b=a._currentElement.props;null!=b.value&&d.getNodeFromInstance(a).setAttribute("value",b.value)},getNativeProps:function(a,b){var d=e({selected:void 0, children:void 0},b);null!=a._wrapperState.selected&&(d.selected=a._wrapperState.selected);var g="";f.forEach(b.children,function(a){null!=a&&("string"===typeof a||"number"===typeof a?g+=a:void 0)});g&&(d.children=g);return d}}},function(c,b,a){function e(a){var b=document.selection.createRange(),d=b.text.length,f=b.duplicate();f.moveToElementText(a);f.setEndPoint("EndToStart",b);a=f.text.length;return{start:a,end:a+d}}function f(a){var b=window.getSelection&&window.getSelection();if(!b||0===b.rangeCount)return null; var d=b.anchorNode,f=b.anchorOffset,g=b.focusNode,e=b.focusOffset,c=b.getRangeAt(0);try{c.startContainer.nodeType,c.endContainer.nodeType}catch(h){return null}var b=b.anchorNode===b.focusNode&&b.anchorOffset===b.focusOffset?0:c.toString().length,k=c.cloneRange();k.selectNodeContents(a);k.setEnd(c.startContainer,c.startOffset);a=k.startContainer===k.endContainer&&k.startOffset===k.endOffset?0:k.toString().length;c=a+b;b=document.createRange();b.setStart(d,f);b.setEnd(g,e);d=b.collapsed;return{start:d? c:a,end:d?a:c}}function d(a,b){var d=document.selection.createRange().duplicate(),f,g;void 0===b.end?g=f=b.start:b.start>b.end?(f=b.end,g=b.start):(f=b.start,g=b.end);d.moveToElementText(a);d.moveStart("character",f);d.setEndPoint("EndToStart",d);d.moveEnd("character",g-f);d.select()}function g(a,b){if(window.getSelection){var d=window.getSelection(),f=a[k()].length,g=Math.min(b.start,f),f=void 0===b.end?g:Math.min(b.end,f);if(!d.extend&&g>f)var e=f,f=g,g=e;var e=h(a,g),c=h(a,f);if(e&&c){var p=document.createRange(); p.setStart(e.node,e.offset);d.removeAllRanges();g>f?(d.addRange(p),d.extend(c.node,c.offset)):(p.setEnd(c.node,c.offset),d.addRange(p))}}}b=a(22);var h=a(411),k=a(210);a=b.canUseDOM&&"selection"in document&&!("getSelection"in window);c.exports={getOffsets:a?e:f,setOffsets:a?d:g}},function(c,b,a){b=a(14);var e=a(104),f=a(58),d=a(17),g=a(30),h=a(85),k=a(10);a(122);a=function(a){this._currentElement=a;this._stringText=""+a;this._domID=this._nativeParent=this._nativeNode=null;this._mountIndex=0;this._commentNodes= this._closingComment=null};b(a.prototype,{mountComponent:function(a,b,g,e){var c=g._idCounter++;e=" react-text: "+c+" ";this._domID=c;this._nativeParent=b;if(a.useCreateElement)return a=g._ownerDocument,e=a.createComment(e),b=a.createComment(" /react-text "),g=f(a.createDocumentFragment()),f.queueChild(g,f(e)),this._stringText&&f.queueChild(g,f(a.createTextNode(this._stringText))),f.queueChild(g,f(b)),d.precacheNode(this,e),this._closingComment=b,g;b=h(this._stringText);return a.renderToStaticMarkup? b:"\x3c!--"+e+"--\x3e"+b+"\x3c!-- /react-text --\x3e"},receiveComponent:function(a,b){if(a!==this._currentElement){this._currentElement=a;var d=""+a;if(d!==this._stringText){this._stringText=d;var f=this.getNativeNode();e.replaceDelimitedText(f[0],f[1],d)}}},getNativeNode:function(){var a=this._commentNodes;if(a)return a;if(!this._closingComment)for(a=d.getNodeFromInstance(this).nextSibling;;){null==a?k(!1):void 0;if(8===a.nodeType&&" /react-text "===a.nodeValue){this._closingComment=a;break}a=a.nextSibling}return this._commentNodes= a=[this._nativeNode,this._closingComment]},unmountComponent:function(){this._commentNodes=this._closingComment=null;d.uncacheNode(this)}});g.measureMethods(a.prototype,"ReactDOMTextComponent",{mountComponent:"mountComponent",receiveComponent:"receiveComponent"});c.exports=a},function(c,b,a){function e(){this._rootNodeID&&n.updateWrapper(this)}function f(a){a=h.executeOnChange(this._currentElement.props,a);l.asap(e,this);return a}var d=a(14),g=a(105),h=a(107),k=a(17),l=a(35),m=a(10);a(12);var n={getNativeProps:function(a, b){null!=b.dangerouslySetInnerHTML?m(!1):void 0;return d({},b,{defaultValue:void 0,value:void 0,children:a._wrapperState.initialValue,onChange:a._wrapperState.onChange})},mountWrapper:function(a,b){var d=b.defaultValue,g=b.children;null!=g&&(null!=d?m(!1):void 0,Array.isArray(g)&&(!(1>=g.length)?m(!1):void 0,g=g[0]),d=""+g);null==d&&(d="");g=h.getValue(b);a._wrapperState={initialValue:""+(null!=g?g:d),listeners:null,onChange:f.bind(a)}},updateWrapper:function(a){var b=h.getValue(a._currentElement.props); null!=b&&g.setValueForProperty(k.getNodeFromInstance(a),"value",""+b)}};c.exports=n},function(c,b,a){function e(a,b){!("_nativeNode"in a)?f(!1):void 0;!("_nativeNode"in b)?f(!1):void 0;for(var e=0,c=a;c;c=c._nativeParent)e++;for(var c=0,l=b;l;l=l._nativeParent)c++;for(;0<e-c;)a=a._nativeParent,e--;for(;0<c-e;)b=b._nativeParent,c--;for(;e--;){if(a===b)return a;a=a._nativeParent;b=b._nativeParent}return null}var f=a(10);c.exports={isAncestor:function(a,b){!("_nativeNode"in a)?f(!1):void 0;!("_nativeNode"in b)?f(!1):void 0;for(;b;){if(b===a)return!0;b=b._nativeParent}return!1},getLowestCommonAncestor:e,getParentInstance:function(a){!("_nativeNode"in a)?f(!1):void 0;return a._nativeParent},traverseTwoPhase:function(a,b,f){for(var e=[];a;)e.push(a),a=a._nativeParent;for(a=e.length;0<a--;)b(e[a],!1,f);for(a=0;a<e.length;a++)b(e[a],!0,f)},traverseEnterLeave:function(a,b,f,c,l){for(var m=a&&b?e(a,b):null,n=[];a&&a!==m;)n.push(a),a=a._nativeParent;for(a=[];b&&b!==m;)a.push(b),b=b._nativeParent;for(b=0;b<n.length;b++)f(n[b], !0,c);for(b=a.length;0<b--;)f(a[b],!1,l)}}},function(c,b,a){a(53);a(79);a(12);c.exports={onCreateMarkupForProperty:function(a,b){(void 0)(a)},onSetValueForProperty:function(a,b,d){(void 0)(b)},onDeleteValueForProperty:function(a,b){(void 0)(b)}}},function(c,b,a){b=a(388);a(12);var e=[];a={addDevtool:function(a){e.push(a)},removeDevtool:function(a){for(var b=0;b<e.length;b++)e[b]===a&&(e.splice(b,1),b--)},onBeginProcessingChildContext:function(){},onEndProcessingChildContext:function(){},onSetState:function(){}, onMountRootComponent:function(a){},onMountComponent:function(a){},onUpdateComponent:function(a){},onUnmountComponent:function(a){}};a.addDevtool(b);c.exports=a},function(c,b,a){function e(){this.reinitializeTransaction()}b=a(14);var f=a(35),d=a(111);a=a(40);var g={initialize:a,close:function(){l.isBatchingUpdates=!1}},h=[{initialize:a,close:f.flushBatchedUpdates.bind(f)},g];b(e.prototype,d.Mixin,{getTransactionWrappers:function(){return h}});var k=new e,l={isBatchingUpdates:!1,batchedUpdates:function(a, b,d,f,g,e){var c=l.isBatchingUpdates;l.isBatchingUpdates=!0;c?a(b,d,f,g,e):k.perform(a,null,b,d,f,g,e)}};c.exports=l},function(c,b,a){var e=a(355),f=a(357),d=a(360),g=a(361);a(22);var h=a(363),k=a(191),l=a(367),m=a(17),n=a(370),s=a(380),q=a(378),r=a(383),t=a(386),p=a(387),u=a(392),v=a(394),x=a(395),w=a(396),y=!1;c.exports={inject:function(){y||(y=!0,p.EventEmitter.injectReactEventListener(t),p.EventPluginHub.injectEventPluginOrder(d),p.EventPluginUtils.injectComponentTree(m),p.EventPluginUtils.injectTreeTraversal(s), p.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:w,EnterLeaveEventPlugin:g,ChangeEventPlugin:f,SelectEventPlugin:x,BeforeInputEventPlugin:e}),p.NativeComponent.injectGenericComponentClass(l),p.NativeComponent.injectTextComponentClass(q),p.DOMProperty.injectDOMPropertyConfig(h),p.DOMProperty.injectDOMPropertyConfig(v),p.EmptyComponent.injectEmptyComponentFactory(function(a){return new n(a)}),p.Updates.injectReconcileTransaction(u),p.Updates.injectBatchingStrategy(r),p.Component.injectEnvironment(k))}}}, function(c,b,a){var e=a(66);c.exports={handleTopLevel:function(a,b,g,c){a=e.extractEvents(a,b,g,c);e.enqueueEvents(a);e.processEventQueue(!1)}}},function(c,b,a){function e(a,b){this.topLevelType=a;this.nativeEvent=b;this.ancestors=[]}function f(a){var b=n(a.nativeEvent),b=l.getClosestInstanceFromNode(b);do{a.ancestors.push(b);var d;if(d=b){for(;b._nativeParent;)b=b._nativeParent;b=l.getNodeFromInstance(b).parentNode;d=l.getClosestInstanceFromNode(b)}b=d}while(b);for(d=0;d<a.ancestors.length;d++)b= a.ancestors[d],q._handleTopLevel(a.topLevelType,b,a.nativeEvent,n(a.nativeEvent))}function d(a){var b=s(window);a(b)}b=a(14);var g=a(214),h=a(22),k=a(54),l=a(17),m=a(35),n=a(116),s=a(419);b(e.prototype,{destructor:function(){this.nativeEvent=this.topLevelType=null;this.ancestors.length=0}});k.addPoolingTo(e,k.twoArgumentPooler);var q={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:h.canUseDOM?window:null,setHandleTopLevel:function(a){q._handleTopLevel=a},setEnabled:function(a){q._enabled=!!a},isEnabled:function(){return q._enabled}, trapBubbledEvent:function(a,b,d){return!d?null:g.listen(d,b,q.dispatchEvent.bind(null,a))},trapCapturedEvent:function(a,b,d){return!d?null:g.capture(d,b,q.dispatchEvent.bind(null,a))},monitorScrollValue:function(a){a=d.bind(null,a);g.listen(window,"scroll",a)},dispatchEvent:function(a,b){if(q._enabled){var d=e.getPooled(a,b);try{m.batchedUpdates(f,d)}finally{e.release(d)}}}};c.exports=q},function(c,b,a){b=a(53);var e=a(66),f=a(106),d=a(108),g=a(189),h=a(195),k=a(80),l=a(200),m=a(30);a=a(35);c.exports= {Component:d.injection,Class:g.injection,DOMProperty:b.injection,EmptyComponent:h.injection,EventPluginHub:e.injection,EventPluginUtils:f.injection,EventEmitter:k.injection,NativeComponent:l.injection,Perf:m.injection,Updates:a.injection}},function(c,b,a){var e,f=a(12);c.exports={onBeginProcessingChildContext:function(){e=!0},onEndProcessingChildContext:function(){e=!1},onSetState:function(){"production"!==process.env.NODE_ENV?f(!e,"setState(...): Cannot call setState() inside getChildContext()"): void 0}}},function(c,b,a){var e=a(407),f=/\/?>/,d=/^<\!\-\-/,g={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(a){var b=e(a);return d.test(a)?a:a.replace(f," "+g.CHECKSUM_ATTR_NAME+'="'+b+'"$&')},canReuseMarkup:function(a,b){var d=b.getAttribute(g.CHECKSUM_ATTR_NAME),d=d&&parseInt(d,10);return e(a)===d}};c.exports=g},function(c,b,a){function e(a,b){b&&(a=a||[],a.push(b));return a}var f=a(108),d=a(199);a(47);var g=a(59),h=a(364),k=a(330),l=a(10);c.exports={Mixin:{_reconcilerInstantiateChildren:function(a, b,d){return h.instantiateChildren(a,b,d)},_reconcilerUpdateChildren:function(a,b,d,f,g){b=k(b);h.updateChildren(a,b,d,f,g);return b},mountChildren:function(a,b,d){this._renderedChildren=a=this._reconcilerInstantiateChildren(a,b,d);var f=[],e=0,c;for(c in a)if(a.hasOwnProperty(c)){var h=a[c],k=g.mountComponent(h,b,this,this._nativeContainerInfo,d);h._mountIndex=e++;f.push(k)}return f},updateTextContent:function(a){var b=this._renderedChildren;h.unmountChildren(b,!1);for(var g in b)b.hasOwnProperty(g)&& l(!1);f.processChildrenUpdates(this,[{type:d.TEXT_CONTENT,content:a,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}])},updateMarkup:function(a){var b=this._renderedChildren;h.unmountChildren(b,!1);for(var g in b)b.hasOwnProperty(g)&&l(!1);f.processChildrenUpdates(this,[{type:d.SET_MARKUP,content:a,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}])},updateChildren:function(a,b,d){this._updateChildren(a,b,d)},_updateChildren:function(a,b,d){var c=this._renderedChildren,h={};if((a= this._reconcilerUpdateChildren(c,a,h,b,d))||c){var k=null,p,l=0,v=0,x=null;for(p in a)if(a.hasOwnProperty(p)){var w=c&&c[p],y=a[p];w===y?(k=e(k,this.moveChild(w,x,v,l)),l=Math.max(w._mountIndex,l),w._mountIndex=v):(w&&(l=Math.max(w._mountIndex,l)),k=e(k,this._mountChildAtIndex(y,x,v,b,d)));v++;x=g.getNativeNode(y)}for(p in h)h.hasOwnProperty(p)&&(k=e(k,this._unmountChild(c[p],h[p])));k&&f.processChildrenUpdates(this,k);this._renderedChildren=a}},unmountChildren:function(a){h.unmountChildren(this._renderedChildren, a);this._renderedChildren=null},moveChild:function(a,b,f,e){if(a._mountIndex<e)return{type:d.MOVE_EXISTING,content:null,fromIndex:a._mountIndex,fromNode:g.getNativeNode(a),toIndex:f,afterNode:b}},createChild:function(a,b,f){return{type:d.INSERT_MARKUP,content:f,fromIndex:null,fromNode:null,toIndex:a._mountIndex,afterNode:b}},removeChild:function(a,b){return{type:d.REMOVE_NODE,content:null,fromIndex:a._mountIndex,fromNode:b,toIndex:null,afterNode:null}},_mountChildAtIndex:function(a,b,d,f,e){f=g.mountComponent(a, f,this,this._nativeContainerInfo,e);a._mountIndex=d;return this.createChild(a,b,f)},_unmountChild:function(a,b){var d=this.removeChild(a,b);a._mountIndex=null;return d}}}},function(c,b,a){var e=a(10),f={isValidOwner:function(a){return!(!a||!("function"===typeof a.attachRef&&"function"===typeof a.detachRef))},addComponentAsRefTo:function(a,b,c){!f.isValidOwner(c)?e(!1):void 0;c.attachRef(b,a)},removeComponentAsRefFrom:function(a,b,c){!f.isValidOwner(c)?e(!1):void 0;var k=c.getPublicInstance();k&&k.refs[b]=== a.getPublicInstance()&&c.detachRef(b)}};c.exports=f},function(c,b,a){function e(a){this.reinitializeTransaction();this.renderToStaticMarkup=!1;this.reactMountReady=f.getPooled(null);this.useCreateElement=a}b=a(14);var f=a(187),d=a(54),g=a(80),h=a(197);a=a(111);var k=[{initialize:h.getSelectionInformation,close:h.restoreSelection},{initialize:function(){var a=g.isEnabled();g.setEnabled(!1);return a},close:function(a){g.setEnabled(a)}},{initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}}]; b(e.prototype,a.Mixin,{getTransactionWrappers:function(){return k},getReactMountReady:function(){return this.reactMountReady},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(a){this.reactMountReady.rollback(a)},destructor:function(){f.release(this.reactMountReady);this.reactMountReady=null}});d.addPoolingTo(e);c.exports=e},function(c,b,a){var e=a(391);c.exports={attachRefs:function(a,b){if(!(null===b||!1===b)){var g=b.ref;if(null!=g){var c=b._owner;"function"===typeof g? g(a.getPublicInstance()):e.addComponentAsRefTo(a,g,c)}}},shouldUpdateRefs:function(a,b){return null===a||!1===a||null===b||!1===b||b._owner!==a._owner||b.ref!==a.ref},detachRefs:function(a,b){if(!(null===b||!1===b)){var g=b.ref;if(null!=g){var c=b._owner;"function"===typeof g?g(null):e.removeComponentAsRefFrom(a,g,c)}}}}},function(c,b){var a={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",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},e={Properties:{},DOMAttributeNamespaces:{xlinkActuate:"http://www.w3.org/1999/xlink",xlinkArcrole:"http://www.w3.org/1999/xlink",xlinkHref:"http://www.w3.org/1999/xlink",xlinkRole:"http://www.w3.org/1999/xlink",xlinkShow:"http://www.w3.org/1999/xlink",xlinkTitle:"http://www.w3.org/1999/xlink",xlinkType:"http://www.w3.org/1999/xlink",xmlBase:"http://www.w3.org/XML/1998/namespace", xmlLang:"http://www.w3.org/XML/1998/namespace",xmlSpace:"http://www.w3.org/XML/1998/namespace"},DOMAttributeNames:{}};Object.keys(a).map(function(b){e.Properties[b]=0;a[b]&&(e.DOMAttributeNames[b]=a[b])});c.exports=e},function(c,b,a){function e(a,b){if(x||null==p||p!==l())return null;var d;d=p;"selectionStart"in d&&h.hasSelectionCapabilities(d)?d={start:d.selectionStart,end:d.selectionEnd}:window.getSelection?(d=window.getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode, focusOffset:d.focusOffset}):document.selection?(d=document.selection.createRange(),d={parentElement:d.parentElement(),text:d.text,top:d.boundingTop,left:d.boundingLeft}):d=void 0;return!v||!s(v,d)?(v=d,d=k.getPooled(t.select,u,a,b),d.type="select",d.target=p,f.accumulateTwoPhaseDispatches(d),d):null}b=a(42);var f=a(67),d=a(22),g=a(17),h=a(197),k=a(43),l=a(216),m=a(212),n=a(48),s=a(130),q=b.topLevelTypes,r=d.canUseDOM&&"documentMode"in document&&11>=document.documentMode,t={select:{phasedRegistrationNames:{bubbled:n({onSelect:null}), captured:n({onSelectCapture:null})},dependencies:[q.topBlur,q.topContextMenu,q.topFocus,q.topKeyDown,q.topMouseDown,q.topMouseUp,q.topSelectionChange]}},p=null,u=null,v=null,x=!1,w=!1,y=n({onSelect:null});c.exports={eventTypes:t,extractEvents:function(a,b,d,f){if(!w)return null;var c=b?g.getNodeFromInstance(b):window;switch(a){case q.topFocus:if(m(c)||"true"===c.contentEditable)p=c,u=b,v=null;break;case q.topBlur:v=u=p=null;break;case q.topMouseDown:x=!0;break;case q.topContextMenu:case q.topMouseUp:return x= !1,e(d,f);case q.topSelectionChange:if(r)break;case q.topKeyDown:case q.topKeyUp:return e(d,f)}return null},didPutListener:function(a,b,d){b===y&&(w=!0)}}},function(c,b,a){b=a(42);var e=a(214),f=a(67),d=a(17),g=a(397),h=a(398),k=a(43),l=a(401),m=a(403),n=a(84),s=a(400),q=a(404),r=a(405),t=a(68),p=a(406),u=a(40),v=a(114),x=a(10);a=a(48);var w=b.topLevelTypes;b={abort:{phasedRegistrationNames:{bubbled:a({onAbort:!0}),captured:a({onAbortCapture:!0})}},animationEnd:{phasedRegistrationNames:{bubbled:a({onAnimationEnd:!0}), captured:a({onAnimationEndCapture:!0})}},animationIteration:{phasedRegistrationNames:{bubbled:a({onAnimationIteration:!0}),captured:a({onAnimationIterationCapture:!0})}},animationStart:{phasedRegistrationNames:{bubbled:a({onAnimationStart:!0}),captured:a({onAnimationStartCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:a({onBlur:!0}),captured:a({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:a({onCanPlay:!0}),captured:a({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:a({onCanPlayThrough:!0}), captured:a({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:a({onClick:!0}),captured:a({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:a({onContextMenu:!0}),captured:a({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:a({onCopy:!0}),captured:a({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:a({onCut:!0}),captured:a({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:a({onDoubleClick:!0}),captured:a({onDoubleClickCapture:!0})}}, drag:{phasedRegistrationNames:{bubbled:a({onDrag:!0}),captured:a({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:a({onDragEnd:!0}),captured:a({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:a({onDragEnter:!0}),captured:a({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:a({onDragExit:!0}),captured:a({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:a({onDragLeave:!0}),captured:a({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:a({onDragOver:!0}), captured:a({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:a({onDragStart:!0}),captured:a({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:a({onDrop:!0}),captured:a({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:a({onDurationChange:!0}),captured:a({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:a({onEmptied:!0}),captured:a({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:a({onEncrypted:!0}), captured:a({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:a({onEnded:!0}),captured:a({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:a({onError:!0}),captured:a({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:a({onFocus:!0}),captured:a({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:a({onInput:!0}),captured:a({onInputCapture:!0})}},invalid:{phasedRegistrationNames:{bubbled:a({onInvalid:!0}),captured:a({onInvalidCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:a({onKeyDown:!0}), captured:a({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:a({onKeyPress:!0}),captured:a({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:a({onKeyUp:!0}),captured:a({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:a({onLoad:!0}),captured:a({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:a({onLoadedData:!0}),captured:a({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:a({onLoadedMetadata:!0}),captured:a({onLoadedMetadataCapture:!0})}}, loadStart:{phasedRegistrationNames:{bubbled:a({onLoadStart:!0}),captured:a({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:a({onMouseDown:!0}),captured:a({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:a({onMouseMove:!0}),captured:a({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:a({onMouseOut:!0}),captured:a({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:a({onMouseOver:!0}),captured:a({onMouseOverCapture:!0})}}, mouseUp:{phasedRegistrationNames:{bubbled:a({onMouseUp:!0}),captured:a({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:a({onPaste:!0}),captured:a({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:a({onPause:!0}),captured:a({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:a({onPlay:!0}),captured:a({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:a({onPlaying:!0}),captured:a({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:a({onProgress:!0}), captured:a({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:a({onRateChange:!0}),captured:a({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:a({onReset:!0}),captured:a({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:a({onScroll:!0}),captured:a({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:a({onSeeked:!0}),captured:a({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:a({onSeeking:!0}),captured:a({onSeekingCapture:!0})}}, stalled:{phasedRegistrationNames:{bubbled:a({onStalled:!0}),captured:a({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:a({onSubmit:!0}),captured:a({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:a({onSuspend:!0}),captured:a({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:a({onTimeUpdate:!0}),captured:a({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:a({onTouchCancel:!0}),captured:a({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:a({onTouchEnd:!0}), captured:a({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:a({onTouchMove:!0}),captured:a({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:a({onTouchStart:!0}),captured:a({onTouchStartCapture:!0})}},transitionEnd:{phasedRegistrationNames:{bubbled:a({onTransitionEnd:!0}),captured:a({onTransitionEndCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:a({onVolumeChange:!0}),captured:a({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:a({onWaiting:!0}), captured:a({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:a({onWheel:!0}),captured:a({onWheelCapture:!0})}}};var y={topAbort:b.abort,topAnimationEnd:b.animationEnd,topAnimationIteration:b.animationIteration,topAnimationStart:b.animationStart,topBlur:b.blur,topCanPlay:b.canPlay,topCanPlayThrough:b.canPlayThrough,topClick:b.click,topContextMenu:b.contextMenu,topCopy:b.copy,topCut:b.cut,topDoubleClick:b.doubleClick,topDrag:b.drag,topDragEnd:b.dragEnd,topDragEnter:b.dragEnter,topDragExit:b.dragExit, topDragLeave:b.dragLeave,topDragOver:b.dragOver,topDragStart:b.dragStart,topDrop:b.drop,topDurationChange:b.durationChange,topEmptied:b.emptied,topEncrypted:b.encrypted,topEnded:b.ended,topError:b.error,topFocus:b.focus,topInput:b.input,topInvalid:b.invalid,topKeyDown:b.keyDown,topKeyPress:b.keyPress,topKeyUp:b.keyUp,topLoad:b.load,topLoadedData:b.loadedData,topLoadedMetadata:b.loadedMetadata,topLoadStart:b.loadStart,topMouseDown:b.mouseDown,topMouseMove:b.mouseMove,topMouseOut:b.mouseOut,topMouseOver:b.mouseOver, topMouseUp:b.mouseUp,topPaste:b.paste,topPause:b.pause,topPlay:b.play,topPlaying:b.playing,topProgress:b.progress,topRateChange:b.rateChange,topReset:b.reset,topScroll:b.scroll,topSeeked:b.seeked,topSeeking:b.seeking,topStalled:b.stalled,topSubmit:b.submit,topSuspend:b.suspend,topTimeUpdate:b.timeUpdate,topTouchCancel:b.touchCancel,topTouchEnd:b.touchEnd,topTouchMove:b.touchMove,topTouchStart:b.touchStart,topTransitionEnd:b.transitionEnd,topVolumeChange:b.volumeChange,topWaiting:b.waiting,topWheel:b.wheel}, B;for(B in y)y[B].dependencies=[B];var A=a({onClick:null}),z={};c.exports={eventTypes:b,extractEvents:function(a,b,d,e){var c=y[a];if(!c)return null;var u;switch(a){case w.topAbort:case w.topCanPlay:case w.topCanPlayThrough:case w.topDurationChange:case w.topEmptied:case w.topEncrypted:case w.topEnded:case w.topError:case w.topInput:case w.topInvalid:case w.topLoad:case w.topLoadedData:case w.topLoadedMetadata:case w.topLoadStart:case w.topPause:case w.topPlay:case w.topPlaying:case w.topProgress:case w.topRateChange:case w.topReset:case w.topSeeked:case w.topSeeking:case w.topStalled:case w.topSubmit:case w.topSuspend:case w.topTimeUpdate:case w.topVolumeChange:case w.topWaiting:u= k;break;case w.topKeyPress:if(0===v(d))return null;case w.topKeyDown:case w.topKeyUp:u=m;break;case w.topBlur:case w.topFocus:u=l;break;case w.topClick:if(2===d.button)return null;case w.topContextMenu:case w.topDoubleClick:case w.topMouseDown:case w.topMouseMove:case w.topMouseOut:case w.topMouseOver:case w.topMouseUp:u=n;break;case w.topDrag:case w.topDragEnd:case w.topDragEnter:case w.topDragExit:case w.topDragLeave:case w.topDragOver:case w.topDragStart:case w.topDrop:u=s;break;case w.topTouchCancel:case w.topTouchEnd:case w.topTouchMove:case w.topTouchStart:u= q;break;case w.topAnimationEnd:case w.topAnimationIteration:case w.topAnimationStart:u=g;break;case w.topTransitionEnd:u=r;break;case w.topScroll:u=t;break;case w.topWheel:u=p;break;case w.topCopy:case w.topCut:case w.topPaste:u=h}!u?x(!1):void 0;a=u.getPooled(c,b,d,e);f.accumulateTwoPhaseDispatches(a);return a},didPutListener:function(a,b,f){b===A&&(b=a._rootNodeID,a=d.getNodeFromInstance(a),z[b]||(z[b]=e.listen(a,"click",u)))},willDeleteListener:function(a,b){if(b===A){var d=a._rootNodeID;z[d].remove(); delete z[d]}}}},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(43);f.augmentClass(e,{animationName:null,elapsedTime:null,pseudoElement:null});c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(43);f.augmentClass(e,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}});c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(43);f.augmentClass(e,{data:null});c.exports=e},function(c, b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(84);f.augmentClass(e,{dataTransfer:null});c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(68);f.augmentClass(e,{relatedTarget:null});c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(43);f.augmentClass(e,{data:null});c.exports=e},function(c,b,a){function e(a,b,d,e){return f.call(this,a,b,d,e)}var f=a(68),d=a(114);b=a(410);a=a(115);f.augmentClass(e,{key:b,location:null, ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:a,charCode:function(a){return"keypress"===a.type?d(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?d(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}});c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(68);b={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null, shiftKey:null,getModifierState:a(115)};f.augmentClass(e,b);c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(43);f.augmentClass(e,{propertyName:null,elapsedTime:null,pseudoElement:null});c.exports=e},function(c,b,a){function e(a,b,e,c){return f.call(this,a,b,e,c)}var f=a(84);f.augmentClass(e,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null});c.exports=e},function(c,b){c.exports=function(a){for(var b=1,f=0,d=0,g=a.length,c=g&-4;d<c;){for(var k=Math.min(d+4096,c);d<k;d+=4)f+=(b+=a.charCodeAt(d))+(b+=a.charCodeAt(d+1))+(b+=a.charCodeAt(d+2))+(b+=a.charCodeAt(d+3));b%=65521;f%=65521}for(;d<g;d++)f+=b+=a.charCodeAt(d);return b%65521|f%65521<<16}},function(c,b,a){b=a(186);a(12);var e=b.isUnitlessNumber;c.exports=function(a,b,g){if(null==b||"boolean"===typeof b||""===b)return"";if(isNaN(b)||0=== b||e.hasOwnProperty(a)&&e[a])return""+b;"string"===typeof b&&(b=b.trim());return b+"px"}},function(c,b,a){a(47);var e=a(17),f=a(110),d=a(209),g=a(10);a(12);c.exports=function(a){if(null==a)return null;if(1===a.nodeType)return a;if(a=f.get(a))return(a=d(a))?e.getNodeFromInstance(a):null;g(!1)}},function(c,b,a){var e=a(114),f={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"}, d={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"};c.exports=function(a){if(a.key){var b=f[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"=== a.type?(a=e(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?d[a.keyCode]||"Unidentified":""}},function(c,b){function a(a){for(;a&&a.firstChild;)a=a.firstChild;return a}c.exports=function(b,f){for(var d=a(b),g=0,c=0;d;){if(3===d.nodeType){c=g+d.textContent.length;if(g<=f&&c>=f)return{node:d,offset:f-g};g=c}a:{for(;d;){if(d.nextSibling){d=d.nextSibling;break a}d=d.parentNode}d=void 0}d=a(d)}}},function(c,b,a){var e=a(85);c.exports=function(a){return'"'+e(a)+'"'}},function(c, b,a){b=a(198);c.exports=b.renderSubtreeIntoContainer},function(c,b){var a=/-(.)/g;c.exports=function(b){return b.replace(a,function(a,b){return b.toUpperCase()})}},function(c,b,a){var e=a(414),f=/^-ms-/;c.exports=function(a){return e(a.replace(f,"ms-"))}},function(c,b,a){function e(a,b){return!a||!b?!1:a===b?!0:f(a)?!1:f(b)?e(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1}var f=a(423);c.exports=e},function(c,b,a){var e=a(10);c.exports= function(a){if(!a||!("object"==typeof a||"function"==typeof a)||!("length"in a&&!("setInterval"in a)&&"number"!=typeof a.nodeType&&(Array.isArray(a)||"callee"in a||"item"in a)))return[a];if(Array.isArray(a))return a.slice();var b;a:{var g=a.length;Array.isArray(a)||!("object"===typeof a||"function"===typeof a)?e(!1):void 0;"number"!==typeof g?e(!1):void 0;!(0===g||g-1 in a)?e(!1):void 0;"function"===typeof a.callee?e(!1):void 0;if(a.hasOwnProperty)try{b=Array.prototype.slice.call(a);break a}catch(c){}b= Array(g);for(var k=0;k<g;k++)b[k]=a[k]}return b}},function(c,b,a){b=a(22);var e=a(417),f=a(217),d=a(10),g=b.canUseDOM?document.createElement("div"):null,h=/^\s*<(\w+)/;c.exports=function(a,b){var c=g;!g?d(!1):void 0;var n;if(n=(n=(n=a.match(h))&&n[1].toLowerCase())&&f(n)){c.innerHTML=n[1]+a+n[2];for(n=n[0];n--;)c=c.lastChild}else c.innerHTML=a;n=c.getElementsByTagName("script");n.length&&(!b?d(!1):void 0,e(n).forEach(b));for(n=Array.from(c.childNodes);c.lastChild;)c.removeChild(c.lastChild);return n}}, function(c,b){c.exports=function(a){return a===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:a.scrollLeft,y:a.scrollTop}}},function(c,b){var a=/([A-Z])/g;c.exports=function(b){return b.replace(a,"-$1").toLowerCase()}},function(c,b,a){var e=a(420),f=/^ms-/;c.exports=function(a){return e(a).replace(f,"-ms-")}},function(c,b){c.exports=function(a){return!(!a||!("function"===typeof Node?a instanceof Node:"object"===typeof a&& "number"===typeof a.nodeType&&"string"===typeof a.nodeName))}},function(c,b,a){var e=a(422);c.exports=function(a){return e(a)&&3==a.nodeType}},function(c,b){var a=Object.prototype.hasOwnProperty;c.exports=function(b,f,d){if(!b)return null;var g={},c;for(c in b)a.call(b,c)&&(g[c]=f.call(d,b[c],c,b));return g}},function(c,b){c.exports=function(a){var b={};return function(f){b.hasOwnProperty(f)||(b[f]=a.call(this,f));return b[f]}}},,,,,,,function(c,b){c.exports={AUTHENTICATED:"authenticated",REDIRECT:"redirect"}}, function(c,b){c.exports={FREE:"forever-free",BASIC:"basic",PREMIUM_I:"premium_i",PREMIUM_II:"premium_ii",PREMIUM_III:"premium_iii",PREMIUM_IV:"premium_iv",PREMIUM_V:"premium_v"}},function(c,b,a){function e(a){var b=1>=arguments.length||void 0===arguments[1]?{}:arguments[1],d=2>=arguments.length||void 0===arguments[2]?"":arguments[2];return k.getTemplateForSingleItem((0,f.default)({},b,{action:a})).replace("{id}",d)}var f=(b=a(13))&&b.__esModule?b:{"default":b},d=a(143),g=a(25),h=a(295),k=a(164),l= a(173);c.exports={read:function(a){var b=arguments[2];return(1>=arguments.length||void 0===arguments[1]?0:arguments[1])?g.get("/api/rest/global-content-items/"+a):g.get(e(l.GET,b,a))},readForCollection:function(a,b){var d=k.getTemplateForCollectionItems(b).replace("{collectionId}",a);return g.get(d)},update:function(a,b){delete a.author;delete a.pendingPushedServices;delete a.pushedServices;return g.put(e(l.PUT,b,a.id),a)},updateForCollection:function(a,b){delete a.author;delete a.pendingPushedServices; delete a.pushedServices;return g.put(e(l.PUT,b,a.id),a)},create:function(a,b,d){return g.post(e(l.POST,d),a,b)},createForCollection:function(a,b,d){return g.post(e(l.POST,d),a,b)},updateField:function(a){a=h(a);return g.post("/api/commondata/SaveItemField",d.stringify(a))},"delete":function(a,b){return g.delete(e(l.DELETE,b,a))},deleteMany:function(a){a=d.stringify({items:a});return g.post("/api/commondata/RemoveItems",a,{headers:{"Content-Type":"application/x-www-form-urlencoded"}})}}},,function(c, b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAYAAAAehFoBAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1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8b31FGv1+i9d17dZ+qe+vSaN/c75/veO/fdc0clk8lQOkU4lGZhDBvDxrAxbAwbw54iIhEppeynykE/aAE1oIDPP4ITsAEWwJVVJGoLSOQVS+SAGfBJP+UAjZkF+b5y+zBcBOIujNpJsFaUW1rDVBPLoMrF2Gfb5wrWhnVOui7Q5GLcNqgG67bzpO3WabjP4fsHMAiawQ1fYNw2ZkCUWVjDt3/UJ70FhkFeilQl4Ngy9l7npLNPomnQDjIc7g9dyP6vVpI7IiyJDxAFU2DIg44m4AqoB086azjBxzOBNsrHPZ2G523JvUQu+ALjOg1P0KQBmQJtIdgBqzoNf4MLUCzQxsB1EN3aJSgT5KtkrXbD9FhrPWrIbDbYDcLwJj/emAdNG3dtW0EYPgXnoMeDphesgdegdhyT3DO4WYBaQSNr5OGzgc/iGT/qkIbGHXH3pvzkjvi8w2/cddFy+w7G+JVnDWrWF7nWG7iPEIeS7KtS7Ok6wBy4A0tc29QI1fFe7wV0goOg93TWKOXlNs53nkweghHrPs5vbmX+0DaGjWFj2Bg2ho3h/xQ/AgwAV9RNHbZ2vQQAAAAASUVORK5CYII="}, function(c,b,a){b=a(56);a=a(833);a=b(a);c.exports=a},function(c,b,a){b=a(858);var e=a(258);a=a(446)(b,e);c.exports=a},function(c,b,a){b=a(861);var e=a(258);a=a(447)(b,e);c.exports=a},function(c,b,a){var e=a(772),f=a(39),d=a(876),g=a(260),h=Math.min;c.exports=function(a,b,c){if(c?f(a,b,c):null==b){a=g(a);var n=a.length;return 0<n?a[e(0,n-1)]:void 0}c=-1;a=d(a);var n=a.length,s=n-1;for(b=h(0>b?0:+b||0,n);++c<b;){var n=e(c,s),q=a[n];a[n]=a[c];a[c]=q}a.length=b;return a}},function(c,b){c.exports=function(a, b){if(a!==b){var f=null===a,d=void 0===a,g=a===a,c=null===b,k=void 0===b,l=b===b;if(a>b&&!c||!g||f&&!k&&l||d&&l)return 1;if(a<b&&!f||!l||c&&!d&&g||k&&g)return-1}return 0}},function(c,b,a){var e=a(49);c.exports=function(a,b){var g=[];e(a,function(a,f,c){b(a,f,c)&&g.push(a)});return g}},function(c,b){c.exports=function(a,b){var f=a.length;for(a.sort(b);f--;)a[f]=a[f].value;return a}},function(c,b,a){var e=a(159),f=a(38),d=a(259),g=a(443),h=a(869);c.exports=function(a,b,c){var n=-1;b=e(b,function(a){return f(a)}); a=d(a,function(a){return{criteria:e(b,function(b){return b(a)}),index:++n,value:a}});return g(a,function(a,b){return h(a,b,c)})}},function(c,b,a){var e=a(859),f=a(38),d=a(864),g=a(27),h=a(39),k=a(260);c.exports=function(a,b){return function(c,s,q){q&&h(c,s,q)&&(s=void 0);s=f(s,q,3);return 1==s.length&&(c=g(c)?c:k(c),q=e(c,s,a,b),!(c.length&&q===b))?q:d(c,s,a,b)}}},function(c,b,a){var e=a(100),f=a(27);c.exports=function(a,b){return function(c,k,l){return"function"==typeof k&&void 0===l&&f(c)?a(c,k): b(c,e(k,l,3))}}},function(c,b,a){var e=a(38),f=a(866),d=a(27);c.exports=function(a,b){return function(c,l,m,n){var s=3>arguments.length;return"function"==typeof l&&void 0===n&&d(c)?a(c,l,m,s):f(c,e(l,n,4),m,s,b)}}},function(c,b){c.exports=function(a){return[].slice.call(a.querySelectorAll("*"),0).filter(function(a){var b=a.getAttribute("tabindex");null===b&&(b=void 0);var d=isNaN(b);if(b=d||0<=b){d=!d;b=a.nodeName.toLowerCase();if(d=/input|select|textarea|button|object/.test(b)?!a.disabled:"a"=== b?a.href||d:d)a:{for(;a&&a!==document.body;){if(0>=a.offsetWidth&&0>=a.offsetHeight||"none"===a.style.display){d=!1;break a}a=a.parentNode}d=!0}b=d}return b})}},function(c,b,a){var e=a(888);b=a(890);var f=a(450);a=b(function(a,b,c){if(c)for(var k=-1,l=f(b),m=l.length;++k<m;){var n=l[k],s=a[n],q=c(s,b[n],n,a,b);if((q===q?q!==s:s===s)||void 0===s&&!(n in a))a[n]=q}else a=e(a,b);return a});c.exports=a},function(c,b,a){function e(a,b){a="number"==typeof a||l.test(a)?+a:-1;b=null==b?s:b;return-1<a&&0== a%1&&a<b}function f(a){return"number"==typeof a&&-1<a&&0==a%1&&a<=s}function d(a){var b;b=a;if(null==b)b=[];else{g(b)||(b=Object(b));for(var d=b.length,d=d&&f(d)&&(k(b)||h(b))&&d||0,c=b.constructor,l=-1,c="function"==typeof c&&c.prototype===b,n=Array(d),s=0<d;++l<d;)n[l]=l+"";for(var q in b)(!s||!e(q,d))&&!("constructor"==q&&(c||!m.call(b,q)))&&n.push(q);b=n}l=(d=b.length)&&a.length;q=!!l&&f(l)&&(k(a)||h(a));c=-1;for(n=[];++c<d;)s=b[c],(q&&e(s,l)||m.call(a,s))&&n.push(s);return n}function g(a){var b= typeof a;return!!a&&("object"==b||"function"==b)}b=a(894);var h=a(895),k=a(896),l=/^\d+$/,m=Object.prototype.hasOwnProperty,n=b(Object,"keys"),s=9007199254740991,q=function(a){return function(b){return null==b?void 0:b[a]}}("length");c.exports=!n?d:function(a){var b=null==a?void 0:a.constructor;return"function"==typeof b&&b.prototype===a||"function"!=typeof a&&null!=a&&f(q(a))?d(a):g(a)?n(a):[]}},,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(18);var f=e(b);b=a(16);var d= e(b);b=a(13);var g=e(b);b=a(46);var h=e(b);b=a(4);var k=e(b);b=a(51);var l=e(b);b=a(7);var m=e(b);b=a(50);var n=e(b);b=a(19);var s=e(b),q=a(2);b=q.PropTypes;var r=a(11),t=a(832),p=a(248),u=a(453),v=function(a){return!a?[]:!Array.isArray(a)?[a]:t(a).filter(function(a){return!!a})},x=function(a){return a.reduce(function(a,b,d){a[b.key]={index:d,child:b};return a},{})},w=["appear","enter","reorder","leave"],y={component:b.oneOfType([b.string,b.element]),transitions:b.shape({appear:b.func,beforeAppear:b.func, afterAppear:b.func,enter:b.func,beforeEnter:b.func,afterEnter:b.func,reorder:b.func,beforeReorder:b.func,afterReorder:b.func,leave:b.func,beforeLeave:b.func,afterLeave:b.func}).isRequired,wrapChildWithTag:b.oneOfType([b.bool,b.string]),getTransitionParams:b.func,maxErrorTimeout:b.number.isRequired},B={component:"div",wrapChildWithTag:!1,maxErrorTimeout:5E3};a=function(a){function b(a){(0,k.default)(this,b);var d=(0,l.default)(this,(0,h.default)(b).call(this,a)),f=v(a.children),c=x(f);d.state={currentChildren:f, currentChildMapping:c,transitioning:!1};a=a.transitions&&a.transitions.appear;d.transitionChildMappings={appear:a?(0,g.default)({},c):{},enter:{},leave:{},reorder:{},all:a?(0,g.default)({},c):{}};return d}(0,n.default)(b,a);(0,m.default)(b,null,[{key:"propTypes",get:function(){return y}},{key:"defaultProps",get:function(){return B}}]);(0,m.default)(b,[{key:"componentWillReceiveProps",value:function(a){var b=this.state,f=b.currentChildMapping,b=b.currentChildren,c=w.reduce(function(b,d){b[d]=a.transitions&& !!a.transitions[d];return b},{}),g=v(a.children),e=x(g),h=(0,d.default)(this.transitionChildMappings,{appear:{},enter:{},leave:{}});b.forEach(function(a,b){var d=a.key,f=e[d];c.leave&&!f?(h.leave[d]=!0,h.all[d]={child:a,index:b}):c.reorder&&(f&&f.index!==b)&&(h.reorder[d]=!0,h.all[d]={child:a,index:f.index})});c.enter&&g.forEach(function(a,b){var d=a.key;e[d]&&!f[d]&&(h.enter[d]=!0,h.all[d]={child:a,index:b})});this.setState({currentChildren:g,currentChildMapping:e,transitioning:0<(0,s.default)(h.all).length})}}, {key:"shouldComponentUpdate",value:function(a,b){return b.transitioning||this.state.transitioning||this.props.children!==a.children}},{key:"componentWillUnmount",value:function(){var a=this;(0,s.default)(this.transitionChildMappings.all).forEach(function(b){(b=a.refs[b])&&b.endCurrentTransition&&b.endCurrentTransition()});this.transitionChildMappings=null}},{key:"getPropsForChild",value:function(){var a=this.props,b=a.wrapChildWithTag,d=a.maxErrorTimeout,f=a.getTransitionParams,a=a.transitions,c= void 0;b&&(c="string"===typeof b?b:"div");return(0,g.default)({wrapperTag:c,maxErrorTimeout:d,getParams:f},a)}},{key:"wrapChild",value:function(a,b,d){var f=this,c=this.state.currentChildMapping,e=d.key,h=c[e]?c[e].index:-1,c=w.find(function(a){return!!f.transitionChildMappings[a][e]})||"";return q.createElement(a,(0,g.default)({},b,{ref:e,key:"TG-"+e,onTransitionEnd:function(a){return f.onTransitionEnd(e,a,h)},transitionRequested:c}),d)}},{key:"onTransitionEnd",value:function(a,b,d){var f=this.state.currentChildMapping, c=this.transitionChildMappings;c&&("reorder"!==b?delete c[b][a]:(!f[a]||f[a].index===d)&&delete c.reorder[a],w.some(function(b){return!!c[b][a]})||delete c.all[a],0===(0,s.default)(c.all).length&&this.setState({transitioning:!1}))}},{key:"getChildComponent",value:function(){return u}},{key:"getMergedChildren",value:function(){var a=(0,g.default)({},this.state.currentChildMapping,this.transitionChildMappings.all);return(0,s.default)(a).map(function(b){return a[b].child})}},{key:"render",value:function(){var a= this,b=p(this.props,["children","transitions","wrapChildWithTag","maxErrorTimeout","getTransitionParams"]),d=b.component,c=b.className,b=(0,f.default)(b,["component","className"]),d=d||"div",e=this.getChildComponent(),h=this.getPropsForChild();return q.createElement(d,(0,g.default)({className:r(c,this.state.className)},b),this.getMergedChildren().map(function(b){return a.wrapChild(e,h,b)}))}}]);return b}(q.Component);c.exports=a},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}} b=a(46);var f=e(b);b=a(4);var d=e(b);b=a(51);var g=e(b);b=a(7);var h=e(b);b=a(50);var k=e(b),l=a(2),m=a(33);b=l.PropTypes;var n=a(237),s={maxErrorTimeout:b.number.isRequired,appear:b.func,beforeAppear:b.func,afterAppear:b.func,enter:b.func,beforeEnter:b.func,afterEnter:b.func,reorder:b.func,beforeReorder:b.func,afterReorder:b.func,leave:b.func,beforeLeave:b.func,afterLeave:b.func,wrapperTag:b.oneOfType([b.string,b.element]),getParams:b.func,transitionRequested:b.string,onTransitionEnd:b.func},q={maxErrorTimeout:5E3}; a=function(a){function b(){(0,d.default)(this,b);var a=(0,g.default)(this,(0,f.default)(b).call(this));a.state={endAbruptly:!1,params:null};a._transitionEndCallbacks=[];return a}(0,k.default)(b,a);(0,h.default)(b,null,[{key:"propTypes",get:function(){return s}},{key:"defaultProps",get:function(){return q}}]);(0,h.default)(b,[{key:"componentWillMount",value:function(){var a=this.props,b=a.transitionRequested,d=a.getParams,a=a.children,f=null;d&&b&&(f=d(b,null,a.props));this.setState({transition:b, params:f})}},{key:"componentDidMount",value:function(){this.state.transition&&this.transition(this.state.transition)}},{key:"componentWillReceiveProps",value:function(a){var b=this.state.transition,d=a.transitionRequested,f=a.getParams;a=a.children;var b=d&&b&&(d!==b||"reorder"===d),c=null;f&&d&&(c=f(d,m.findDOMNode(this),a.props,b));this.setState({transition:d,endAbruptly:b,params:c})}},{key:"shouldComponentUpdate",value:function(a,b){return Boolean(a.transitionRequested||b.endAbruptly||this.props.children!== a.children)}},{key:"componentDidUpdate",value:function(){this.state.endAbruptly&&this.cleanAfterTransition();this.state.transition&&this.transition(this.state.transition)}},{key:"componentWillUnmount",value:function(){try{this.cleanAfterTransition("transitionEndCallback still existent at unmounting")}catch(a){console.error(a)}}},{key:"endCurrentTransition",value:function(){this.setState({endAbruptly:!0,transition:""})}},{key:"beforeTransition",value:function(a){var b=this.props["before"+n(a)];b&& (!this.state.endAbruptly||"reorder"===a)&&b(m.findDOMNode(this),this.state.params)}},{key:"afterTransition",value:function(a){var b=this.props["after"+n(a)];b&&(!this.state.endAbruptly||"reorder"===a)&&b(m.findDOMNode(this),this.state.params)}},{key:"triggerTransition",value:function(a){this.startErrorTimer();this.props[a](m.findDOMNode(this),this.state.params,this.cleanAfterTransition)}},{key:"transition",value:function(a){var b=this,d=m.findDOMNode(this);this.registerCallback(function(){b.props.onTransitionEnd(a)}); !this.props[a]||!d?this.cleanAfterTransition():(this.beforeTransition(a),this.registerCallback(function(){return b.afterTransition(a)}),this.triggerTransition(a))}},{key:"startErrorTimer",value:function(){var a=this,b=setTimeout(function(){try{a.cleanAfterTransition("Transition timed out before a proper end.")}catch(b){console.error(b)}},0>=arguments.length||void 0===arguments[0]?this.props.maxErrorTimeout:arguments[0]);this.registerCallback(function(){return clearTimeout(b)})}},{key:"registerCallback", value:function(a){"function"===typeof a&&this._transitionEndCallbacks.push(a)}},{key:"cleanAfterTransition",value:function(a){this._transitionEndCallbacks.length&&"string"===typeof a&&console.warn("[TransitionGroupChild]",a);this.fireCallbacks()}},{key:"fireCallbacks",value:function(){for(var a=this._transitionEndCallbacks.length;0<a;){var b=this._transitionEndCallbacks.pop(),a=this._transitionEndCallbacks.length;b&&b()}}},{key:"render",value:function(){var a=this.props,b=a.children,d=a.className, a=a.wrapperTag;!a&&"string"===typeof b&&(a="span");return a?l.createElement(a,{className:d},b):l.Children.only(b)}}]);return b}(l.Component);c.exports=a},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d=a(1199);a=function(){function a(){(0,e.default)(this,a);this.generateActions("loadSuccess","loadFailure","deleteSuccess","deleteFailure","removeAccessSuccess","removeAccessFailure")}(0,f.default)(a,[{key:"load",value:function(a){var b= this;this.dispatch({status:a});return d.load(a).then(function(a){return b.actions.loadSuccess(a.data.results)},function(a){return b.actions.loadFailure(a.data.error)}).catch(function(a){return console.error(a)})}},{key:"delete",value:function(a){var b=this;return d.deleteWebsite(a).then(function(){return b.actions.deleteSuccess(a)},function(){return b.actions.deleteFailure(a)}).catch(function(a){return console.error(a)})}},{key:"removeAccess",value:function(a){var b=this;return d.removeWebsiteAccess(a).then(function(){return b.actions.removeAccessSuccess(a)}, function(){return b.actions.removeAccessFailure(a)}).catch(function(a){return console.error(a)})}}]);return a}();c.exports=b.createActions(a)},function(c,b,a){var e=a(2),f=a(11),d=a(37),g=a(736);b=e.createClass({displayName:"RadioGroup",propTypes:{className:e.PropTypes.string,isDisabled:e.PropTypes.bool,name:e.PropTypes.string,onChange:e.PropTypes.func.isRequired,options:e.PropTypes.array,title:e.PropTypes.string,value:e.PropTypes.any},getDefaultProps:function(){return{options:[]}},renderRadioInput:function(a){var b, d,c=this.props,n=c.isDisabled,s=c.name,q=c.onChange,c=a.value===c.value,r=f(g.option,(b={},b[g.isDisabled]=n,b));b=f((d={},d[g.isDisabled]=n,d));return e.createElement("label",{key:a.value,className:r},e.createElement("input",{className:b,type:"radio",name:s,disabled:n,value:a.value,checked:c,onChange:q}),e.createElement("div",null,a.label))},render:function(){var a=this.props,b=a.title,f=a.options,c=a.children;return e.createElement(d,{className:a.className},b&&e.createElement("div",{className:"title"}, b),f.map(this.renderRadioInput),c)}});c.exports=b},,,,function(c,b,a){c.exports=a.p+"1400217d1f0345060f12d72f61b8c3a9.png"},function(c,b,a){c.exports=a.p+"4bd40896a5de8130f6b3c3014b9dff38.png"},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAXXGlDQ1BJQ0MgUHJvZmlsZQAAaAXtm3dQFN+75k8POYcZZkgDQ84555xzzmHIIDnnIEkRyQIGckYRJIOiqCAGUEGiIiIqmBAVRILCbfju7t3avfev+9utulX0VNNP93l76kw3Vf3U53kbAClnfGhoIIIWgKDgyHBLPU2cvYMjjuQ1IIM/FIADMOI9I0I1zM2NwX+6bM8C6GjwhcjRd/2nZf/xALWXd4QnAJAwPBznFeEZBOtmWNt7hoZHAoA4Oos7JjL0SHPDGhUOTxDW8kfa9x99NDeUxz/a/bjG2lILroHPIaX0ONbkqUfa91jT5x7paE9feJy5HK4XD/byD4b1QwAYVT398F4ASJHCx4WDgkKOtDSs+f+ZJ6wAYLf2iwr28g73CAmMxGn7R4QG4uNwWvhAf49wfKQ3fMa/egkKjIKv0fFydKUpvYNtrOCtMryyAmvgB6JAMPAC3iAceIAQEAgiAQ5oA38QAULhPTyIg/e14G0gfMwDrsLDFd7AK9I7Fr4GAGiFhMaF+/v6ReI04DvoLYwzCPYUFcZJiktIgaP/h6MaADbRx/cZQj/+92NhwwAo5MD37OhW4I6qAMBzATCwCgBy+9+Pcf2Ep10AwNBzz6jw6H/qCI82RI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1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7F9Ue9AAABEElEQVR42tTXyW7CMBSF4TAVBFvaMqU0b8XjlULLGBAN81swtZWYynsghWPkhRe3Gxbo+Er/IrtPtpLYjnO/yaG4Qz4u2qMuM/ZFI0NdhxU7M5DU2CLaCti2TdgWirFhS2gnYJus2L2AbTBi3X+wn4xY9ck6CNgPm7B1RmwZHQVsDUVtwb4zYl/Rn4CtmtiQvDeFjegH9qlGHTsmbcPWX09aauszBCtWQHP9Upnjowo6M2xrHv0KK+kzHQPVPepHQPZQggX5jL4FZN8G5IAJ+YQ2AvILPbAgH9FaQAZsyJWAHDIhs2gpIEdsyIWAHKMk0386EJATNqQaD50M5BSlWE8/nj4Yz5iR5p3+ZuRFgAEAifbWWRallPgAAAAASUVORK5CYII="}, function(c,b,a){c.exports=a.p+"ceff5db950c7bdae4bd6f1e0f0fa3e92.png"},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAXXGlDQ1BJQ0MgUHJvZmlsZQAAaAXtm3dQFN+75k8POYcZZkgDQ84555xzzmHIIDnnIEkRyQIGckYRJIOiqCAGUEGiIiIqmBAVRILCbfju7t3avfev+9utulX0VNNP93l76kw3Vf3U53kbAClnfGhoIIIWgKDgyHBLPU2cvYMjjuQ1IIM/FIADMOI9I0I1zM2NwX+6bM8C6GjwhcjRd/2nZf/xALWXd4QnAJAwPBznFeEZBOtmWNt7hoZHAoA4Oos7JjL0SHPDGhUOTxDW8kfa9x99NDeUxz/a/bjG2lILroHPIaX0ONbkqUfa91jT5x7paE9feJy5HK4XD/byD4b1QwAYVT398F4ASJHCx4WDgkKOtDSs+f+ZJ6wAYLf2iwr28g73CAmMxGn7R4QG4uNwWvhAf49wfKQ3fMa/egkKjIKv0fFydKUpvYNtrOCtMryyAmvgB6JAMPAC3iAceIAQEAgiAQ5oA38QAULhPTyIg/e14G0gfMwDrsLDFd7AK9I7Fr4GAGiFhMaF+/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sBDuw+jTBRYhQRuKy2q0vCfwIJun/0dpWM89zFDIOUeBQAAVQAAU4cgljjKT/js/Hp0L2xF0SlASRLu2oVAJA+jgCnEC9BdDju78AvJuLIHwBZIy5DZH9CuAMGjbMVw1Y6xUgZ8xvKAoi9wVwAY2ESWfVdER+xN5dAAVj3hJL1DIQhStAzEx7s7FDGmY5YtcZuIIma7BacEDVVv2EY+z6BkrQE1R9ccRX2FP62gWJwz2TSHaB0d9yBVAABQgN8BJgAEP5EKNFIAVBAAAAAElFTkSuQmCC"}, function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAL1JREFUeNpiYMAEZkA8C4jvA/EvIP4LxA+AeD4QWzLgAXxAvBSI/wPxOSCuAeJwIA4B4kogPg2VWwLE3Ng0nwTit0AciMcSHyB+DVXLgyyxFKpZDUmMC4h3QDEXkrgK1JClyH7+j2YzSMM+IP4IxfvQDPGF6jFngAbYORyazaEYmyHHgLiOARraNTg0wwA2Q1iBmIkBGlXhUMEdWDSjG7IDWZCJgQqAYi9QHIgURyPFCYkqSZnizER2dgYIMAC5qFO2PVFr9AAAAABJRU5ErkJggg=="},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAZNJREFUeNrMl79KA0EQxi9GEomxsk0j2CURrLQ51Dewig9g4wvYWNrZ2SQR7ERI6rQiiMWBlRgsFKNPIIJaiCdEvw2jDKt3++ckuwO/5m5mv9mb3bndXKBvs2AdrIEFMAfK9O4NPIArcAp64DH4J6uDDojBpyYfoEuJplou5d0M2ANbkp8Y/BLcgicwSV9nHiyCPPMVyRyCbfBiMusquJNmdQIaoJQSJ0qyAc6k2AGo6Yovg2cW3AehRelWwDUbR4y5pDNzL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AUYABdg3P4GoX9qAAAAAElFTkSuQmCC"}, function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3woVDjoQMEtYQQAAAI9JREFUOMutk0sKAyEQRN9kF3DrgXL2uULmFLPIJjDLl0UMTMSoaAoEsat/1faiMoPL6R6A2OETE/cNFTWoq3pXY3ornZg4a/IhN1gJUuQ0CS1bT5ZqdXSUWm2tJZYNXb7GOIZ/tzAl4tQYhz/SR8QDeAAbcAP2glx7sm2JewAsp20MwPWHc75MB/DMAwzhBRd9JksMgAISAAAAAElFTkSuQmCC"},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3woVDjkxVw8b3AAAAPVJREFUWMPtl9ENwyAMRC9dpRtkF+Ts2F26QVfIBJWuP+GjBAjGRG6kWuKLcPckgjkmkvCsG5zrZwFmAGGgT9g090UyHTPJleSb5JKZ145l01o37a/5knksK0Q0j7WDSBeEZEGEkAHmUSvUAGoLNRBS0FiOtmAERLN5DaAXQmV+BFATFOO3zQCtwtK7ZdafSizmGoAahOnEaM92DsLUM3q6Wwmiq2G534aX2gLXn9D1GLo2ItdWLAMvI9ECyAnXsbQCyImBRI4ARkYy6YlkuVAqhlAq2lCaxnKLeQqRjeVT4W04A7gDeAx8mLwAPNOJ6f849Qb4AIEdi3VvAzBFAAAAAElFTkSuQmCC"}, function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAXXGlDQ1BJQ0MgUHJvZmlsZQAAaAXtm3dQFN+75k8POYcZZkgDQ84555xzzmHIIDnnIEkRyQIGckYRJIOiqCAGUEGiIiIqmBAVRILCbfju7t3avfev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3Qh/su6EE86D046D046D046D046D/7bdB4AEOEjJXnsAiDKcPiVhJ3Dw00sACSDAPyF04j9isPDv/UAECwAMBz2zzshR9XE8FszRXwYLNO1p+Qqqcfn/29//g0Sbd7HB9ic4wAAAOhJREFUeAHtmTEOhEAMxADd/7981EgRSoGBIb5yheaCx7tbsCz+JCABCUhAAhKQgARmEliL1/4Xa3cuVTNh/79hySHBAggpChvz10im9+SjZ45boGHApx/RgE/X23i58QZ0boEGx0sfoW+Fw6023gABXCpvYNgbzoDDngQYnp4pbgGAeFSkBkTVBQyrAQDUqEgNiKoLGFYDAKhRkRoQVRcwrAYAUKMiNSCqLmBYDQCgRkVqQFRdwLAaAECNitSAqLqAYTUAgBoVOd6AzrfB029rUXUXw443QACFFS5JQAISkIAEJCCBEQR2INUFY+bCLiIAAAAASUVORK5CYII="}, function(c,b,a){c.exports=a.p+"a569cb62e2b897a82d1b06cc4810fa63.png"},function(c,b,a){c.exports=a.p+"f4fc5c99d3037e3a48b5a0f181f90cf5.png"},function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAXOWlDQ1BJQ0MgUHJvZmlsZQAAaIHtm3dQFN+Wx28POYcZZkgDQ84555xzzmHIIDnnIEkRyQIGckYRJIOiqCAGUEGiIiIqmBAVRILCtvrb97Z291Xt/rFbu/W4XT3326fP9L3dM1X3U+ecBkDKGR8aGoigBSAoODLcUk8TZ+/giCN5DsjgjQJwAEa8Z0Sohrm5MfiHbXsWQL/6JyK/rvWP/f7TRu3lHeEJACQM6zivCM8gWDfD2t4zNDwSAMQvH+6YyNBfmhvWqHB4grCW/6V9/+hfc0N5/NHuv32sLbVgDX+HlNLjtyZP/aV9f2v63F862tMXPs9cDvuLB3v5B8P6LgCMqp5+eC8ApEhhu3BQUMgvLQ1r/j/z/N3Yrf2igr28wz1CAiNx2v4RoYH4OJwWPtDfIxwf6e3133wC/4UWFBj1r2P/etKU3sE2VnCvDO+swBr4gSgQD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5u3mn+2YLQw9lL75d1XKq9uLsov9ryWet2xJLrU9kboTesy/3LTW963jSs8Kw3veN41vOd53/iB70PzqsBq65rw2vWP4h87P0l/6vus+Hnoi/qXka/6X8fXzdenvzl8W9rw3Pj0Pfj71o/4n9DP7E3qzQtb2K36X8K/ureVt0d/m/6e23Hf+bwbuXuwd2YfuV/5R+BP91/1v+MH9gcfDsMPD//JZo5TAug4cziSR8nH0Xq0/B/6n/zmaIBRFoAmdQBsUgEwHgagEl55YE0Jb80BANbqAME/DBBMOwAhNgQI4AziOGKCh46+FYL3EIAAEMIfIkAMexAyOJ+gAFSAGtACOtiNMAAMnFWwACzAHXsSPiAIuxLx49RC4X/4El04uTABFsAGzi7+py8JPk4vEkAqyIQ9ST4ogR1JJexHWmA30g0GwTDsRMbBFJgHS+AD7EB+gl1wCBHDzgMFscCeQxCSgBRO3MZJCnGSQpykECcpxEkKcZJC/KtSiONn/8nz/6QL4b/ehXBCG05owwltOKENJ7ThvxFtOHn+n3Qh/su6EE86D046D046D046D046D/7bdB4AEOEjJXnsAiDKcPiVhJ3Dw00sACSDAPyF04j9isPDv/UAECwAMBz2zzshR9XE8FszRXwYLNO1p+Qqqcfn/29//g0Sbd7HB9ic4wAAAE9JREFUWAljYBgFoyEw0kOAEUsA/MciRk0hFDuZqGnyqFmjIUBOCKCkSKgBo7mAnJAc1TN0Q2A0FwzduBt1ObVCYDQXUCskR80ZDYGhGwIAZ2IEDb0WUzEAAAAASUVORK5CYII="}, function(c,b){c.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAXXGlDQ1BJQ0MgUHJvZmlsZQAAaAXtm3dQFN+75k8POYcZZkgDQ84555xzzmHIIDnnIEkRyQIGckYRJIOiqCAGUEGiIiIqmBAVRILCbfju7t3avfev+9utulX0VNNP93l76kw3Vf3U53kbAClnfGhoIIIWgKDgyHBLPU2cvYMjjuQ1IIM/FIADMOI9I0I1zM2NwX+6bM8C6GjwhcjRd/2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HOb8MhMV+ueI1mYUDhV5U7stlB9+dsdy9QiMsi1XiiqwMj7ACZEGyIIEVILmd9xqCg7sSWAFLZWDECugXgysTWAGSWz8roEd45BKkjokmaeCm70I9rACulZ8RoWZ5AiqgXNQZmPOwPxDqFh+uSUAFSE7dSkte2sUfK0RwNN8lU8083WrXFcBVIP0AhCuzrySQAraqwA6zAXAOSF+bxZf4CCknAcjnKHEcpnPVFcDtp6Pa/7kVbWcCKGCnCmyrGwXXGQrgnGCv+HKtcq/vNxZSqGb2N+3V8x+ZDjepwI4v3jZ2zWMF7BJb37ASx2RSAXxuvl2M8fl6gwuT8wjYlgYV2BugwO2qPmDqEPlJ+brA9MyJ+/BOqegLprGWSqxzXbHcQrtZftAbpFDBNbgh8ba4Ll88D8gXY646+SFwmgpHASzcdc1H1GPa2CLlq/NlxTH5LMxxkTY2Bi7GTvJQNUE2mY1iLJ/wY5xaQjHmli/GN6oQHeSzdYqeRBa1QhvjTsw1iKbOxdGa/8JgnXsIr4f6Yji9wtx1vUxUU7ixiSu0fPjRO8fkG+DwbhDjvBReUhaapfkBXIJOFZbATob78JbDUmLdMc5BDp8QrTdso3tAfnK2h4R7X4CVwF3Xg9hb9eCCT4Y2YNvsU+7fGcgBQT6Nkuea7PDqYfZh3SGK9MYIv+lvla81PUU40xI4nBTEDLZvjXBK24g09j6DAx9CyhvRidT/l6YsXJt7Q4W+KziJpcGNF2exc4S6NsfOlivTDyhfJ1dcXptTYlvkfJs7MNNj5ABHkdU1ydg+UrFxc5QPK78jvK18Z4q5yr3bowOwOI5DvlYOb43asgCTRHp5OtTu4+rlabduj/dpk43r6/P/CTAA7UGbbRTyJT8AAAAASUVORK5CYII="}, ,,function(c,b){c.exports=function(a,b){for(var f=-1,d=a.length;++f<d;)if(!b(a[f],f,a))return!1;return!0}},function(c,b,a){var e=a(49);c.exports=function(a,b){var c=!0;e(a,function(a,f,e){return c=!!b(a,f,e)});return c}},function(c,b,a){var e=a(49);c.exports=function(a,b){var c;e(a,function(a,f,e){c=b(a,f,e);return!c});return!!c}},function(c,b){YUI.add("model",function(a,b){function f(){f.superclass.constructor.apply(this,arguments)}var d=YUI.namespace("Env.Model"),c=a.Lang,h=a.Array,k=a.Object,l= "error";a.Model=a.extend(f,a.Base,{idAttribute:"id",_allowAdHocAttrs:!0,_isYUIModel:!0,initializer:function(a){this.changed={};this.lastChange={};this.lists=[]},destroy:function(a,b){var d=this;"function"===typeof a&&(b=a,a=null);d.onceAfter("destroy",function(){function f(c){c||h.each(d.lists.concat(),function(b){b.remove(d,a)});b&&b.apply(null,arguments)}a&&(a.remove||a["delete"])?d.sync("delete",a,f):f()});return f.superclass.destroy.call(d)},generateClientId:function(){d.lastId||(d.lastId=0); return this.constructor.NAME+"_"+(d.lastId+=1)},getAsHTML:function(b){b=this.get(b);return a.Escape.html(c.isValue(b)?String(b):"")},getAsURL:function(a){a=this.get(a);return encodeURIComponent(c.isValue(a)?String(a):"")},isModified:function(){return this.isNew()||!k.isEmpty(this.changed)},isNew:function(){return!c.isValue(this.get("id"))},load:function(a,b){var d=this;"function"===typeof a&&(b=a,a={});a||(a={});d.sync("read",a,function(f,c){var g={options:a,response:c},e;f?(g.error=f,g.src="load", d.fire(l,g)):(d._loadEvent||(d._loadEvent=d.publish("load",{preventable:!1})),e=g.parsed=d._parse(c),d.setAttrs(e,a),d.changed={},d.fire("load",g));b&&b.apply(null,arguments)});return d},parse:function(b){if("string"===typeof b)try{return a.JSON.parse(b)}catch(d){return this.fire(l,{error:d,response:b,src:"parse"}),null}return b},save:function(a,b){var d=this;"function"===typeof a&&(b=a,a={});a||(a={});d._validate(d.toJSON(),function(f){f?b&&b.call(null,f):d.sync(d.isNew()?"create":"update",a,function(f, c){var g={options:a,response:c},e;f?(g.error=f,g.src="save",d.fire(l,g)):(d._saveEvent||(d._saveEvent=d.publish("save",{preventable:!1})),c&&(e=g.parsed=d._parse(c),d.setAttrs(e,a)),d.changed={},d.fire("save",g));b&&b.apply(null,arguments)})});return d},set:function(a,b,d){var f={};f[a]=b;return this.setAttrs(f,d)},setAttrs:function(b,d){var f=this.idAttribute,c,g,e,h;d=a.merge(d);h=d._transaction={};"id"!==f&&(b=a.merge(b),k.owns(b,f)?b.id=b[f]:k.owns(b,"id")&&(b[f]=b.id));for(g in b)k.owns(b,g)&& this._setAttr(g,b[g],d);if(!k.isEmpty(h)){f=this.changed;e=this.lastChange={};for(g in h)k.owns(h,g)&&(c=h[g],f[g]=c.newVal,e[g]={newVal:c.newVal,prevVal:c.prevVal,src:c.src||null});d.silent||(this._changeEvent||(this._changeEvent=this.publish("change",{preventable:!1})),d.changed=e,this.fire("change",d))}return this},sync:function(){var a=h(arguments,0,!0).pop();"function"===typeof a&&a()},toJSON:function(){var a=this.getAttrs();delete a.clientId;delete a.destroyed;delete a.initialized;"id"!==this.idAttribute&& delete a.id;return a},undo:function(a,b){var d=this.lastChange,f=this.idAttribute,c={},g;a||(a=k.keys(d));h.each(a,function(a){k.owns(d,a)&&(a=a===f?"id":a,g=!0,c[a]=d[a].prevVal)});return g?this.setAttrs(c,b):this},validate:function(a,b){b&&b()},addAttr:function(a,b,d){var e=this.idAttribute,h;e&&a===e&&(e=this._isLazyAttr("id")||this._getAttrCfg("id"),h=b.value===b.defaultValue?null:b.value,c.isValue(h)||(h=e.value===e.defaultValue?null:e.value,c.isValue(h)||(h=c.isValue(b.defaultValue)?b.defaultValue: e.defaultValue)),b.value=h,e.value!==h&&(e.value=h,this._isLazyAttr("id")?this._state.add("id","lazy",e):this._state.add("id","value",h)));return f.superclass.addAttr.apply(this,arguments)},_parse:function(a){return this.parse(a)},_validate:function(a,b){function d(e){c.isValue(e)?(f.fire(l,{attributes:a,error:e,src:"validate"}),b(e)):b()}var f=this;1===f.validate.length?d(f.validate(a,d)):f.validate(a,d)},_setAttrVal:function(a,b,d,c,g,e){var h=f.superclass._setAttrVal.apply(this,arguments),k=g&& g._transaction,l=e&&e.initializing;h&&(k&&!l)&&(k[a]={newVal:this.get(a),prevVal:d,src:g.src||null});return h}},{NAME:"model",ATTRS:{clientId:{valueFn:"generateClientId",readOnly:!0},id:{value:null}}})},"3.17.2",{requires:["base-build","escape","json-parse"]})},,function(c,b,a){var e=a(2),f=a(37),d=a(11),g=a(817);b=e.createClass({displayName:"FlatSelect",propTypes:{className:e.PropTypes.string,isFixedWidth:e.PropTypes.bool,name:e.PropTypes.string.isRequired,onChange:e.PropTypes.func.isRequired,options:e.PropTypes.array, title:e.PropTypes.string,value:e.PropTypes.string},getDefaultProps:function(){return{options:[],isFixedWidth:!0}},renderSelectButtons:function(a){var b,f=this.props,c=f.name,n=f.onChange,s=f.options,q=f.isFixedWidth,f=a.value===f.value,r=d(g.option,(b={},b[g.active]=f,b));return e.createElement("label",{key:a.value,className:r,style:q?{width:100/s.length+"%"}:{}},e.createElement("input",{"data-test":a.testAttr,type:"radio",name:c,value:a.value,checked:f,onChange:n}),a.label)},render:function(){var a= this.props,b=a.title,d=a.options;return e.createElement(f,{className:a.className},b&&e.createElement("div",{className:"title"},b),e.createElement("div",{className:g.optionsContainer},d.map(this.renderSelectButtons)))}});c.exports=b},function(c,b){c.exports={ENABLED:1,DISABLED:2}},,function(c,b,a){b=a(1125);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,,,function(c,b,a){b=a(1240);a=a(870)(b);c.exports=a},function(c,b,a){function e(a){return a&&a.__esModule?a: {"default":a}}b=a(46);var f=e(b);b=a(4);var d=e(b);b=a(7);var g=e(b);b=a(51);var h=e(b);b=a(158);var k=e(b);b=a(50);var l=e(b);b=a(19);b=e(b);var m=a(26),n=m.Record,s=m.Set,q=m.Map,r=a(76),t=a(537);a={allowSquarespacePromotion:!0,amazonAssociateTag:void 0,announcementBarSettings:q(),assetPurchasesByNonAdminsAllowed:!0,businessHours:q(),collectionTitleFormat:void 0,commentAnonAllowed:void 0,commentApprovalRequired:void 0,commentAvatarsOn:void 0,commentDisableAfterDaysDefault:0,commentEnableByDefault:void 0, commentFlagThreshold:0,commentFlagsAllowed:void 0,commentLikesAllowed:void 0,commentSortType:void 0,commentThreaded:void 0,commentsEnabled:!0,configurationMenuItems:void 0,contactEmail:void 0,contactPhoneNumber:void 0,country:void 0,defaultPostFormat:void 0,disqusShortname:"",homepageTitleFormat:void 0,hours:void 0,id:void 0,itemTitleFormat:void 0,lastAgreedTermsOfService:void 0,markdownMode:void 0,mobileInfoBarSettings:q(),notFoundPageId:null,ownerId:void 0,pinterestOverlayOptions:q(),simpleLikingEnabled:void 0, socialAccountDisplayOrder:void 0,ssBadgeDevices:void 0,ssBadgePosition:void 0,ssBadgeType:void 0,ssBadgeVisibility:void 0,state:void 0,storeSettings:void 0,subjects:void 0,tutorialsCompleted:s(),type:void 0,contentDescription:q(),goals:q(),useDeviceView:!0,useEscapeKeyToLogin:!0,websiteId:void 0};var p=(0,b.default)(a);c.exports=function(a){function b(){var a=0>=arguments.length||void 0===arguments[0]?{}:arguments[0];(0,d.default)(this,b);return(0,h.default)(this,(0,f.default)(b).call(this,m.fromJS(t(a))))} (0,l.default)(b,a);(0,g.default)(b,[{key:"merge",value:function(a){a=a instanceof n?a:r(t(a),p);return(0,k.default)((0,f.default)(b.prototype),"merge",this).call(this,a)}},{key:"serializeToModel",value:function(){var a=this.toJS(),b=a.tutorialsCompleted;null===a.notFoundPageId&&(a.notFoundPageId="system-default");b&&(a.tutorialsCompleted=b.reduce(function(a,b){a[b]=!0;return a},{}));return a}}]);return b}(n(a))},function(c,b,a){var e=(b=a(19))&&b.__esModule?b:{"default":b},f=(b=a(16))&&b.__esModule? b:{"default":b},d=a(26).Set;c.exports=function(a){var b=a.notFoundPageId,c=a.tutorialsCompleted;a=(0,f.default)({},a);c&&(a.tutorialsCompleted=d((0,e.default)(c)));"system-default"===b&&(a.notFoundPageId=null);return a}},,function(c,b){c.exports={PRE_SELECT:1,SELECT_WEBSITE:2,REDIRECT:3}},,function(c,b,a){b=a(432);c.exports={AUTHENTICATED:b.AUTHENTICATED,REDIRECT:b.REDIRECT,CLOSE:"close",STEP_CHANGE:"step-change",CART_UPDATE:"cart"}},,function(c,b,a){c.exports={"default":a(723),__esModule:!0}},function(c, b,a){b=c.exports=a(3)();b.i(a(23),void 0);b.push([c.id,".Button-primary-2OWIg {\n}\n.Button-recommend-2Gev7 {\n}\n.Button-minor-3yzec {\n}\n.Button-caution-2HLwV {\n}\n.Button-text-9cpue {\n}\n.Button-inset-21Jhw {\n}\n",""]);b.locals={primary:"Button-primary-2OWIg "+a(23).locals.primary+"",recommend:"Button-recommend-2Gev7 "+a(23).locals.recommend+"",minor:"Button-minor-3yzec "+a(23).locals.minor+"",caution:"Button-caution-2HLwV "+a(23).locals.caution+"",text:"Button-text-9cpue "+a(23).locals.text+ "",inset:"Button-inset-21Jhw "+a(23).locals.inset+""}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".Field-container-1EwT9 {\n margin-top: 11px;\n}\n.Field-errorMessage-38dQE {\n color: #f0523d;\n font-size: 11px;\n padding: 4px 0;\n}\n.Field-childField-2URnO {\n font-size: 11px;\n margin-left: 33px;\n}\n.Field-inline-ma6GI .FieldLabel {\n display: inline-block;\n width: 20%;\n}\n.Field-inline-ma6GI .FieldLabel + input {\n width: 80%;\n}\n.Field-inline-ma6GI .Field-errorMessage-38dQE {\n margin-left: 20%;\n}\n.Field-container-1EwT9.Field-midnight-2Qrn7 {\n position: relative;\n margin-top: 0;\n padding: 11px;\n padding-bottom: 0;\n width: 50%;\n box-sizing: border-box;\n}\n.fullWidthFields .Field-container-1EwT9.Field-midnight-2Qrn7 {\n width: 100%;\n}\n.Field-container-1EwT9.Field-midnight-2Qrn7 .Field-errorMessage-38dQE {\n z-index: 1;\n background-color: #f0523d;\n padding: 11px;\n box-sizing: border-box;\n position: absolute;\n width: calc(100% - 22px);\n color: #ffffff;\n font-weight: 400;\n font-size: 12px;\n}\n@media screen and (max-width: 600px) {\n .Field-container-1EwT9.Field-midnight-2Qrn7 {\n width: 100%;\n }\n}\n@media screen and (max-width: 330px) {\n .FieldLabel {\n font-size: 9px;\n }\n}\n", ""]);b.locals={container:"Field-container-1EwT9",errorMessage:"Field-errorMessage-38dQE",childField:"Field-childField-2URnO",inline:"Field-inline-ma6GI",midnight:"Field-midnight-2Qrn7"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".Label-midnight-1YyG4 {\n line-height: 11px;\n font-size: 11px;\n text-transform: uppercase;\n font-weight: 400;\n color: #888888;\n}\n",""]);b.locals={midnight:"Label-midnight-1YyG4"}},function(c,b,a){b=a(544);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{}); b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(546);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,function(c,b,a){var e=a(65),f=a(39);c.exports=function(a,b,c){var k=a?a.length:0;c&&f(a,b,c)&&(b=!1);return k?e(a,b):[]}},function(c,b){c.exports=function(a,b,f){for(var d=a.length,c=f?d:-1;f?c--:++c<d;)if(b(a[c],c,a))return c;return-1}},function(c,b,a){b=a(1038)(!0);c.exports=b},function(c,b,a){var e=a(148),f=a(297),d=a(298);c.exports=function(a,b){var c=-1, l=e,m=a.length,n=!0,s=n&&200<=m,q=s?d():null,r=[];q?(l=f,n=!1):(s=!1,q=b?[]:r);a:for(;++c<m;){var t=a[c],p=b?b(t,c,a):t;if(n&&t===t){for(var u=q.length;u--;)if(q[u]===p)continue a;b&&q.push(p);r.push(t)}else 0>l(q,p,0)&&((b||s)&&q.push(p),r.push(t))}return r}},function(c,b){c.exports=function(a,b){for(var f=-1,d=b.length,c=Array(d);++f<d;)c[f]=a[b[f]];return c}},function(c,b,a){var e=a(862),f=a(38),d=a(867),g=a(27),h=a(39),k=a(260);c.exports=function(a,b,c){c&&h(a,b,c)&&(b=void 0);b=f(b,c,3);return 1== b.length?e(g(a)?a:k(a),b):d(a,b)}},function(c,b,a){var e=a(1236),f=a(937);b=a(870)(function(a,b,c){return c?e(a,b,c):f(a,b)});c.exports=b},function(c,b,a){var e=a(333);c.exports={shouldComponentUpdate:function(a,b){return e(this,a,b)}}},,,,,,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(19);var f=e(b);b=a(13);var d=e(b);b=a(146);var g=e(b);b=a(29);var h=e(b);b=a(4);var k=e(b);b=a(7);var l=e(b);b=a(9);var m=a(157),n=a(95),s=a(272),q=a(920),r=a(218),t=r.BundleType,p=a(341); a=function(){function a(){(0,k.default)(this,a);this.generateActions("createAuthorSuccess","createAuthorFailure","createInviteSuccess","deleteAuthorSuccess","deleteContributorSuccess","deleteInviteSuccess","updateInviteSuccess","updateAuthorSuccess","updateAuthorFailure","updateContributorPermissionsSuccess","resetSuccess","resetFailure","transferOwnerSuccess")}(0,l.default)(a,[{key:"reset",value:function(){var a=this,b=[q.readMemberPermissions(),q.readMemberInvites()];h.default.all(b).then(function(b){b= (0,g.default)(b,2);var c=b[0],e=b[1],k=[],l=[],s=[],u=[],x=n.state.get("ownerId"),q=void 0,e=e.data;c.data&&c.data.forEach(function(a){var b=(a.guilds||{})[p.CIRCLE_USER],c=(0,d.default)({},a.memberAccount,{isCircleMember:b,lastLoginOn:a.lastLoginOn,permissions:a.permissions,permissionsId:a.id});c.avatarId&&u.push(m.fetch(c.avatarId,!0).then(function(a){c.avatarBundle=new r({item:a,isGlobal:!0,type:t.IMAGE_META})}));c.id===x?q=c:c.pseudonymAccount?k.push(c):(0,f.default)(c.permissions).length?l.push(c): s.push(c)});h.default.all(u).then(function(){a.actions.resetSuccess({invitations:e,basicAuthors:k,contributorsWithoutPermissions:s,contributorsWithPermissions:l,websiteOwner:q})})}).catch(this.actions.resetFailure)}},{key:"transferOwner",value:function(a,b,d,f){var c=this;return q.transferOwner(a,b).then(function(){c.actions.transferOwnerSuccess(a);d()},f)}},{key:"createInvite",value:function(a,b,d){var c=this;a.permissions=(0,f.default)(a.permissions).filter(function(b){return a.permissions[b]}); return q.createMemberInvite(a).then(function(a){c.actions.createInviteSuccess(a.data);return b()},d).catch(function(a){return console.error(a)})}},{key:"updateInvite",value:function(a,b,d){var c=this;a.permissions=(0,f.default)(a.permissions).filter(function(b){return a.permissions[b]});return q.updateMemberInvite(a).then(function(a){c.actions.updateInviteSuccess(a.data);return b()},d).catch(function(a){return console.error(a)})}},{key:"deleteInvite",value:function(a){var b=this;return q.deleteMemberInvite(a).then(function(){return b.actions.deleteInviteSuccess(a)}).catch(function(a){return console.error(a)})}}, {key:"updateContributor",value:function(a){var b=this;a.permissions=(0,f.default)(a.permissions).filter(function(b){return a.permissions[b]});return q.updateMemberPermissions(a).then(function(a){b.actions.updateContributorPermissionsSuccess(a.data);return h.default.resolve()}).catch(function(a){return console.error(a)})}},{key:"deleteContributor",value:function(a){var b=this;return q.deleteMemberPermissions(a).then(function(){b.actions.deleteContributorSuccess(a);return h.default.resolve()}).catch(function(a){return console.error(a)})}}, {key:"createAuthor",value:function(a){var b=this;return q.createBasicAuthor(a).then(function(a){q.assignPermissionsToBasicAuthor(a).then(function(){return b.actions.createAuthorSuccess(a.data)})}).catch(this.actions.createAuthorFailure)}},{key:"updateAuthor",value:function(a){var b=this,d=a.avatarBundle;delete a.avatarBundle;(a.pseudonymAccount?q.updateAuthor:s.update)(a).then(function(a){a.data.avatarBundle=d;b.actions.updateAuthorSuccess(a.data)},this.actions.updateAuthorFailure)}},{key:"deleteAuthor", value:function(a){var b=this;return q.deleteAuthor(a).then(function(){b.actions.deleteAuthorSuccess(a)}).catch(function(a){return console.error(a)})}}]);return a}();c.exports=b.createActions(a)},function(c,b,a){b=(b=a(240))&&b.__esModule?b:{"default":b};c.exports=(0,b.default)({TRIAL_UPGRADE_PLAN:"trial-upgrade",TRIAL_SWITCH_PRODUCT:"trial-switch",UPGRADE_PLAN:"upgrade",SWITCH_PRODUCT:"switch"})},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b}, d=a(147);b=a(9);var g=a(44),h=a(454);a=function(){function a(){(0,e.default)(this,a);this.state={websiteSummaries:[],loading:!1};this.bindActions(h);this.bindListeners({bootstrap:g.BOOTSTRAP});this.exportPublicMethods({getWebsiteSummaries:this.getWebsiteSummaries,filter:this.filter})}(0,f.default)(a,[{key:"onLoadSuccess",value:function(a){this.setState({websiteSummaries:a})}},{key:"onDelete",value:function(){this.setState({loading:!0})}},{key:"onDeleteSuccess",value:function(a){this.setState({websiteSummaries:this.state.websiteSummaries.filter(function(b){return b.id!== a}),loading:!1})}},{key:"onDeleteFailure",value:function(){this.setState({loading:!1})}},{key:"onRemoveAccess",value:function(){this.setState({loading:!0})}},{key:"onRemoveAccessSuccess",value:function(a){this.setState({websiteSummaries:this.state.websiteSummaries.filter(function(b){return b.id!==a}),loading:!1})}},{key:"onRemoveAccessFailure",value:function(){this.setState({loading:!1})}},{key:"bootstrap",value:function(a){this.setState({websiteSummaries:a.websiteSummaries})}},{key:"filter",value:function(a){var b= this.state.websiteSummaries,f=a.toLowerCase().trim(),c=function(){return d((0>=arguments.length||void 0===arguments[0]?"":arguments[0]).toLowerCase(),f)};return b.filter(function(a){var b=a.identifier,d=a.primaryDomain,f=a.domains;return c(a.siteTitle)||c(b)||c(d)||f.some(function(a){return c(a.name)})})}},{key:"getWebsiteSummaries",value:function(){return this.state.websiteSummaries}}]);return a}();c.exports=b.createStore(a,"WebsiteSummariesStore")},,,,,function(c,b){c.exports={ACTIVE:1,EXPIRED:2, PASTDUE:3}},,,,function(c,b){c.exports={TWO_FACTOR_AUTH_REQUIRED:1,LOGIN_REQUIRED:2,INVALID_CODE:3,NO_PHONE_NUMBER:4}},,function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=a(2);b=f.PropTypes;var d=a(11),g=a(28),h=a(1126);a=f.createClass({displayName:"Navigation",propTypes:{leftButtonLabel:b.string,rightButtonLabel:b.string,onLeftButtonClick:b.func,onRightButtonClick:b.func,leftButtonProps:b.object,rightButtonProps:b.object,forceStack:b.bool,theme:g},getDefaultProps:function(){return{leftButtonProps:{}, rightButtonProps:{},forceStack:!1}},renderButton:function(a,b,d,c){if(!a)return null;var g=a.replace(/\s/g,"-");return f.createElement("button",(0,e.default)({className:b,onClick:d},c,{"data-test":g}),a)},render:function(){var a,b=this.props,c=b.leftButtonLabel,e=b.rightButtonLabel,g=b.onLeftButtonClick,q=b.onRightButtonClick,r=b.leftButtonProps,t=b.rightButtonProps,p=b.theme,b=b.forceStack,b=d(h.container,h[p],(a={},a[h.forceStack]=b,a));a=d(h.leftButton,h["leftButton_"+p]);p=d(h.rightButton,h["rightButton_"+ p]);return f.createElement("div",{className:b},f.createElement("div",{className:d(h.buttonWrapper,h.left)},this.renderButton(c,a,g,r)),f.createElement("div",{className:d(h.buttonWrapper,h.right)},this.renderButton(e,p,q,t)))}});c.exports=a},,,function(c,b,a){var e=a(148),f=a(297),d=a(298);c.exports=function(a,b){var c=a?a.length:0,l=[];if(!c)return l;var m=-1,n=e,s=!0,q=s&&200<=b.length?d(b):null,r=b.length;q&&(n=f,s=!1,b=q);a:for(;++m<c;)if(q=a[m],s&&q===q){for(var t=r;t--;)if(b[t]===q)continue a; l.push(q)}else 0>n(b,q,0)&&l.push(q);return l}},,,,,function(c,b){c.exports={TOP_LEFT:"TOP_LEFT",TOP_CENTER:"TOP_CENTER",TOP_RIGHT:"TOP_RIGHT",CENTER_LEFT:"CENTER_LEFT",CENTER_CENTER:"CENTER_CENTER",CENTER_RIGHT:"CENTER_RIGHT",BOTTOM_LEFT:"BOTTOM_LEFT",BOTTOM_CENTER:"BOTTOM_CENTER",BOTTOM_RIGHT:"BOTTOM_RIGHT"}},,,function(c,b,a){b=c.exports=a(3)();b.i(a(45),void 0);b.i(a(263),void 0);b.push([c.id,".Description-midnight-Vscf7 {\n padding: 11px;\n}\n.Description-hidden-4xjou {\n display: none;\n}\n.Description-title-2_Xa9 {\n}\n.Description-text-2ZNA5 a:hover {\n color: #3e3e3e;\n}\n.Description-text-2ZNA5 {\n color: #797979;\n font-size: 11px;\n}\n.Description-bookmarklet-3S4kR {\n background: #e4e4e4;\n border-bottom: none;\n border-radius: 100px;\n color: #3e3e3e;\n display: block;\n font-size: 11px;\n font-weight: 500;\n margin-left: auto;\n margin-right: auto;\n padding: 5.5px 0;\n text-align: center;\n width: 160px;\n}\n", ""]);b.locals={midnight:"Description-midnight-Vscf7",hidden:"Description-hidden-4xjou",title:"Description-title-2_Xa9 "+a(45).locals.headline+"",text:"Description-text-2ZNA5",bookmarklet:"Description-bookmarklet-3S4kR "+a(263).locals.smallMargin+""}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".Input-container-1WRGR {\n margin-top: 11px;\n}\n.Input-errorMessage-1kTwU {\n color: #f0523d;\n font-size: 11px;\n padding: 4px 0;\n}\n.Input-childField-ezAkI {\n font-size: 11px;\n margin-left: 33px;\n}\n.Input-inline-15X5s .FieldLabel {\n display: inline-block;\n width: 20%;\n}\n.Input-inline-15X5s .FieldLabel + input {\n width: 80%;\n}\n.Input-inline-15X5s .Input-errorMessage-1kTwU {\n margin-left: 20%;\n}\n.Input-container-1WRGR.Input-midnight-1pwjw {\n position: relative;\n margin-top: 0;\n padding: 11px;\n padding-bottom: 0;\n width: 50%;\n box-sizing: border-box;\n}\n.fullWidthFields .Input-container-1WRGR.Input-midnight-1pwjw {\n width: 100%;\n}\n.Input-container-1WRGR.Input-midnight-1pwjw .Input-errorMessage-1kTwU {\n z-index: 1;\n background-color: #f0523d;\n padding: 11px;\n box-sizing: border-box;\n position: absolute;\n width: calc(100% - 22px);\n color: #ffffff;\n font-weight: 400;\n font-size: 12px;\n}\n@media screen and (max-width: 600px) {\n .Input-container-1WRGR.Input-midnight-1pwjw {\n width: 100%;\n }\n}\n@media screen and (max-width: 330px) {\n .FieldLabel {\n font-size: 9px;\n }\n}\n.Input-errors-uSM2i input {\n box-shadow: inset 0 0 0 2px #f0523d;\n}\n.Input-large-3nSsJ input {\n font-size: 16px;\n}\n.Input-readOnly-xm8xM input[type] {\n background: #e4e4e4;\n color: #797979;\n font-style: italic;\n}\n.Input-midnight-1pwjw input {\n background: transparent;\n color: #ffffff;\n width: 100%;\n border-bottom: 1px solid #797979;\n font-size: 16px;\n padding: 11px 0;\n font-weight: 400;\n}\n.Input-midnight-1pwjw input::-webkit-input-placeholder {\n color: #3e3e3e;\n}\n.Input-midnight-1pwjw input:-moz-placeholder {\n color: #3e3e3e;\n opacity: 1;\n}\n.Input-midnight-1pwjw input::-moz-placeholder {\n color: #3e3e3e;\n opacity: 1;\n}\n.Input-midnight-1pwjw input:-ms-input-placeholder {\n color: #3e3e3e;\n}\n.Input-midnight-1pwjw input:focus {\n border-color: #ffffff;\n}\n.Input-midnight-1pwjw.Input-errors-uSM2i input {\n box-shadow: none;\n border-color: #f0523d;\n}\n.Input-midnight-1pwjw .FieldLabel {\n visibility: hidden;\n}\n.Input-midnight-1pwjw.Input-hasValue-170L2 .FieldLabel {\n visibility: visible;\n}\n.Input-denarius-jjCTo {\n position: relative;\n}\n.Input-denarius-jjCTo .FieldLabel {\n font-size: 12px;\n position: absolute;\n top: 15px;\n left: 11px;\n color: #a1a1a1;\n font-weight: 300;\n}\n.Input-denarius-jjCTo.Input-hasValue-170L2 .FieldLabel,\n.Input-denarius-jjCTo.Input-focused-2BZMe .FieldLabel {\n font-size: 9px;\n float: left;\n font-weight: 500;\n text-transform: uppercase;\n position: absolute;\n top: 9px;\n left: 11px;\n color: #a1a1a1;\n letter-spacing: .4px;\n}\n.Input-denarius-jjCTo input {\n border: 1px solid #e4e4e4;\n border-radius: 3px;\n font-size: 12px;\n height: 44px;\n box-sizing: border-box;\n padding: 15px 9px 0px 9px;\n background: transparent;\n}\n.Input-denarius-jjCTo.Input-focused-2BZMe input {\n border-color: #a1a1a1;\n}\n.Input-denarius-jjCTo.Input-errors-uSM2i input {\n box-shadow: inset 0 0 0 2px #f0523d;\n -webkit-appearance: none;\n}\n.Input-denarius-jjCTo.Input-unlabeled-y18Hj input {\n font-size: 12px;\n padding-top: 0px;\n}\n.Input-denarius-jjCTo.Input-readOnly-xm8xM input[type] {\n background: transparent;\n font-style: normal;\n}\n", ""]);b.locals={container:"Input-container-1WRGR",errorMessage:"Input-errorMessage-1kTwU",childField:"Input-childField-ezAkI",inline:"Input-inline-15X5s",midnight:"Input-midnight-1pwjw",errors:"Input-errors-uSM2i",large:"Input-large-3nSsJ",readOnly:"Input-readOnly-xm8xM",hasValue:"Input-hasValue-170L2",denarius:"Input-denarius-jjCTo",focused:"Input-focused-2BZMe",unlabeled:"Input-unlabeled-y18Hj"}},function(c,b,a){b=a(589);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)}, function(c,b,a){b=a(590);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(252);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,,function(c,b,a){var e=a(38),f=a(322);c.exports=function(a){return function(b,c,k){c=e(c,k,3);return f(b,c,a,!0)}}},,function(c,b,a){b=a(1132)(!0);c.exports=b},,,,function(c,b){YUI.add("squarespace-model-sync-rest",function(a){function b(){this._ioConfigCache={}}b.prototype={sync:function(b, d,c){a.Lang.isValue(d.timeout)||(d.timeout=1E7);a.ModelSync.REST.prototype.sync.apply(this,arguments)},_storeRequest:function(b,d){this._ioConfigCache[b.id]=a.merge(d,{})},_retrieveAndEvict:function(a){var b=this._ioConfigCache[a];this._ioConfigCache[a]=null;return b},_isCrumbFailure:function(a){return a&&a.crumbFail&&a.crumb},_sendSyncIORequest:function(b){var d=a.ModelSync.REST.prototype._sendSyncIORequest.apply(this,arguments);this._storeRequest(d,b);return d},_onSyncIOEnd:function(b,d){this._retrieveAndEvict(b); a.ModelSync.REST.prototype._onSyncIOEnd.apply(this,arguments)},_onSyncIOSuccess:function(b,d,c){var e=this._retrieveAndEvict(b),k={},l=d.responseText;a.Lang.isValue(l)&&l.trim()&&(k=a.JSON.parse(l));this._isCrumbFailure(k)?(k=k.crumb,a.ModelSync.REST.CSRF_TOKEN=k,a.Env.CSRF_TOKEN=k,e.headers["X-CSRF-Token"]=k,this._sendSyncIORequest(e)):a.ModelSync.REST.prototype._onSyncIOSuccess.apply(this,arguments)},_onSyncIOFailure:function(b,d,c){if(b=c.callback){c={};var e=d.responseText;a.Lang.isValue(e)&& e.trim()&&(c=a.JSON.parse(e));b({code:d.status,msg:d.statusText,responseJSON:c},d)}}};a.mix(b,a.ModelSync.REST,!1,null,1);a.namespace("Squarespace.ModelSync").REST=b},"1.0",{requires:["model-sync-rest"]})},function(c,b){YUI.add("model-list",function(a,b){function c(){c.superclass.constructor.apply(this,arguments)}var d=a.Attribute.prototype,g=a.Lang,h=a.Array;a.ModelList=a.extend(c,a.Base,{model:a.Model,_isYUIModelList:!0,initializer:function(b){b||(b={});var d=this.model=b.model||this.model;"string"=== typeof d&&((this.model=a.Object.getValue(a,d.split(".")))||a.error("ModelList: Model class not found: "+d));this.publish("add",{defaultFn:this._defAddFn});this.publish("reset",{defaultFn:this._defResetFn});this.publish("remove",{defaultFn:this._defRemoveFn});this.after("*:idChange",this._afterIdChange);this._clear();b.items&&this.add(b.items,{silent:!0})},destructor:function(){this._clear()},add:function(b,d){var c=b._isYUIModelList;return c||g.isArray(b)?h.map(c?b.toArray():b,function(b,c){var f= d||{};"index"in f&&(f=a.merge(f,{index:f.index+c}));return this._add(b,f)},this):this._add(b,d)},create:function(b,d,c){var f=this;"function"===typeof d&&(c=d,d={});d||(d={});b._isYUIModel||(b=new this.model(b));f.fire("create",a.merge(d,{model:b}));return b.save(d,function(a){a||f.add(b,d);c&&c.apply(null,arguments)})},each:function(a,b){var d=this._items.concat(),c,f,e;c=0;for(e=d.length;c<e;c++)f=d[c],a.call(b||f,f,c,this);return this},filter:function(a,b){var d=[],c=this._items,f,e,g;"function"=== typeof a&&(b=a,a={});f=0;for(g=c.length;f<g;++f)e=c[f],b.call(this,e,f,this)&&d.push(e);return a.asList?(c=new this.constructor({model:this.model}),d.length&&c.add(d,{silent:!0}),c):d},get:function(a){return this.attrAdded(a)?d.get.apply(this,arguments):this.invoke("get",a)},getAsHTML:function(b){return this.attrAdded(b)?a.Escape.html(d.get.apply(this,arguments)):this.invoke("getAsHTML",b)},getAsURL:function(a){return this.attrAdded(a)?encodeURIComponent(d.get.apply(this,arguments)):this.invoke("getAsURL", a)},getByClientId:function(a){return this._clientIdMap[a]||null},getById:function(a){return this._idMap[a]||null},invoke:function(a){var b=[this._items,a].concat(h(arguments,1,!0));return h.invoke.apply(h,b)},load:function(a,b){var d=this;"function"===typeof a&&(b=a,a={});a||(a={});this.sync("read",a,function(c,f){var e={options:a,response:f},g;c?(e.error=c,e.src="load",d.fire("error",e)):(d._loadEvent||(d._loadEvent=d.publish("load",{preventable:!1})),g=e.parsed=d._parse(f),d.reset(g,a),d.fire("load", e));b&&b.apply(null,arguments)});return this},map:function(a,b){return h.map(this._items,a,b)},parse:function(b){if("string"===typeof b)try{return a.JSON.parse(b)||[]}catch(d){return this.fire("error",{error:d,response:b,src:"parse"}),null}return b||[]},remove:function(a,b){var d=a._isYUIModelList;return d||g.isArray(a)?(a=h.map(d?a.toArray():a,function(a){return g.isNumber(a)?this.item(a):a},this),h.map(a,function(a){return this._remove(a,b)},this)):this._remove(a,b)},reset:function(b,d){b||(b=[]); d||(d={});var c=a.merge({src:"reset"},d);b=b._isYUIModelList?b.toArray():h.map(b,function(a){return a._isYUIModel?a:new this.model(a)},this);c.models=b;d.silent?this._defResetFn(c):(this.comparator&&b.sort(a.bind(this._sort,this)),this.fire("reset",c));return this},some:function(a,b){var d=this._items.concat(),c,f,e;c=0;for(e=d.length;c<e;c++)if(f=d[c],a.call(b||f,f,c,this))return!0;return!1},sort:function(b){if(!this.comparator)return this;var d=this._items.concat();b||(b={});d.sort(a.rbind(this._sort, this,b));d=a.merge(b,{models:d,src:"sort"});b.silent?this._defResetFn(d):this.fire("reset",d);return this},sync:function(){var a=h(arguments,0,!0).pop();"function"===typeof a&&a()},toArray:function(){return this._items.concat()},toJSON:function(){return this.map(function(a){return a.toJSON()})},_add:function(b,d){var c;d||(d={});b._isYUIModel||(b=new this.model(b));c=b.get("id");if(this._clientIdMap[b.get("clientId")]||g.isValue(c)&&this._idMap[c])this.fire("error",{error:"Model is already in the list.", model:b,src:"add"});else return c=a.merge(d,{index:"index"in d?d.index:this._findIndex(b),model:b}),d.silent?this._defAddFn(c):this.fire("add",c),b},_attachList:function(a){a.lists.push(this);a.addTarget(this)},_clear:function(){h.each(this._items,this._detachList,this);this._clientIdMap={};this._idMap={};this._items=[]},_compare:function(a,b){return a<b?-1:a>b?1:0},_detachList:function(a){var b=h.indexOf(a.lists,this);-1<b&&(a.lists.splice(b,1),a.removeTarget(this))},_findIndex:function(a){var b= this._items,d=b.length,c=0,f,e;if(!this.comparator||!d)return d;for(e=this.comparator(a);c<d;)f=c+d>>1,a=b[f],0>this._compare(this.comparator(a),e)?c=f+1:d=f;return c},_parse:function(a){return this.parse(a)},_remove:function(b,d){var c;d||(d={});g.isNumber(b)?(c=b,b=this.item(c)):c=this.indexOf(b);if(-1===c||!b)this.fire("error",{error:"Model is not in the list.",index:c,model:b,src:"remove"});else return c=a.merge(d,{index:c,model:b}),d.silent?this._defRemoveFn(c):this.fire("remove",c),b},_sort:function(a, b,d){a=this._compare(this.comparator(a),this.comparator(b));return 0===a?a:d&&d.descending?-a:a},_afterIdChange:function(a){var b=a.newVal,d=a.prevVal;a=a.target;if(g.isValue(d))if(this._idMap[d]===a)delete this._idMap[d];else return;else if(-1===this.indexOf(a))return;g.isValue(b)&&(this._idMap[b]=a)},_defAddFn:function(a){var b=a.model,d=b.get("id");this._clientIdMap[b.get("clientId")]=b;g.isValue(d)&&(this._idMap[d]=b);this._attachList(b);this._items.splice(a.index,0,b)},_defRemoveFn:function(a){var b= a.model,d=b.get("id");this._detachList(b);delete this._clientIdMap[b.get("clientId")];g.isValue(d)&&delete this._idMap[d];this._items.splice(a.index,1)},_defResetFn:function(a){"sort"===a.src?this._items=a.models.concat():(this._clear(),a.models.length&&this.add(a.models,{silent:!0}))}},{NAME:"modelList"});a.augment(c,a.ArrayList)},"3.17.2",{requires:"array-extras array-invoke arraylist base-build escape json-parse model".split(" ")})},function(c,b){YUI.add("model-sync-rest",function(a,b){function c(){} var d=a.Lang;c.CSRF_TOKEN=YUI.Env.CSRF_TOKEN;c.EMULATE_HTTP=!1;c.HTTP_HEADERS={Accept:"application/json","Content-Type":"application/json"};c.HTTP_METHODS={create:"POST",read:"GET",update:"PUT","delete":"DELETE"};c.HTTP_TIMEOUT=3E4;c._NON_ATTRS_CFG=["root","url"];c.prototype={root:"",url:"",initializer:function(a){a||(a={});"root"in a&&(this.root=a.root||"");"url"in a&&(this.url=a.url||"")},getURL:function(b,d){var c=this.root,f=this.url;return this._isYUIModelList?!f?this.model.prototype.root:this._substituteURL(f, a.merge(this.getAttrs(),d)):c&&("create"===b||this.isNew())?c:!f?this._joinURL(this.getAsURL("id")||""):this._substituteURL(f,a.merge(this.getAttrs(),d))},parseIOResponse:function(a){return a.responseText},serialize:function(b){return a.JSON.stringify(this)},sync:function(b,d,e){d||(d={});var l=this.getURL(b,d),m=c.HTTP_METHODS[b],n=a.merge(c.HTTP_HEADERS,d.headers),s=d.timeout||c.HTTP_TIMEOUT;d=d.csrfToken||c.CSRF_TOKEN;var q;"POST"===m||"PUT"===m?q=this.serialize(b):delete n["Content-Type"];if(c.EMULATE_HTTP&& ("PUT"===m||"DELETE"===m))n["X-HTTP-Method-Override"]=m,m="POST";if(d&&("POST"===m||"PUT"===m||"DELETE"===m))n["X-CSRF-Token"]=d;this._sendSyncIORequest({action:b,callback:e,entity:q,headers:n,method:m,timeout:s,url:l})},_joinURL:function(a){var b=this.root;if(!b&&!a)return"";"/"===a.charAt(0)&&(a=a.substring(1));return b&&"/"===b.charAt(b.length-1)?b+a+"/":b+"/"+a},_parse:function(a){"function"===typeof this.parseIOResponse&&(a=this.parseIOResponse(a));return this.parse(a)},_sendSyncIORequest:function(b){return a.io(b.url, {arguments:{action:b.action,callback:b.callback,url:b.url},context:this,data:b.entity,headers:b.headers,method:b.method,timeout:b.timeout,on:{start:this._onSyncIOStart,failure:this._onSyncIOFailure,success:this._onSyncIOSuccess,end:this._onSyncIOEnd}})},_substituteURL:function(b,c){if(!b)return"";var f={};a.Object.each(c,function(a,b){if(d.isString(a)||d.isNumber(a))f[b]=encodeURIComponent(a)});return d.sub(b,f)},_onSyncIOEnd:function(a,b){},_onSyncIOFailure:function(a,b,d){(a=d.callback)&&a({code:b.status, msg:b.statusText},b)},_onSyncIOSuccess:function(a,b,d){(a=d.callback)&&a(null,b)},_onSyncIOStart:function(a,b){}};a.namespace("ModelSync").REST=c},"3.17.2",{requires:["model","io-base","json-stringify"]})},,function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(11),g=a(2);b=g.PropTypes;var h=a(41),k=a(37),l=a(93),m=a(818);a=g.createClass({displayName:"Range",mixins:[h],propTypes:{errorMessage:b.string,label:b.string,max:b.number,min:b.number,step:b.number, onChange:b.func.isRequired,value:b.number.isRequired,parseValue:b.func,renderValue:b.oneOfType([b.bool,b.func]),labelWidth:b.number},getDefaultProps:function(){return{min:0,max:100,step:1,parseValue:function(a){return parseFloat(a)},renderValue:function(a){return a},labelWidth:3*l.globalGrid}},handleChange:function(a){var b=this.props,d=b.parseValue,b=b.onChange;a.target={value:d(a.target.value)};b(a)},render:function(){var a,b=this.props,c=b.errorMessage,h=b.label,l=b.className,p=b.renderValue,u= b.value,v=b.labelWidth,b=(0,f.default)(b,"errorMessage label className renderValue value labelWidth".split(" ")),l=d(m.field,l,(a={},a[m.hasValueDisplay]=p,a));a=p?{marginLeft:v}:null;return g.createElement(k,{errorMessage:c,label:h,className:l},p&&g.createElement("div",{className:m.valueContainer,style:{width:v}},p(u)),g.createElement("div",{className:m.inputContainer,style:a},g.createElement("input",(0,e.default)({},b,{value:u,onChange:this.handleChange,type:"range",className:m.input}))))}});c.exports= a},,function(c,b){c.exports={UNKNOWN:1,GO_DADDY:2,GOOGLE:3,OPEN_SRS:4,NAMECHEAP:5,ENOM:6,NETWORK_SOLUTIONS:7,DREAMHOST:8,BLUEHOST:9,I_WANT_MY_NAME:10,NAME_COM:11,HOVER:12,DOMAINS101:13,ONE_AND_ONE:14,DOTSTER:15,DYN_AND_NETTICA:16,DYNADOT:17,EASY_DNS:18,REGISTER_COM:19,WORDPRESS:20,YAHOO:21}},,,,,function(c,b,a){b=a(160);var e=Object.prototype.hasOwnProperty;b=b(function(a,b,c){e.call(a,c)?a[c].push(b):a[c]=[b]});c.exports=b},function(c,b,a){var e=a(440),f=Number.POSITIVE_INFINITY;c.exports=function(a){return e(a, f)}},function(c,b,a){var e=a(38),f=a(259),d=a(443),g=a(868),h=a(39);c.exports=function(a,b,c){if(null==a)return[];c&&h(a,b,c)&&(b=void 0);var n=-1;b=e(b,c,3);a=f(a,function(a,d,c){return{criteria:b(a,d,c),index:++n,value:a}});return d(a,g)}},,function(c,b,a){b=a(984)(function(a,b,d){return a+(d?"-":"")+b.toLowerCase()});c.exports=b},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b,a){b=a(9);c.exports=b.generateActions("show","frameLoaded","closeFrame", "showLoading")},function(c,b,a){function e(a,b){var d=m;!b.height&&!b.width&&(d=n);return(0,f.default)({},d,l,a)}var f=(b=a(16))&&b.__esModule?b:{"default":b},d=a(785);a=a(234);var g=a.toStyleCoords,h=a.constrainToWindow,k=a.positions,l={padding:0,constrain:"window"},m={join:k.TOP_LEFT,to:k.TOP_RIGHT},n={join:k.CENTER_CENTER,to:k.CENTER_CENTER},s=function(a,b){switch(a){case "center":return n;case "right":return{join:k.TOP_LEFT,to:k.TOP_RIGHT};case "left":return{join:k.TOP_RIGHT,to:k.TOP_LEFT};case "bottom":return{join:k.TOP_CENTER, to:k.BOTTOM_CENTER};case "top":return{join:k.BOTTOM_CENTER,to:k.TOP_CENTER};case "window":return e(a,b);default:return e(a,b)}};c.exports={alignNodes:function(a,b){var c=2>=arguments.length||void 0===arguments[2]?l:arguments[2],c=s(c,new d(b));c.padding&&(c.offsetX=c.padding,c.offsetY=c.padding);var f=new d(b),e=new d(a,c),c=e.getJoinPoint(f,c);return g(h(c,e))}}},function(c,b,a){var e=a(2),f=a(11),d=a(815);b=e.PropTypes;b=e.createClass({displayName:"ProgressBar",propTypes:{progress:b.number.isRequired, delay:b.number.isRequired},getDefaultProps:function(){return{delay:500}},getInitialState:function(){return{visible:0===this.props.delay}},componentDidMount:function(){0<this.props.delay&&this.initDelayTimeout()},componentWillUnmount:function(){this.delayTimer&&clearTimeout(this.delayTimer)},initDelayTimeout:function(){var a=this;this.delayTimer=setTimeout(function(){a.setState({visible:!0})},this.props.delay)},render:function(){var a={width:this.props.progress+"%"};return!this.state.visible?null: e.createElement("div",{className:f(this.props.className,d.container)},e.createElement("div",{className:d.inner,style:a}))}});c.exports=b},function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11);b=a(28);var h=a(37),k=a(819),l=a(275);a=d.createClass({displayName:"TextArea",propTypes:{className:d.PropTypes.string,errorClassName:d.PropTypes.string,errorMessage:d.PropTypes.string,hasErrors:d.PropTypes.bool,label:d.PropTypes.string,maxLength:d.PropTypes.number, maxRows:d.PropTypes.number,minRows:d.PropTypes.number,placeholder:d.PropTypes.string,readOnly:d.PropTypes.bool,theme:b.isRequired,value:d.PropTypes.string},getDefaultProps:function(){return{theme:"damask",maxLength:1E4,maxRows:10,minRows:2,readOnly:!1}},getInitialState:function(){return{maxHeight:Number.MAX_VALUE,minHeight:0}},componentDidMount:function(){this.measureMinMaxHeight()},componentDidUpdate:function(a){var b=this.props,d=b.minRows;a.maxRows===b.maxRows&&a.minRows===d||this.measureMinMaxHeight()}, measureMinMaxHeight:function(){var a=this.props,b=a.maxRows,d=a.minRows,c=this.state,a=c.maxHeight,c=c.minHeight,f=window.getComputedStyle(this.refs.sizingHelper),e=parseFloat(f.paddingTop)+parseFloat(f.paddingBottom)+parseFloat(f.borderTopWidth)+parseFloat(f.borderBottomWidth),f=parseFloat(f.lineHeight),b=b*f+e,d=d*f+e;b===a&&d===c||this.setState({maxHeight:b,minHeight:d})},render:function(){var a,b=this.props,c=b.children,q=b.className,r=b.errorClassName,t=b.errorMessage,p=b.hasErrors,u=b.readOnly, v=b.label,x=b.placeholder,w=b.theme,y=b.value,b=(0,f.default)(b,"children className errorClassName errorMessage hasErrors readOnly label placeholder theme value".split(" ")),B=this.state,A=B.maxHeight,B=B.minHeight,q=g(q,"sqs-text",k[w],(a={"has-errors":t||p},a[k.errors]=t||p,a[k.readOnly]=u,a[k.hasValue]=!!y,a));a=!y||y.lastIndexOf("\n")===y.length-1?(y||"")+"&nbsp;":y;return d.createElement(h,{label:v,className:q,errorClassName:r,errorMessage:t,theme:w},d.createElement("div",{className:k.wrapper}, d.createElement("textarea",(0,e.default)({className:l.formField},b,{autoCapitalize:"sentences",autoCompplete:"off",placeholder:x,readOnly:u,spellCheck:!0,value:y})),d.createElement("div",{className:g(l.formField,k.sizingHelper),style:{maxHeight:A,minHeight:B},ref:"sizingHelper"},a)),c&&d.createElement("div",{className:"description"},c))}});c.exports=a},function(c,b,a){var e=a(2),f=a(11),d=a(37),g=a(820);b=e.createClass({displayName:"Toggle",propTypes:{errorMessage:e.PropTypes.string,label:e.PropTypes.string, offLabel:e.PropTypes.string,onChange:e.PropTypes.func.isRequired,onLabel:e.PropTypes.string,value:e.PropTypes.bool,size:e.PropTypes.oneOf(["large","small"])},getDefaultProps:function(){return{value:!1,onLabel:"On",offLabel:"Off",size:"large"}},handleChange:function(){var a=this.props,b=a.onChange;b({target:{value:!a.value}})},render:function(){var a,b=this.props,c=b.value,m=b.errorMessage,n=b.label,s=b.onLabel,q=b.offLabel,r=b.className,b=b.size,c=f(g.container,g.animate,(a={},a[g.active]=c,a[g.inactive]= !c,a[g.small]="small"===b,a));return e.createElement(d,{errorMessage:m,label:n,onClick:this.handleChange,className:r},e.createElement("div",{className:c},e.createElement("div",{className:g.switchBox},e.createElement("div",{className:g.toggleBox},e.createElement("div",{className:g.toggleBackground},e.createElement("div",{className:g.on},s),e.createElement("div",{className:g.off},q)))),e.createElement("div",{className:g.switchShadow},"\u00a0"),e.createElement("div",{className:g.handleWrapper},e.createElement("div", {className:g.handle},"\u00a0"))))}});c.exports=b},function(c,b){c.exports={GIVEN_NAME:"given-name",FAMILY_NAME:"family-name",CITY:"city",STATE:"state",POSTAL_CODE:"postal-code",COUNTRY_NAME:"country-name",CC_FULL_NAME:"cc-full-name",CC_NUMBER:"cc-number",CC_EXP_MOTNH:"cc-exp-month",CC_EXP_YEAR:"cc-exp-year",CC_CSC:"cc-csc"}},,,,,,,,,,,function(c,b,a){c.exports={"default":a(724),__esModule:!0}},function(c,b,a){a(274);a(251);c.exports=a(728)},function(c,b,a){a(274);a(251);c.exports=a(729)},,,,function(c, b,a){var e=a(138),f=a(767);c.exports=a(31).getIterator=function(a){var b=f(a);if("function"!=typeof b)throw TypeError(a+" is not iterable!");return e(b.call(a))}},function(c,b,a){var e=a(587),f=a(127)("iterator"),d=a(344);c.exports=a(31).isIterable=function(a){a=Object(a);return void 0!==a[f]||"@@iterator"in a||d.hasOwnProperty(e(a))}},function(c,b,a){b=c.exports=a(3)();b.i(a(175),void 0);b.push([c.id,".LoadingSpinner-spinner-1Bk2i {\n background-color: transparent;\n border-radius: 150px;\n display: inline-block;\n vertical-align: middle;\n}\n.LoadingSpinner-centered-27_mv {\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n.LoadingSpinner-light-2mjBq {\n border: 2px solid rgba(255, 255, 255, 0.7);\n border-top-color: rgba(255, 255, 255, 0.15);\n border-left-color: rgba(255, 255, 255, 0.15);\n}\n.LoadingSpinner-dark-R3LeZ {\n border: 2px solid rgba(0, 0, 0, 0.75);\n border-top-color: rgba(0, 0, 0, 0.08);\n border-left-color: rgba(0, 0, 0, 0.08);\n}\n.LoadingSpinner-extra-small-1F_Ca {\n width: 4px;\n height: 4px;\n}\n.LoadingSpinner-small-3XxlY {\n width: 8px;\n height: 8px;\n}\n.LoadingSpinner-default-394l4 {\n width: 12px;\n height: 12px;\n}\n.LoadingSpinner-large-NDb81 {\n width: 22px;\n height: 22px;\n}\n.LoadingSpinner-extra-large-2Dohj {\n width: 40px;\n height: 40px;\n}\n.LoadingSpinner-xx-large-3V4Ou {\n width: 80px;\n height: 80px;\n}\n", ""]);b.locals={spinner:"LoadingSpinner-spinner-1Bk2i "+a(175).locals.spin+"",centered:"LoadingSpinner-centered-27_mv",light:"LoadingSpinner-light-2mjBq",dark:"LoadingSpinner-dark-R3LeZ","extra-small":"LoadingSpinner-extra-small-1F_Ca",small:"LoadingSpinner-small-3XxlY","default":"LoadingSpinner-default-394l4",large:"LoadingSpinner-large-NDb81","extra-large":"LoadingSpinner-extra-large-2Dohj","xx-large":"LoadingSpinner-xx-large-3V4Ou"}},function(c,b,a){b=c.exports=a(3)();b.i(a(24),void 0);b.push([c.id, "@-webkit-keyframes shiver {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 25% {\n -webkit-transform: translateX(11px);\n transform: translateX(11px);\n }\n 75% {\n -webkit-transform: translateX(-11px);\n transform: translateX(-11px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@keyframes shiver {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 25% {\n -webkit-transform: translateX(11px);\n transform: translateX(11px);\n }\n 75% {\n -webkit-transform: translateX(-11px);\n transform: translateX(-11px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@-webkit-keyframes shimmy {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 50% {\n -webkit-transform: translateX(-33px);\n transform: translateX(-33px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@keyframes shimmy {\n from {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n 50% {\n -webkit-transform: translateX(-33px);\n transform: translateX(-33px);\n }\n to {\n -webkit-transform: translateX(0px);\n transform: translateX(0px);\n }\n}\n@-webkit-keyframes spin {\n from {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes spin {\n from {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@-webkit-keyframes bounceIn {\n 0% {\n opacity: 0;\n -webkit-transform: scale(0.3);\n transform: scale(0.3);\n }\n 50% {\n opacity: 1;\n -webkit-transform: scale(1.05);\n transform: scale(1.05);\n }\n 70% {\n -webkit-transform: scale(0.9);\n transform: scale(0.9);\n }\n 100% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}\n@keyframes bounceIn {\n 0% {\n opacity: 0;\n -webkit-transform: scale(0.3);\n transform: scale(0.3);\n }\n 50% {\n opacity: 1;\n -webkit-transform: scale(1.05);\n transform: scale(1.05);\n }\n 70% {\n -webkit-transform: scale(0.9);\n transform: scale(0.9);\n }\n 100% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}\n@-webkit-keyframes pulseBadgeOpacity {\n 0% {\n opacity: 1;\n }\n 85% {\n opacity: .6;\n }\n 100% {\n opacity: 1;\n }\n}\n@keyframes pulseBadgeOpacity {\n 0% {\n opacity: 1;\n }\n 85% {\n opacity: .6;\n }\n 100% {\n opacity: 1;\n }\n}\n@-webkit-keyframes fadeout {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n}\n@keyframes fadeout {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n}\n@-webkit-keyframes riseandfadein {\n 0% {\n -webkit-transform: translateY(22px);\n transform: translateY(22px);\n opacity: 0;\n }\n 100% {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n opacity: 1;\n }\n}\n@keyframes riseandfadein {\n 0% {\n -webkit-transform: translateY(22px);\n transform: translateY(22px);\n opacity: 0;\n }\n 100% {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n opacity: 1;\n }\n}\n/**\n * Jiggles the container back and forth slowly. Used to draw attention of a user\n * back to the item. For instance, if a user attempts to click out of a modal\n * that is not completed.\n */\n.Check-shake-2BDTs {\n -webkit-animation-name: shiver;\n animation-name: shiver;\n -webkit-animation-duration: 0.2s;\n animation-duration: 0.2s;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n/**\n * Shake the item back and forth very quickly. Used to indicate that an action\n * is improper or impossible, such as saving a form with errors or deleting an\n * item without sufficient permissions.\n */\n.Check-shiver-2R9C_ {\n -webkit-animation-name: shiver;\n animation-name: shiver;\n -webkit-animation-duration: 0.1s;\n animation-duration: 0.1s;\n -webkit-animation-iteration-count: 2;\n animation-iteration-count: 2;\n -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n/**\n * Gently rocks the animated item to the left. Used to gently remind the user\n * that an action cannot happen, such as when reaching the end of a list, or\n * trying slide something farther than it can go.\n */\n.Check-shimmy-XvWYc {\n -webkit-animation-name: shimmy;\n animation-name: shimmy;\n -webkit-animation-duration: 0.3s;\n animation-duration: 0.3s;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n/**\n * Spin your heart out!\n */\n.Check-spin-3_0d- {\n -webkit-animation-name: spin;\n animation-name: spin;\n -webkit-animation-duration: 1s;\n animation-duration: 1s;\n -webkit-animation-iteration-count: infinite;\n animation-iteration-count: infinite;\n -webkit-animation-timing-function: linear;\n animation-timing-function: linear;\n}\n.Check-pulseBadgeOpacity-1ACuk {\n -webkit-animation-name: pulseBadgeOpacity;\n animation-name: pulseBadgeOpacity;\n -webkit-animation-duration: 4s;\n animation-duration: 4s;\n -webkit-animation-iteration-count: infinite;\n animation-iteration-count: infinite;\n -webkit-animation-timing-function: ease-in-out;\n animation-timing-function: ease-in-out;\n}\n.Check-fadeout-3mN-O {\n -webkit-animation-name: fadeout;\n animation-name: fadeout;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n}\n.Check-fadein-1T0AW {\n -webkit-animation-name: fadein;\n animation-name: fadein;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n}\n.Check-riseandfadein-66XVH {\n -webkit-animation-name: riseandfadein;\n animation-name: riseandfadein;\n -webkit-animation-iteration-count: 1;\n animation-iteration-count: 1;\n}\n.Check-checkElement-1p4iW {\n cursor: pointer;\n padding-left: 33px;\n position: relative;\n}\n.Check-checkElement-1p4iW:before {\n border: 2px solid rgba(121, 121, 121, 0.2);\n border-radius: 50%;\n box-sizing: border-box;\n content: ' ';\n display: block;\n height: 22px;\n left: 0;\n position: absolute;\n top: 0;\n transition: border-color 0.1s ease-in-out;\n width: 22px;\n z-index: 1;\n}\n.Check-checkElement-1p4iW:hover:before {\n border-color: rgba(121, 121, 121, 0.5);\n}\n.Check-checkElement-1p4iW.Check-active-1qgj6:before {\n border-color: #3e3e3e;\n}\n.Check-checkElement-1p4iW:after {\n background-size: 9px;\n border-radius: 50%;\n box-sizing: border-box;\n content: ' ';\n display: block;\n height: 22px;\n left: 0;\n position: absolute;\n top: 0;\n -webkit-transform: scale(0);\n -ms-transform: scale(0);\n transform: scale(0);\n width: 22px;\n z-index: 2;\n}\n.Check-checkElement-1p4iW.Check-active-1qgj6:after {\n opacity: 1;\n -webkit-animation-name: bounceIn;\n animation-name: bounceIn;\n -webkit-animation-duration: 0.4s;\n animation-duration: 0.4s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n -webkit-animation-iteration-count: once;\n animation-iteration-count: once;\n transition: background-color 0.2s ease-in-out;\n}\n.Check-checkElement-1p4iW.Check-active-1qgj6:hover:after {\n background-color: black;\n}\n.Check-checkElement-1p4iW.Check-isDisabled-2RIyG,\n.Check-checkElement-1p4iW.Check-isDisabled-2RIyG:hover {\n cursor: default;\n opacity: 0.6;\n}\n.Check-checkElement-1p4iW.Check-isDisabled-2RIyG:hover:before {\n border-color: rgba(121, 121, 121, 0.2);\n}\n.Check-checkElement-1p4iW.Check-isDisabled-2RIyG:hover:after {\n background-color: #3e3e3e;\n}\n", ""]);b.locals={shake:"Check-shake-2BDTs",shiver:"Check-shiver-2R9C_",shimmy:"Check-shimmy-XvWYc",spin:"Check-spin-3_0d-",pulseBadgeOpacity:"Check-pulseBadgeOpacity-1ACuk",fadeout:"Check-fadeout-3mN-O",fadein:"Check-fadein-1T0AW",riseandfadein:"Check-riseandfadein-66XVH",checkElement:"Check-checkElement-1p4iW "+a(24).locals.checkAfter+"",active:"Check-active-1qgj6",isDisabled:"Check-isDisabled-2RIyG"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".RadioGroup-option-prs8Y {\n position: relative;\n cursor: pointer;\n font-weight: 500;\n display: block;\n}\n.RadioGroup-option-prs8Y.RadioGroup-isDisabled-2qKdv {\n cursor: default;\n opacity: 0.6;\n}\n.RadioGroup-option-prs8Y:not(:first-child) {\n margin-top: 20px;\n}\n.RadioGroup-option-prs8Y input[type=radio] {\n opacity: 0;\n position: absolute;\n left: 0;\n top: 0;\n}\n.RadioGroup-option-prs8Y input[type=radio] + div {\n padding-left: 33px;\n display: block;\n}\n.RadioGroup-option-prs8Y input[type=radio] + div:before {\n height: 22px;\n width: 22px;\n position: absolute;\n left: 0;\n right: 0;\n content: ' ';\n display: inline-block;\n border: 2px solid rgba(121, 121, 121, 0.2);\n border-radius: 50%;\n box-sizing: border-box;\n transition: border-color 0.1s ease-in-out;\n}\n.RadioGroup-option-prs8Y input[type=radio] + div:hover:before {\n border-color: rgba(121, 121, 121, 0.5);\n}\n.RadioGroup-option-prs8Y input[type=radio]:checked + div:before {\n border: 8px solid #3e3e3e;\n -webkit-animation-name: bounceIn;\n animation-name: bounceIn;\n -webkit-animation-duration: 0.4s;\n animation-duration: 0.4s;\n -webkit-animation-iteration-count: once;\n animation-iteration-count: once;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n}\n.RadioGroup-option-prs8Y input[type=radio]:checked + div:hover:before {\n border-color: black;\n}\n", ""]);b.locals={option:"RadioGroup-option-prs8Y",isDisabled:"RadioGroup-isDisabled-2qKdv"}},function(c,b,a){b=c.exports=a(3)();b.i(a(24),void 0);b.push([c.id,".Search-container-1bUhB {\n position: relative;\n}\n.Search-searchInput-1AY9F {\n background-color: #fff;\n background-position: 11px center;\n border: none;\n box-sizing: border-box;\n color: #3e3e3e;\n cursor: auto;\n height: 44px;\n padding: 11px 44px;\n position: relative;\n width: 100%;\n}\n.Search-searchInput-1AY9F::-ms-clear {\n display: none;\n}\n.Search-searchInput-1AY9F.Search-hiddenSearchIcon-3HpFL {\n padding-left: 11px;\n}\n.Search-searchIcon-21IJS {\n position: absolute;\n width: 22px;\n height: 22px;\n top: 11px;\n left: 11px;\n cursor: default;\n}\n.Search-btnClear-2WDG5 {\n position: absolute;\n right: 0;\n bottom: 0;\n height: 44px;\n width: 44px;\n text-indent: -9000px;\n transition: opacity 0.3s ease-in-out;\n}\n.Search-btnClear-2WDG5:hover {\n opacity: 1;\n}\n.Search-btnClear-2WDG5.Search-hidden-3KXFj {\n cursor: default;\n opacity: 0;\n}\n.Search-hasErrors-2LXAK .Search-searchInput-1AY9F {\n box-shadow: inset 0 0 0 2px #f0523d;\n}\n", ""]);b.locals={container:"Search-container-1bUhB",searchInput:"Search-searchInput-1AY9F",hiddenSearchIcon:"Search-hiddenSearchIcon-3HpFL",searchIcon:"Search-searchIcon-21IJS "+a(24).locals.search+"",btnClear:"Search-btnClear-2WDG5 "+a(24).locals.clear+"",hidden:"Search-hidden-3KXFj",hasErrors:"Search-hasErrors-2LXAK"}},function(c,b,a){b=a(730);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(731);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{}); b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(732);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(733);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,,function(c,b,a){b=a(160)(function(a,b,d){a[d]=b});c.exports=b},function(c,b,a){(function(b){function f(a){var b=a?a.length:0;for(this.data={hash:k(null),set:new h};b--;)this.push(a[b])}var d=a(745),g=a(300),h=g(b,"Set"),k=g(Object,"create");f.prototype.push= d;c.exports=f}).call(b,function(){return this}())},,function(c,b,a){var e=a(70);c.exports=function(a){var b=this.data;"string"==typeof a||e(a)?b.set.add(a):b.hash[a]=!0}},function(c,b){c.exports=function(a,b,c){var d=a.length;for(b+=c?0:-1;c?b--:++b<d;){var g=a[b];if(g!==g)return b}return-1}},function(c,b,a){b=a(224);a=a(598)(b);c.exports=a},function(c,b,a){(function(a){(function(){var b,d,g;"undefined"!==typeof performance&&null!==performance&&performance.now?c.exports=function(){return performance.now()}: "undefined"!==typeof a&&null!==a&&a.hrtime?(c.exports=function(){return(b()-g)/1E6},d=a.hrtime,b=function(){var a;a=d();return 1E9*a[0]+a[1]},g=b()):Date.now?(c.exports=function(){return Date.now()-g},g=Date.now()):(c.exports=function(){return(new Date).getTime()-g},g=(new Date).getTime())}).call(this)}).call(b,a(530))},,,,,,,,,,,,,function(c,b){c.exports={APPROVED:1,AWAITING_MODERATION:2,DELETED:3,SPAM:4,POSSIBLY_SPAM:5}},,,,,,,function(c,b,a){var e=a(148),f=Array.prototype.splice;c.exports=function(){var a= arguments,b=a[0];if(!b||!b.length)return b;for(var c=0,k=a.length;++c<k;)for(var l=0,m=a[c];-1<(l=e(b,m,l));)f.call(b,l,1);return b}},function(c,b,a){var e=a(65),f=a(555);b=a(56)(function(a){return f(e(a,!1,!0))});c.exports=b},function(c,b,a){b=a(160)(function(a,b,d){a[d?0:1].push(b)},function(){return[[],[]]});c.exports=b},,function(c,b){var a=Math.floor,e=Math.random;c.exports=function(b,d){return b+a(e()*(d-b+1))}},function(c,b,a){c.exports=a(881)},function(c,b){YUI.add("squarespace-dialog-check-template", function(a){var b=a.Handlebars;(function(){var a=b.template;(b.templates=b.templates||{})["dialog-check.html"]=a(function(a,b,c,f,e){this.compilerInfo=[4,">= 1.0.0"];c=this.merge(c,a.helpers);e=e||{};var m,n=this.escapeExpression;a='<div class="check-element ';if((f=c["if"].call(b,b.data,{hash:{},inverse:this.noop,fn:this.program(1,function(a,b){return"active"},e),data:e}))||0===f)a+=f;a+='">\n ';if((m=c["if"].call(b,(f=b.strings,null==f||!1===f?f:f.title),{hash:{},inverse:this.noop,fn:this.program(3, function(a,b){var d,c;return d=""+('\n <div class="title">'+n((c=(c=a.strings,null==c||!1===c?c:c.title),"function"===typeof c?c.apply(a):c))+"</div>\n ")},e),data:e}))||0===m)a+=m;a+="\n ";if((m=c["if"].call(b,(f=b.strings,null==f||!1===f?f:f.description),{hash:{},inverse:this.noop,fn:this.program(5,function(a,b){var d,c,f;d='\n <div class="description">';if((f=(c=(c=a.strings,null==c||!1===c?c:c.description),"function"===typeof c?c.apply(a):c))||0===f)d+=f;return d+"</div>\n "},e),data:e}))|| 0===m)a+=m;return a+"\n</div>\n"})})();a.Handlebars.registerPartial("dialog-check.html".replace("/","."),b.templates["dialog-check.html"])},"1.0",{requires:["handlebars-base"]})},,,,,,function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2);a=d.createClass({displayName:"FileDropZone",propTypes:{onDrop:d.PropTypes.func.isRequired,validMimeTypes:d.PropTypes.array},filterValidTypes:function(a){var b=this.props.validMimeTypes;return!b?Array.prototype.slice.call(a, 0):Array.prototype.reduce.call(a,function(a,d){-1<b.indexOf(d.type)&&a.push(d);return a},[])},handleDrag:function(a){0<this.filterValidTypes(a.dataTransfer.items).length&&(a.preventDefault(),a.dataTransfer.effectAllowed="copy",a.dataTransfer.dropEffect="copy")},handleDrop:function(a){var b=this.filterValidTypes(a.dataTransfer.files);0<b.length&&(a.preventDefault(),a.stopPropagation(),this.props.onDrop(b))},render:function(){var a=this.props,b=a.children,a=(0,f.default)(a,["children"]);delete a.onDrop; return d.createElement("div",(0,e.default)({onDragEnter:this.handleDrag,onDragOver:this.handleDrag,onDrop:this.handleDrop},a),b)}});c.exports=a},function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11),h=a(810);a=d.createClass({displayName:"Body",render:function(){var a=this.props,b=a.className,c=a.children,a=(0,f.default)(a,["className","children"]),b=g(h.body,b);return d.createElement("div",(0,e.default)({className:b},a),c)}});c.exports= a},function(c,b,a){var e=(b=a(13))&&b.__esModule?b:{"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(11),g=a(2),h=a(811);a=g.createClass({displayName:"ModalButton",propTypes:{danger:g.PropTypes.bool},render:function(){var a=this.props,b=a.danger,c=a.children,n=a.className,a=(0,f.default)(a,["danger","children","className"]),n=d(h[b?"caution":"standard"],n);return g.createElement("button",(0,e.default)({},a,{className:n}),c)}});c.exports=a},function(c,b,a){var e=(b=a(13))&&b.__esModule?b: {"default":b},f=(b=a(18))&&b.__esModule?b:{"default":b},d=a(2),g=a(11);b=a(28);var h=a(812);a=d.createClass({displayName:"Footer",propTypes:{style:d.PropTypes.object,theme:b.isRequired},getDefaultProps:function(){return{style:null,theme:"damask"}},render:function(){var a=this.props,b=a.style,c=a.className,n=a.theme,a=(0,f.default)(a,["style","className","theme"]),c=g([h.footer,h[n],c]);return d.createElement("div",(0,e.default)({className:c,style:b},a),this.props.children)}});c.exports=a},function(c, b,a){var e=a(2),f=a(11),d=a(813);b=e.createClass({displayName:"Title",render:function(){var a=f(d.header,this.props.className);return e.createElement("div",{className:a},this.props.children)}});c.exports=b},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(4);var f=e(b);b=a(7);var d=e(b);b=a(16);var g=e(b);a=a(234);var h=a.constrainToWindow,k=a.translatePointToCorner,l=a.translateJoinOffset;a=function(){function a(b){var d=1>=arguments.length||void 0===arguments[1]?{}:arguments[1]; (0,f.default)(this,a);this.setProps(b,d);this.setOptions(d)}(0,d.default)(a,[{key:"setProps",value:function(a){var b={};("window"===a||a===window)&&console.warn("[Region] window is not a supported anchor type.");"mousepointer"===a?(a=window.Y.Squarespace.Mouse,b={height:0,width:0,x:a.lastX,y:a.lastY}):a instanceof Node||a instanceof Object&&a.nodeType?(b=a.getBoundingClientRect(),b={x:b.left,y:b.top,width:a.offsetWidth,height:a.offsetHeight}):a instanceof Object&&a.hasOwnProperty("top")&&a.hasOwnProperty("left")? b={x:a.left,y:a.top,height:a.height||0,width:a.width||0}:console.warn("[Region] Unrecognized anchor type; returning (0, 0)");a=(0,g.default)({height:0,width:0,x:0,y:0},b);var b=a.width,d=a.x,c=a.y;this.height=a.height;this.width=b;this.y=c;this.x=d}},{key:"setOptions",value:function(a){var b=a.offsetX;this.offsetY=a.offsetY||0;this.offsetX=b||0}},{key:"getDimensions",value:function(){return{width:this.width,height:this.height}}},{key:"getPoint",value:function(){return{x:this.x,y:this.y}}},{key:"constrain", value:function(a,b){"window"===(2>=arguments.length||void 0===arguments[2]?"window":arguments[2])?h(a,b):console.warn("[NormalizedRegion] Unsupported Container")}},{key:"getJoinPoint",value:function(b,d){var c=l({offsetX:this.offsetX,offsetY:this.offsetY},d.join),f=c.offsetX,c=c.offsetY;b instanceof a||(b=new a(b));var e=k(b.getPoint(),b.getDimensions(),d.to),g=k({x:0,y:0},this.getDimensions(),d.join);return{x:e.x-g.x+f,y:e.y-g.y+c}}},{key:"toJS",value:function(){return{x:this.x,y:this.y,width:this.width, height:this.height}}}]);return a}();c.exports=a},,function(c,b,a){var e=(b=a(18))&&b.__esModule?b:{"default":b},f=a(2),d=a(11),g=a(37),h=a(780),k=a(708),l=a(816);a=f.PropTypes;a=f.createClass({displayName:"File",propTypes:{title:a.string,label:a.string,file:a.object,percentUploaded:a.number,filePreviewRenderer:a.func,onCancelClick:a.func.isRequired,onFileSelected:a.func.isRequired,validMimeTypes:a.array},getInitialState:function(){return{file:this.props.file||null}},componentWillReceiveProps:function(a){this.setState({file:a.file})}, handleDrop:function(a){this.props.onFileSelected(a.slice(0,1));this.setState({file:a[0]})},handleChange:function(a){a=Array.prototype.slice.call(a.target.files,0);this.props.onFileSelected(a);this.setState({file:a[0]})},handleCancelClick:function(){var a=this.state.file;this.setState({file:null});this.props.onCancelClick(a)},renderInput:function(){var a=this.props,b=a.label,a=(a=a.validMimeTypes)?a.join():null;return[f.createElement("input",{className:l.fileInput,ref:"fileInput",type:"file",onChange:this.handleChange, accept:a,multiple:!1}),b&&f.createElement("div",{className:l.label},b),f.createElement("div",{className:l.uploadIcon})]},renderProgressBar:function(){return[f.createElement(k,{className:l.progressBar,progress:this.props.percentUploaded}),f.createElement("button",{className:l.cancelButton,onClick:this.handleCancelClick},"Cancel")]},renderFilePreview:function(){var a=this.props.filePreviewRenderer,b=this.state.file;return a?a(b):[f.createElement("div",{className:l.label},b.name),f.createElement("div", {className:l.fileIcon})]},render:function(){var a=this.props,b=a.children,c=a.style,k=a.className,r=a.title,t=a.percentUploaded,p=a.validMimeTypes,a=(0,e.default)(a,"children style className title percentUploaded validMimeTypes".split(" "));delete a.label;var u=this.state.file;return f.createElement(g,a,r&&f.createElement("div",{className:"title"},r),b&&f.createElement("div",{className:"description"},b),f.createElement(h,{onDrop:this.handleDrop,className:d(k,l.inside),validMimeTypes:p,style:c},!u? this.renderInput():t||0===t?this.renderProgressBar():this.renderFilePreview()))}});c.exports=a},,,,,,function(c,b,a){a(797);c.exports=a(31).Object.freeze},function(c,b,a){a(798);c.exports=a(31).Object.values},function(c,b,a){var e=a(165),f=a(139),d=a(458).f;c.exports=function(a){return function(b){b=f(b);for(var c=e(b),l=c.length,m=0,n=[],s;l>m;)if(d.call(b,s=c[m++]))n.push(a?[s,b[s]]:b[s]);return n}}},,function(c,b,a){var e=a(134),f=a(613).onFreeze;a(88)("freeze",function(a){return function(b){return a&& e(b)?a(f(b)):b}})},function(c,b,a){c=a(63);var e=a(795)(!1);c(c.S,"Object",{values:function(a){return e(a)}})},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".Body-body-1aeDU {\n margin: 11px 0;\n}\n",""]);b.locals={body:"Body-body-1aeDU"}},function(c,b,a){b=c.exports=a(3)();b.i(a(23),void 0);b.push([c.id,".Button-standard-33pc9 {\n background: transparent;\n}\n.Button-standard-33pc9:hover {\n background-color: #fff;\n}\n.Button-caution-dznOC {\n}\n.Button-caution-dznOC:disabled,\n.Button-caution-dznOC:disabled:hover {\n color: #a1a1a1;\n background-color: #e4e4e4;\n}\n", ""]);b.locals={standard:"Button-standard-33pc9 "+a(23).locals.minor+"",caution:"Button-caution-dznOC "+a(23).locals.caution+""}},function(c,b,a){b=c.exports=a(3)();b.i(a(23),void 0);b.push([c.id,".Footer-footer-8qHSM {\n margin: 22px -33px -22px;\n}\n",""]);b.locals={footer:"Footer-footer-8qHSM "+a(23).locals.buttonContainer+""}},function(c,b,a){b=c.exports=a(3)();b.i(a(45),void 0);b.push([c.id,".Header-header-13vZ5 {\n margin-bottom: 11px;\n}\n",""]);b.locals={header:"Header-header-13vZ5 "+a(45).locals.headline+ ""}},function(c,b,a){b=c.exports=a(3)();b.i(a(264),void 0);b.push([c.id,".Modal-overlay-1F7bC {\n position: fixed;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n -webkit-perspective: 600;\n perspective: 600;\n opacity: 0;\n overflow-x: hidden;\n overflow-y: auto;\n background-color: rgba(0, 0, 0, 0.4);\n z-index: 300000;\n}\n.Modal-overlay-1F7bC.ReactModal__Overlay--after-open {\n opacity: 1;\n transition: opacity 150ms;\n}\n.Modal-overlay-1F7bC.ReactModal__Overlay--before-close {\n opacity: 0;\n}\n.Modal-content-qKUAI {\n position: fixed;\n top: 50%;\n left: 50%;\n -webkit-transform-origin: top left;\n -ms-transform-origin: top left;\n transform-origin: top left;\n -webkit-transform: scale(0.96) translate(-50%, -50%);\n -ms-transform: scale(0.96) translate(-50%, -50%);\n transform: scale(0.96) translate(-50%, -50%);\n}\n.Modal-content-qKUAI.Modal-positionToPoint-2JkJC {\n -webkit-transform-origin: center center;\n -ms-transform-origin: center center;\n transform-origin: center center;\n -webkit-transform: scale(0.96);\n -ms-transform: scale(0.96);\n transform: scale(0.96);\n}\n.Modal-content-qKUAI:focus {\n outline: none;\n}\n.Modal-content-qKUAI.ReactModal__Content--after-open {\n -webkit-transform: scale(1) translate(-50%, -50%);\n -ms-transform: scale(1) translate(-50%, -50%);\n transform: scale(1) translate(-50%, -50%);\n transition: -webkit-transform 300ms;\n transition: transform 300ms;\n transition: transform 300ms, -webkit-transform 300ms;\n}\n.Modal-content-qKUAI.ReactModal__Content--after-open.Modal-positionToPoint-2JkJC {\n -webkit-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n}\n.Modal-content-qKUAI.ReactModal__Content--before-close {\n -webkit-transform: scale(0.96) translate(-50%, -50%);\n -ms-transform: scale(0.96) translate(-50%, -50%);\n transform: scale(0.96) translate(-50%, -50%);\n transition: -webkit-transform 300ms;\n transition: transform 300ms;\n transition: transform 300ms, -webkit-transform 300ms;\n}\n.Modal-content-qKUAI.ReactModal__Content--before-close.Modal-positionToPoint-2JkJC {\n -webkit-transform: scale(0.96);\n -ms-transform: scale(0.96);\n transform: scale(0.96);\n}\n.Modal-container-20fNL {\n color: inherit;\n background-color: #f2f2f2;\n padding: 22px 33px;\n box-sizing: border-box;\n border-radius: 4px;\n overflow-y: auto;\n max-height: 90vh;\n}\n.Modal-midnight-u26UD {\n color: #3e3e3e;\n font-weight: 400;\n}\n.Modal-fields-ta0Jl {\n margin-bottom: 11px;\n}\n.Modal-fields-ta0Jl .Modal-check-field-wrapper-jdNKx {\n padding: 0;\n}\n.Modal-fields-ta0Jl .Modal-check-field-wrapper-jdNKx .Modal-field-description-28x_K {\n background: none;\n}\n", ""]);b.locals={overlay:"Modal-overlay-1F7bC",content:"Modal-content-qKUAI",positionToPoint:"Modal-positionToPoint-2JkJC",container:"Modal-container-20fNL "+a(264).locals.windowShadow+"",midnight:"Modal-midnight-u26UD",fields:"Modal-fields-ta0Jl","check-field-wrapper":"Modal-check-field-wrapper-jdNKx","field-description":"Modal-field-description-28x_K"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".ProgressBar-container-Ej1rN {\n height: 8px;\n border: 1px solid #666;\n border-radius: 5px;\n margin: 0 auto;\n background: #666;\n width: 65%;\n}\n.ProgressBar-inner-1IkxH {\n background: #eee;\n height: 8px;\n max-width: 100%;\n border-radius: 5px;\n}\n", ""]);b.locals={container:"ProgressBar-container-Ej1rN",inner:"ProgressBar-inner-1IkxH"}},function(c,b,a){b=c.exports=a(3)();b.i(a(24),void 0);b.i(a(23),void 0);b.push([c.id,".File-inside-3qg6Z {\n position: relative;\n padding-top: 100%;\n box-sizing: border-box;\n background: white;\n}\n.File-fileInput-Mx1mx {\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n cursor: pointer;\n}\n.File-icon-_Bxyq {\n position: absolute;\n z-index: 1;\n top: 50%;\n left: 0;\n width: 100%;\n height: 44px;\n margin-top: -22px;\n}\n.File-uploadIcon-1yR5o {\n opacity: 0.15;\n transition: opacity cubic-bezier(0.645, 0.045, 0.355, 1) 0.4s;\n}\n.File-fileIcon-2-d2e {\n cursor: default;\n}\n.File-label-23muB + .File-icon-_Bxyq {\n margin-top: -33px;\n}\n.File-label-23muB {\n position: absolute;\n z-index: 1;\n top: 50%;\n left: 0;\n width: 100%;\n height: 22px;\n margin-top: 11px;\n color: #797979;\n overflow: hidden;\n text-align: center;\n text-overflow: ellipsis;\n transition: color cubic-bezier(0.645, 0.045, 0.355, 1) 0.4s;\n}\n.File-inside-3qg6Z:hover .File-uploadIcon-1yR5o {\n opacity: 0.5;\n}\n.File-inside-3qg6Z:hover .File-label-23muB {\n color: #3e3e3e;\n}\n.File-progressBar-1Rg5- {\n position: absolute;\n top: 50%;\n left: 50%;\n -webkit-transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n margin-top: -11px;\n}\n.File-cancelButton-29Fkh {\n position: absolute;\n top: 50%;\n left: 50%;\n width: auto;\n margin-top: 11px;\n -webkit-transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n font-size: 11px;\n}\n", ""]);b.locals={inside:"File-inside-3qg6Z",fileInput:"File-fileInput-Mx1mx",icon:"File-icon-_Bxyq",uploadIcon:"File-uploadIcon-1yR5o File-icon-_Bxyq "+a(24).locals.upload+"",fileIcon:"File-fileIcon-2-d2e File-icon-_Bxyq "+a(24).locals.file+"",label:"File-label-23muB",progressBar:"File-progressBar-1Rg5-",cancelButton:"File-cancelButton-29Fkh "+a(23).locals.text+""}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".FlatSelect-optionsContainer-1qkSp {\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n font: 500 11px/22px 'Gotham SSm A', 'Gotham SSm B', 'Gotham SSm', 'Proxima Nova', 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n text-transform: uppercase;\n border: 1px solid #e4e4e4;\n border-radius: 4px;\n overflow: hidden;\n}\n.FlatSelect-optionsContainer-1qkSp input {\n display: none;\n}\n.FlatSelect-optionsContainer-1qkSp label {\n padding: 10px;\n box-sizing: border-box;\n text-align: center;\n -webkit-flex: 1 1 auto;\n -ms-flex: 1 1 auto;\n flex: 1 1 auto;\n border-left: 1px solid #e4e4e4;\n cursor: pointer;\n}\n.FlatSelect-optionsContainer-1qkSp label:not(.FlatSelect-active-Kz9KE):hover {\n background-color: #e4e4e4;\n z-index: 10;\n border-color: #f2f2f2;\n}\n.FlatSelect-optionsContainer-1qkSp label:not(.FlatSelect-active-Kz9KE):hover + label {\n border-color: #f2f2f2;\n}\n.FlatSelect-optionsContainer-1qkSp label:first-child {\n border-left: 0;\n}\n.FlatSelect-optionsContainer-1qkSp label.FlatSelect-active-Kz9KE {\n background-color: #e4e4e4;\n border-right: 0;\n}\n", ""]);b.locals={optionsContainer:"FlatSelect-optionsContainer-1qkSp",active:"FlatSelect-active-Kz9KE"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id," {\n /**\n * Read this first: https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/\n */\n}\n.Range-valueContainer-1H_yi {\n position: absolute;\n}\n.Range-input-1Ojvj {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n width: 100%;\n -webkit-transform: translateY(-3px);\n -ms-transform: translateY(-3px);\n transform: translateY(-3px);\n height: 24px;\n display: inline-block;\n background-color: inherit;\n}\n.Range-input-1Ojvj::-webkit-slider-runnable-track {\n height: 2px;\n background: #DFDFDF;\n border: none;\n}\n.Range-input-1Ojvj::-moz-range-track {\n height: 2px;\n background: #DFDFDF;\n border: none;\n}\n.Range-input-1Ojvj::-ms-track {\n height: 2px;\n background: #DFDFDF;\n border: none;\n color: transparent;\n}\n.Range-input-1Ojvj::-webkit-slider-thumb {\n -webkit-appearance: none;\n appearance: none;\n transition: -webkit-transform linear 0.15s;\n transition: transform linear 0.15s;\n transition: transform linear 0.15s, -webkit-transform linear 0.15s;\n border: none;\n height: 12px;\n width: 12px;\n border-radius: 50%;\n background: #3e3e3e;\n margin-top: -5px;\n}\n.Range-input-1Ojvj::-webkit-slider-thumb:hover,\n.Range-input-1Ojvj::-webkit-slider-thumb:active {\n -webkit-transform: scale(1.5);\n transform: scale(1.5);\n cursor: col-resize;\n}\n.Range-input-1Ojvj::-moz-range-thumb {\n transition: -webkit-transform linear 0.15s;\n transition: transform linear 0.15s;\n transition: transform linear 0.15s, -webkit-transform linear 0.15s;\n border: none;\n height: 12px;\n width: 12px;\n border-radius: 50%;\n background: #3e3e3e;\n margin-top: -5px;\n}\n.Range-input-1Ojvj::-moz-range-thumb:hover,\n.Range-input-1Ojvj::-moz-range-thumb:active {\n transform: scale(1.5);\n cursor: col-resize;\n}\n.Range-input-1Ojvj::-ms-thumb {\n transition: -webkit-transform linear 0.15s;\n transition: transform linear 0.15s;\n transition: transform linear 0.15s, -webkit-transform linear 0.15s;\n border: none;\n height: 12px;\n width: 12px;\n border-radius: 50%;\n background: #3e3e3e;\n margin-top: -5px;\n}\n.Range-input-1Ojvj::-ms-thumb:hover,\n.Range-input-1Ojvj::-ms-thumb:active {\n -ms-transform: scale(1.5);\n transform: scale(1.5);\n cursor: col-resize;\n}\n", ""]);b.locals={valueContainer:"Range-valueContainer-1H_yi",input:"Range-input-1Ojvj"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".TextArea-wrapper-AEHMf {\n position: relative;\n}\n.TextArea-wrapper-AEHMf textarea {\n resize: none;\n height: 100% !important;\n position: absolute !important;\n}\n.TextArea-wrapper-AEHMf .TextArea-sizingHelper-3NS2P {\n white-space: pre-wrap;\n word-wrap: break-word;\n box-sizing: border-box;\n visibility: hidden;\n height: auto;\n}\n.TextArea-errors-3bbVx textarea {\n box-shadow: inset 0 0 0 2px #f0523d;\n}\n.TextArea-readOnly-3siIr textarea {\n background: #e4e4e4;\n color: #797979;\n font-style: italic;\n}\n.TextArea-denarius-28vKb .TextArea-wrapper-AEHMf {\n border: 1px solid #e4e4e4;\n border-radius: 3px;\n}\n.TextArea-denarius-28vKb .TextArea-wrapper-AEHMf textarea {\n min-height: 0;\n font-size: 12px;\n background: transparent;\n resize: none;\n}\n", ""]);b.locals={wrapper:"TextArea-wrapper-AEHMf",sizingHelper:"TextArea-sizingHelper-3NS2P",errors:"TextArea-errors-3bbVx",readOnly:"TextArea-readOnly-3siIr",denarius:"TextArea-denarius-28vKb"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".Toggle-switchBox-13hKR {\n width: 77px;\n height: 33px;\n overflow: hidden;\n border-radius: 100px;\n background-color: #dcdcdc;\n -webkit-user-select: none;\n}\n.Toggle-toggleBox-23Jap {\n margin-left: -44px;\n width: 165px;\n height: 33px;\n}\n.Toggle-toggleBackground-29n59 {\n width: 176px;\n height: 33px;\n}\n.Toggle-on-2bJrv,\n.Toggle-off-ERnZ9 {\n width: 61.5px;\n height: 33px;\n display: inline-block;\n font-size: 11px;\n font-weight: 500;\n text-align: center;\n line-height: 34px;\n text-transform: uppercase;\n box-sizing: border-box;\n}\n.Toggle-on-2bJrv {\n padding-right: 15.5px;\n padding-left: 5.5px;\n color: #eee;\n background-color: #3e3e3e;\n}\n.Toggle-off-ERnZ9 {\n padding-left: 15.5px;\n padding-right: 5.5px;\n color: #999;\n}\n.Toggle-handleWrapper-3AfXC {\n cursor: pointer;\n height: 33px;\n top: -65px;\n position: relative;\n}\n.Toggle-handle-3CNST {\n width: 31px;\n height: 31px;\n position: relative;\n left: 1px;\n background-color: #eee;\n border-radius: 100px;\n}\n.Toggle-switchShadow-1PavF {\n height: 33px;\n position: relative;\n top: -33px;\n border-radius: 100px;\n}\n.Toggle-container-3bZ67 {\n width: 77px;\n height: 33px;\n -webkit-user-select: none;\n}\n.Toggle-container-3bZ67.Toggle-active-HC9Xg .Toggle-toggleBackground-29n59 {\n margin-left: 44px;\n}\n.Toggle-container-3bZ67.Toggle-active-HC9Xg .Toggle-handle-3CNST {\n left: 45px;\n}\n.Toggle-container-3bZ67.Toggle-active-HC9Xg .Toggle-off-ERnZ9 {\n background-color: #3e3e3e;\n transition: background-color ease-out 0.1s;\n}\n.Toggle-container-3bZ67.Toggle-inactive-1LAiz .Toggle-toggleBackground-29n59 {\n margin-left: 0;\n}\n.Toggle-container-3bZ67.Toggle-inactive-1LAiz .Toggle-on-2bJrv {\n background-color: #dcdcdc;\n transition: background-color ease-out 0.1s;\n}\n.Toggle-container-3bZ67.Toggle-animate-3YVSq .Toggle-toggleBackground-29n59 {\n transition: margin-left ease-out 0.1s;\n}\n.Toggle-container-3bZ67.Toggle-animate-3YVSq .Toggle-handle-3CNST {\n transition: left ease-out 0.1s;\n}\n.Toggle-small-xEEiZ {\n width: 62.7px;\n height: 24.2px;\n}\n.Toggle-small-xEEiZ .Toggle-switchBox-13hKR {\n width: 62.7px;\n height: 24.2px;\n}\n.Toggle-small-xEEiZ .Toggle-toggleBox-23Jap {\n margin-left: -38.5px;\n width: 139.7px;\n height: 24.2px;\n}\n.Toggle-small-xEEiZ .Toggle-toggleBackground-29n59 {\n width: 154px;\n height: 24.2px;\n}\n.Toggle-small-xEEiZ .Toggle-on-2bJrv,\n.Toggle-small-xEEiZ .Toggle-off-ERnZ9 {\n width: 51.6px;\n height: 24.2px;\n line-height: 25.2px;\n}\n.Toggle-small-xEEiZ .Toggle-on-2bJrv {\n padding-right: 11.1px;\n padding-left: 7.33333333px;\n}\n.Toggle-small-xEEiZ .Toggle-off-ERnZ9 {\n padding-left: 11.1px;\n padding-right: 7.33333333px;\n}\n.Toggle-small-xEEiZ .Toggle-handleWrapper-3AfXC {\n height: 24.2px;\n top: -47.4px;\n}\n.Toggle-small-xEEiZ .Toggle-handle-3CNST {\n width: 22.2px;\n height: 22.2px;\n}\n.Toggle-small-xEEiZ .Toggle-switchShadow-1PavF {\n height: 24.2px;\n top: -24.2px;\n}\n.Toggle-small-xEEiZ.Toggle-active-HC9Xg .Toggle-toggleBackground-29n59 {\n margin-left: 38.5px;\n}\n.Toggle-small-xEEiZ.Toggle-active-HC9Xg .Toggle-handle-3CNST {\n left: 39.5px;\n}\n", ""]);b.locals={switchBox:"Toggle-switchBox-13hKR",toggleBox:"Toggle-toggleBox-23Jap",toggleBackground:"Toggle-toggleBackground-29n59",on:"Toggle-on-2bJrv",off:"Toggle-off-ERnZ9",handleWrapper:"Toggle-handleWrapper-3AfXC",handle:"Toggle-handle-3CNST",switchShadow:"Toggle-switchShadow-1PavF",container:"Toggle-container-3bZ67",active:"Toggle-active-HC9Xg",inactive:"Toggle-inactive-1LAiz",animate:"Toggle-animate-3YVSq",small:"Toggle-small-xEEiZ"}},function(c,b,a){b=a(799);"string"===typeof b&&(b=[[c.id, b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(800);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(801);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(802);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(803);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(804); "string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(805);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(806);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(807);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(808);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)}, function(c,b,a){b=a(809);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,,,,,,,,,function(c,b,a){var e=a(65);c.exports=function(a){return a&&a.length?e(a,!0):[]}},function(c,b,a){var e=a(257),f=a(159),d=a(865),g=a(62),h=Math.max;c.exports=function(a){if(!a||!a.length)return[];var b=-1,c=0;a=e(a,function(a){if(g(a))return c=h(a.length,c),!0});for(var n=Array(c);++b<c;)n[b]=f(a,d(b));return n}},function(c,b,a){c.exports={all:a(835),any:a(836),at:a(837),collect:a(838), contains:a(839),countBy:a(840),detect:a(841),each:a(842),eachRight:a(843),every:a(176),filter:a(241),find:a(89),findLast:a(844),findWhere:a(845),foldl:a(846),foldr:a(847),forEach:a(242),forEachRight:a(438),groupBy:a(615),include:a(848),includes:a(147),indexBy:a(742),inject:a(849),invoke:a(850),map:a(243),max:a(877),min:a(878),partition:a(770),pluck:a(851),reduce:a(255),reduceRight:a(439),reject:a(852),sample:a(440),select:a(853),shuffle:a(616),size:a(854),some:a(145),sortBy:a(617),sortByAll:a(855), sortByOrder:a(856),sum:a(557),where:a(857)}},function(c,b,a){c.exports=a(176)},function(c,b,a){c.exports=a(145)},function(c,b,a){var e=a(863),f=a(65);b=a(56)(function(a,b){return e(a,f(b))});c.exports=b},function(c,b,a){c.exports=a(243)},function(c,b,a){c.exports=a(147)},function(c,b,a){b=a(160);var e=Object.prototype.hasOwnProperty;b=b(function(a,b,c){e.call(a,c)?++a[c]:a[c]=1});c.exports=b},function(c,b,a){c.exports=a(89)},function(c,b,a){c.exports=a(242)},function(c,b,a){c.exports=a(438)},function(c, b,a){b=a(258);a=a(299)(b,!0);c.exports=a},function(c,b,a){var e=a(533),f=a(89);c.exports=function(a,b){return f(a,e(b))}},function(c,b,a){c.exports=a(255)},function(c,b,a){c.exports=a(439)},function(c,b,a){c.exports=a(147)},function(c,b,a){c.exports=a(255)},function(c,b,a){var e=a(49),f=a(873),d=a(62),g=a(156);b=a(56)(function(a,b,c){var m=-1,n="function"==typeof b,s=g(b),q=d(a)?Array(a.length):[];e(a,function(a){var d=n?b:s&&null!=a?a[b]:void 0;q[++m]=d?d.apply(a,c):f(a,b,c)});return q});c.exports= b},function(c,b,a){var e=a(243),f=a(1039);c.exports=function(a,b){return e(a,f(b))}},function(c,b,a){var e=a(257),f=a(38),d=a(442),g=a(27);c.exports=function(a,b,c){var m=g(a)?e:d;b=f(b,c,3);return m(a,function(a,d,c){return!b(a,d,c)})}},function(c,b,a){c.exports=a(241)},function(c,b,a){var e=a(151),f=a(92),d=a(78);c.exports=function(a){var b=a?e(a):0;return f(b)?b:d(a).length}},function(c,b,a){var e=a(65),f=a(444),d=a(39);b=a(56)(function(a,b){if(null==a)return[];var c=b[2];c&&d(b[0],b[1],c)&&(b.length= 1);return f(a,e(b),[])});c.exports=b},function(c,b,a){var e=a(444),f=a(27),d=a(39);c.exports=function(a,b,c,l){if(null==a)return[];l&&d(b,c,l)&&(c=void 0);f(b)||(b=null==b?[]:[b]);f(c)||(c=null==c?[]:[c]);return e(a,b,c)}},function(c,b,a){var e=a(533),f=a(241);c.exports=function(a,b){return f(a,e(b))}},function(c,b){c.exports=function(a,b){for(var c=a.length;c--&&!1!==b(a[c],c,a););return a}},function(c,b){c.exports=function(a,b,c,d){for(var g=-1,h=a.length,k=d;++g<h;){var l=a[g],m=+b(l);c(m,d)&& (d=m,k=l)}return k}},function(c,b){c.exports=function(a,b,c,d){var g=-1,h=a.length;for(d&&h&&(c=a[++g]);++g<h;)c=b(c,a[g],g,a);return c}},function(c,b){c.exports=function(a,b,c,d){var g=a.length;for(d&&g&&(c=a[--g]);g--;)c=b(c,a[g],g,a);return c}},function(c,b){c.exports=function(a,b){for(var c=a.length,d=0;c--;)d+=+b(a[c])||0;return d}},function(c,b,a){var e=a(62),f=a(266);c.exports=function(a,b){for(var c=-1,k=null==a,l=!k&&e(a),m=l?a.length:0,n=b.length,s=Array(n);++c<n;){var q=b[c];s[c]=l?f(q, m)?a[q]:void 0:k?void 0:a[q]}return s}},function(c,b,a){var e=a(49);c.exports=function(a,b,c,h){var k=h,l=k;e(a,function(a,f,e){f=+b(a,f,e);if(c(f,k)||f===h&&f===l)k=f,l=a});return l}},,function(c,b){c.exports=function(a,b,c,d,g){g(a,function(a,g,l){c=d?(d=!1,a):b(c,a,g,l)});return c}},function(c,b,a){var e=a(49);c.exports=function(a,b){var c=0;e(a,function(a,f,e){c+=+b(a,f,e)||0});return c}},function(c,b,a){var e=a(441);c.exports=function(a,b){return e(a.criteria,b.criteria)||a.index-b.index}},function(c, b,a){var e=a(441);c.exports=function(a,b,c){for(var h=-1,k=a.criteria,l=b.criteria,m=k.length,n=c.length;++h<m;){var s=e(k[h],l[h]);if(s){if(h>=n)return s;a=c[h];return s*("asc"===a||!0===a?1:-1)}}return a.index-b.index}},function(c,b,a){var e=a(100),f=a(39),d=a(56);c.exports=function(a){return d(function(b,d){var c=-1,m=null==b?0:d.length,n=2<m?d[m-2]:void 0,s=2<m?d[2]:void 0,q=1<m?d[m-1]:void 0;"function"==typeof n?(n=e(n,q,5),m-=2):(n="function"==typeof q?q:void 0,m-=n?1:0);s&&f(d[0],d[1],s)&& (n=3>m?void 0:n,m=1);for(;++c<m;)(s=d[c])&&a(b,s,n);return b})}},function(c,b,a){var e=a(56);c.exports=function(a,b){return e(function(c){var e=c[0];if(null==e)return e;c.push(b);return a.apply(void 0,c)})}},function(c,b,a){var e=a(100);c.exports=function(a){return function(b,c,h){if("function"!=typeof c||void 0!==h)c=e(c,h,3);return a(b,c)}}},function(c,b,a){var e=a(278),f=a(265),d=a(156),g=a(321),h=a(225);c.exports=function(a,b,c){null!=a&&!d(b,a)&&(b=h(b),a=1==b.length?a:e(a,f(b,0,-1)),b=g(b)); b=null==a?a:a[b];return null==b?void 0:b.apply(a,c)}},function(c,b){c.exports=function(a,b){return a>b}},function(c,b){c.exports=function(a,b){return a<b}},function(c,b,a){var e=a(744),f=a(151),d=a(92),g=a(71);c.exports=function(a){var b=a?f(a):0;return!d(b)?g(a):!b?[]:e(a)}},function(c,b,a){b=a(445);a=a(874);a=b(a,Number.NEGATIVE_INFINITY);c.exports=a},function(c,b,a){b=a(445);a=a(875);a=b(a,Number.POSITIVE_INFINITY);c.exports=a},function(c,b,a){c.exports={assign:a(558),create:a(1245),defaults:a(1246), defaultsDeep:a(1247),extend:a(1248),findKey:a(747),findLastKey:a(1249),forIn:a(1383),forInRight:a(1250),forOwn:a(1251),forOwnRight:a(1252),functions:a(880),get:a(247),has:a(1185),invert:a(599),keys:a(78),keysIn:a(128),mapKeys:a(600),mapValues:a(185),merge:a(535),methods:a(1253),omit:a(248),pairs:a(1186),pick:a(76),result:a(1254),set:a(1133),transform:a(1187),values:a(71),valuesIn:a(1255)}},function(c,b,a){var e=a(1239),f=a(128);c.exports=function(a){return e(a,f(a))}},function(c,b,a){var e=a(2),f= a(33);b=a(887);var d=e.createFactory(a(882)),g=a(883),h=a(886),k=a(33).unstable_renderSubtreeIntoContainer,l=a(449);a=b.canUseDOM?window.HTMLElement:{};var m=e.createClass({displayName:"Modal",statics:{setAppElement:function(a){g.setElement(a)},injectCSS:function(){}},propTypes:{isOpen:e.PropTypes.bool.isRequired,style:e.PropTypes.shape({content:e.PropTypes.object,overlay:e.PropTypes.object}),appElement:e.PropTypes.instanceOf(a),onAfterOpen:e.PropTypes.func,onRequestClose:e.PropTypes.func,closeTimeoutMS:e.PropTypes.number, ariaHideApp:e.PropTypes.bool,shouldCloseOnOverlayClick:e.PropTypes.bool},getDefaultProps:function(){return{isOpen:!1,ariaHideApp:!0,closeTimeoutMS:0,shouldCloseOnOverlayClick:!0}},componentDidMount:function(){this.node=document.createElement("div");this.node.className="ReactModalPortal";document.body.appendChild(this.node);this.renderPortal(this.props)},componentWillReceiveProps:function(a){this.renderPortal(a)},componentWillUnmount:function(){f.unmountComponentAtNode(this.node);document.body.removeChild(this.node); h(document.body).remove("ReactModal__Body--open")},renderPortal:function(a){a.isOpen?h(document.body).add("ReactModal__Body--open"):h(document.body).remove("ReactModal__Body--open");a.ariaHideApp&&g.toggle(a.isOpen,a.appElement);this.portal=k(this,d(l({},a,{defaultStyles:m.defaultStyles})),this.node)},render:function(){return e.DOM.noscript()}});m.defaultStyles={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(255, 255, 255, 0.75)"},content:{position:"absolute",top:"40px", left:"40px",right:"40px",bottom:"40px",border:"1px solid #ccc",background:"#fff",overflow:"auto",WebkitOverflowScrolling:"touch",borderRadius:"4px",outline:"none",padding:"20px"}};c.exports=m},function(c,b,a){b=a(2);var e=b.DOM.div,f=a(884),d=a(885),g=a(449),h={overlay:{base:"ReactModal__Overlay",afterOpen:"ReactModal__Overlay--after-open",beforeClose:"ReactModal__Overlay--before-close"},content:{base:"ReactModal__Content",afterOpen:"ReactModal__Content--after-open",beforeClose:"ReactModal__Content--before-close"}}; c.exports=b.createClass({displayName:"ModalPortal",getDefaultProps:function(){return{style:{overlay:{},content:{}}}},getInitialState:function(){return{afterOpen:!1,beforeClose:!1}},componentDidMount:function(){this.props.isOpen&&(this.setFocusAfterRender(!0),this.open())},componentWillUnmount:function(){clearTimeout(this.closeTimer)},componentWillReceiveProps:function(a){!this.props.isOpen&&a.isOpen?(this.setFocusAfterRender(!0),this.open()):this.props.isOpen&&!a.isOpen&&this.close()},componentDidUpdate:function(){this.focusAfterRender&& (this.focusContent(),this.setFocusAfterRender(!1))},setFocusAfterRender:function(a){this.focusAfterRender=a},open:function(){f.setupScopedFocus(this.node);f.markForFocusLater();this.setState({isOpen:!0},function(){this.setState({afterOpen:!0});if(this.props.isOpen&&this.props.onAfterOpen)this.props.onAfterOpen()}.bind(this))},close:function(){this.ownerHandlesClose()&&(0<this.props.closeTimeoutMS?this.closeWithTimeout():this.closeWithoutTimeout())},focusContent:function(){this.refs.content.focus()}, closeWithTimeout:function(){this.setState({beforeClose:!0},function(){this.closeTimer=setTimeout(this.closeWithoutTimeout,this.props.closeTimeoutMS)}.bind(this))},closeWithoutTimeout:function(){this.setState({afterOpen:!1,beforeClose:!1},this.afterClose)},afterClose:function(){f.returnFocus();f.teardownScopedFocus()},handleKeyDown:function(a){9==a.keyCode&&d(this.refs.content,a);27==a.keyCode&&(a.preventDefault(),this.requestClose(a))},handleOverlayClick:function(a){for(var b=a.target;b;){if(b=== this.refs.content)return;b=b.parentNode}this.props.shouldCloseOnOverlayClick&&(this.ownerHandlesClose()?this.requestClose(a):this.focusContent())},requestClose:function(a){if(this.ownerHandlesClose())this.props.onRequestClose(a)},ownerHandlesClose:function(){return this.props.onRequestClose},shouldBeClosed:function(){return!this.props.isOpen&&!this.state.beforeClose},buildClassName:function(a,b){var d=h[a].base;this.state.afterOpen&&(d+=" "+h[a].afterOpen);this.state.beforeClose&&(d+=" "+h[a].beforeClose); return b?d+" "+b:d},render:function(){var a=this.props.className?{}:this.props.defaultStyles.content,b=this.props.overlayClassName?{}:this.props.defaultStyles.overlay;return this.shouldBeClosed()?e():e({ref:"overlay",className:this.buildClassName("overlay",this.props.overlayClassName),style:g({},b,this.props.style.overlay||{}),onClick:this.handleOverlayClick},e({ref:"content",style:g({},a,this.props.style.content||{}),className:this.buildClassName("content",this.props.className),tabIndex:"-1",onKeyDown:this.handleKeyDown}, this.props.children))}})},function(c,b){function a(a){f(a);(a||d).setAttribute("aria-hidden","true")}function e(a){f(a);(a||d).removeAttribute("aria-hidden")}function f(a){if(!a&&!d)throw Error("react-modal: You must set an element with `Modal.setAppElement(el)` to make this accessible");}var d="undefined"!==typeof document?document.body:null;b.toggle=function(b,d){b?a(d):e(d)};b.setElement=function(a){"string"===typeof a&&(a=document.querySelectorAll(a),a="length"in a?a[0]:a);return d=a||d};b.show= e;b.hide=a;b.resetForTesting=function(){d=document.body}},function(c,b,a){function e(a){k=!0}function f(a){k&&(k=!1,g&&setTimeout(function(){g.contains(document.activeElement)||(d(g)[0]||g).focus()},0))}var d=a(448),g=null,h=null,k=!1;b.markForFocusLater=function(){h=document.activeElement};b.returnFocus=function(){try{h.focus()}catch(a){console.warn("You tried to return focus to "+h+" but it is not in the DOM anymore")}h=null};b.setupScopedFocus=function(a){g=a;window.addEventListener?(window.addEventListener("blur", e,!1),document.addEventListener("focus",f,!0)):(window.attachEvent("onBlur",e),document.attachEvent("onFocus",f))};b.teardownScopedFocus=function(){g=null;window.addEventListener?(window.removeEventListener("blur",e),document.removeEventListener("focus",f)):(window.detachEvent("onBlur",e),document.detachEvent("onFocus",f))}},function(c,b,a){var e=a(448);c.exports=function(a,b){var c=e(a);if(c.length){if(c[b.shiftKey?0:c.length-1]===document.activeElement||a===document.activeElement)b.preventDefault(), c[b.shiftKey?c.length-1:0].focus()}else b.preventDefault()}},function(c,b){function a(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0,e=a.length;c<e;c++)if(a[c]===b)return c;return-1}function e(a){if(!(this instanceof e))return new e(a);a||(a={});a.nodeType&&(a={el:a});this.opts=a;this.el=a.el||document.body;"object"!==typeof this.el&&(this.el=document.querySelector(this.el))}c.exports=function(a){return new e(a)};e.prototype.add=function(b){var d=this.el;if(d){if(""===d.className)return d.className= b;var c=d.className.split(" ");if(-1<a(c,b))return c;c.push(b);d.className=c.join(" ");return c}};e.prototype.remove=function(b){var d=this.el;if(d&&""!==d.className){var c=d.className.split(" ");b=a(c,b);-1<b&&c.splice(b,1);d.className=c.join(" ");return c}};e.prototype.has=function(b){var d=this.el;if(d)return d=d.className.split(" "),-1<a(d,b)};e.prototype.toggle=function(a){this.el&&(this.has(a)?this.remove(a):this.add(a))}},function(c,b,a){var e;(function(){var f=!!("undefined"!==typeof window&& window.document&&window.document.createElement),d={canUseDOM:f,canUseWorkers:"undefined"!==typeof Worker,canUseEventListeners:f&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:f&&!!window.screen};!(e=function(){return d}.call(b,a,b,c),void 0!==e&&(c.exports=e))})()},function(c,b,a){var e=a(889),f=a(450);c.exports=function(a,b){return null==b?a:e(b,f(b),a)}},function(c,b){c.exports=function(a,b,c){c||(c={});for(var d=-1,g=b.length;++d<g;){var h=b[d];c[h]=a[h]}return c}},function(c, b,a){var e=a(891),f=a(892),d=a(893);c.exports=function(a){return d(function(b,d){var c=-1,m=null==b?0:d.length,n=2<m?d[m-2]:void 0,s=2<m?d[2]:void 0,q=1<m?d[m-1]:void 0;"function"==typeof n?(n=e(n,q,5),m-=2):(n="function"==typeof q?q:void 0,m-=n?1:0);s&&f(d[0],d[1],s)&&(n=3>m?void 0:n,m=1);for(;++c<m;)(s=d[c])&&a(b,s,n);return b})}},function(c,b){function a(a){return a}c.exports=function(b,c,d){if("function"!=typeof b)return a;if(void 0===c)return b;switch(d){case 1:return function(a){return b.call(c, a)};case 3:return function(a,d,k){return b.call(c,a,d,k)};case 4:return function(a,d,k,l){return b.call(c,a,d,k,l)};case 5:return function(a,d,k,l,m){return b.call(c,a,d,k,l,m)}}return function(){return b.apply(c,arguments)}}},function(c,b){var a=/^\d+$/,e=function(a){return function(b){return null==b?void 0:b[a]}}("length");c.exports=function(b,d,c){var h=typeof c;if(!c||!("object"==h||"function"==h))return!1;h=typeof d;if("number"==h){if(h=null!=c)h=e(c),h="number"==typeof h&&-1<h&&0==h%1&&9007199254740991>= h;if(h)var h=d,k=c.length,h="number"==typeof h||a.test(h)?+h:-1,h=-1<h&&0==h%1&&h<(null==k?9007199254740991:k)}else h="string"==h&&d in c;return h?(d=c[d],b===b?b===d:d!==d):!1}},function(c,b){var a=Math.max;c.exports=function(b,c){if("function"!=typeof b)throw new TypeError("Expected a function");c=a(void 0===c?b.length-1:+c||0,0);return function(){for(var d=arguments,g=-1,h=a(d.length-c,0),k=Array(h);++g<h;)k[g]=d[c+g];switch(c){case 0:return b.call(this,k);case 1:return b.call(this,d[0],k);case 2:return b.call(this, d[0],d[1],k)}h=Array(c+1);for(g=-1;++g<c;)h[g]=d[g];h[c]=k;return b.apply(this,h)}}},function(c,b){var a=/^\[object .+?Constructor\]$/,e=Object.prototype,f=Function.prototype.toString,d=e.toString,g=RegExp("^"+f.call(e.hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");c.exports=function(b,c){var e=null==b?void 0:b[c];var m;null==e?m=!1:(m=typeof e,m=e&&("object"==m||"function"==m)&&"[object Function]"==d.call(e)?g.test(f.call(e)): !!e&&"object"==typeof e&&a.test(e));return m?e:void 0}},function(c,b){var a=Object.prototype,e=a.hasOwnProperty,f=a.toString,d=a.propertyIsEnumerable,g=function(a){return function(b){return null==b?void 0:b[a]}}("length");c.exports=function(a){var b;if(b=!!a&&"object"==typeof a)if(b=null!=a)if(b=g(a),b="number"==typeof b&&-1<b&&0==b%1&&9007199254740991>=b)b=typeof a,b=a&&("object"==b||"function"==b)?f.call(a):"",b=!("[object Function]"==b||"[object GeneratorFunction]"==b);return b&&e.call(a,"callee")&& (!d.call(a,"callee")||"[object Arguments]"==f.call(a))}},function(c,b){var a=/^\[object .+?Constructor\]$/,e=Object.prototype,f=Function.prototype.toString,d=e.toString,g=RegExp("^"+f.call(e.hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),e=function(b,c){var e=null==b?void 0:b[c];var m;null==e?m=!1:(m=typeof e,m=e&&("object"==m||"function"==m)&&"[object Function]"==d.call(e)?g.test(f.call(e)):!!e&&"object"==typeof e&& a.test(e));return m?e:void 0}(Array,"isArray")||function(a){return!!a&&"object"==typeof a&&"number"==typeof a.length&&(-1<a.length&&0==a.length%1&&9007199254740991>=a.length)&&"[object Array]"==d.call(a)};c.exports=e},function(c,b,a){var e={transition:"transitionend",OTransition:"otransitionend",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"}[a(336)("transition")];c.exports={addTransitionEndListener:function(a,b,c){a.addEventListener(e,b,c);return b},removeTransitionEndListener:function(a, b,c){a.removeEventListener(e,b,c)}}},,,,,,,,,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(46);var f=e(b);b=a(4);var d=e(b);b=a(51);var g=e(b);b=a(158);var h=e(b);b=a(7);var k=e(b);b=a(50);var l=e(b);b=a(13);var m=e(b);b=a(2).PropTypes;var n=a(452),s=a(907),q=a(769),r=a(834),t=r.forEach,p=r.every,u=a(247),v=a(237);a=a(131);var r=a.loadStyles,x=a.addClass,w=a.removeClass,y=r("CSSTG",{".group":{position:"relative",display:"block"},".child":{"backface-visibility":"hidden", filter:"blur(1)"},".wrappedChild":{padding:"0.1px",margin:"-0.1px"}}),B=["appear","enter","reorder","leave"];a=b.shape({className:b.oneOfType([b.string,b.shape({from:b.string,to:b.string})]),from:b.object,to:b.object});var A=(0,m.default)({},n.propTypes,{transitions:b.shape({appear:a,enter:a,reorder:a,leave:a}).isRequired}),z=(0,m.default)({},n.defaultProps,{wrapChildWithTag:"div"});a=function(a){function b(a){(0,d.default)(this,b);a=(0,g.default)(this,(0,f.default)(b).call(this,a));a.state.className= y.group;return a}(0,l.default)(b,a);(0,k.default)(b,null,[{key:"propTypes",get:function(){return A}},{key:"defaultProps",get:function(){return z}}]);(0,k.default)(b,[{key:"componentWillMount",value:function(){this.normalizeClassNames(this.props)}},{key:"componentWillReceiveProps",value:function(a){(0,h.default)((0,f.default)(b.prototype),"componentWillReceiveProps",this).call(this,a);this.normalizeClassNames(a)}},{key:"normalizeClassNames",value:function(a){var b=a.transitions,d={},c=[];B.forEach(function(a){var f= b[a];if(f){var e=f.className||"",g="string"===typeof e,f=g&&e||e.from,e=g&&e||e.to,f=f?f.split(/\s+/):null,e=e?e.split(/\s+/):null;d[a]={from:f,to:e};c.push(f,e)}});this.setState({transitionClassNames:d,allTransitionClassNames:q.apply(void 0,c)})}},{key:"applyStyles",value:function(a,b,d){var c={};b&&t(b,function(b,f){"function"===typeof b&&(b=b(a,d));void 0!==b&&(c[f]=b,a.style[f]=b)});return c}},{key:"removeStyles",value:function(a,b){b&&t(b,function(b,d){a.style[d]=null})}},{key:"doComputedStylesMatch", value:function(a){var b=1>=arguments.length||void 0===arguments[1]?{}:arguments[1],d=window.getComputedStyle(a);return p(b,function(a,b){return d[b]===String(a)})}},{key:"beforeTransition",value:function(a,b,d){var c=this.props.transitions,f=this.state,e=f.transitionClassNames;w(b,f.allTransitionClassNames);d=this.applyStyles(b,u(c,[a,"from"]),d);d=Boolean(d&&this.doComputedStylesMatch(b,d));x(b,y.child);x(b,e[a].from);return d}},{key:"transition",value:function(a,b,d){var c=this.state,f=c.transitionClassNames, c=c.allTransitionClassNames,e=u(this.props.transitions,[a,"to"]);w(b,c);x(b,f[a].to);a=this.applyStyles(b,e,d);return Boolean(a&&!this.doComputedStylesMatch(b,a))}},{key:"afterTransition",value:function(a,b){var d=this.props.transitions[a]||{};w(b,this.state.allTransitionClassNames);w(b,y.child);this.removeStyles(b,d.from);this.removeStyles(b,d.to)}},{key:"getChildComponent",value:function(){return s}},{key:"getPropsForChild",value:function(){var a=this,d=(0,h.default)((0,f.default)(b.prototype), "getPropsForChild",this).call(this),c=d.wrapperTag,e=d.maxErrorTimeout,d=d.getParams,g=this.props,p=g.wrapChildWithTag,k=g.transitions,l={};B.forEach(function(b){k[b]&&(l["before"+v(b)]=a.beforeTransition.bind(a,b),l[b]=a.transition.bind(a,b),"leave"!==b&&(l["after"+v(b)]=a.afterTransition.bind(a,b)))});return(0,m.default)({wrapperTag:c,maxErrorTimeout:e,getParams:d||this.getCSSTransitionParams.bind(this),className:p?y.wrappedChild:""},l)}},{key:"getCSSTransitionParams",value:function(a){var b=u(this.props.transitions, [a,"getParams"]);if(b){for(var d=arguments.length,c=Array(1<d?d-1:0),f=1;f<d;f++)c[f-1]=arguments[f];return b.apply(void 0,c)}return null}}]);return b}(n);c.exports=a},function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(146);var f=e(b);b=a(227);var d=e(b);b=a(46);var g=e(b);b=a(4);var h=e(b);b=a(7);var k=e(b);b=a(51);var l=e(b);b=a(50);var m=e(b);a(2);var n=a(33),s=a(353),q=a(768),r=a(437);b=a(897);var t=b.addTransitionEndListener,p=b.removeTransitionEndListener;a=function(a){function b(){(0, h.default)(this,b);return(0,l.default)(this,(0,g.default)(b).apply(this,arguments))}(0,m.default)(b,a);(0,k.default)(b,[{key:"triggerTransition",value:function(a){var b=this,d=n.findDOMNode(this);this.prepBeforeTransitionTriggered(d);s(function(){!1!==b.props[a](d,b.state.params)?b.prepAfterTransitionTriggered(d):b.cleanAfterTransition()})}},{key:"prepBeforeTransitionTriggered",value:function(a){this._transitionProperties=[];var b=t(a,this.onCSSTransitionEnd.bind(this));this.registerCallback(function(){p(a, b)})}},{key:"onCSSTransitionEnd",value:function(a){q(this._transitionProperties,a.propertyName);0===this._transitionProperties.length&&this.cleanAfterTransition()}},{key:"prepAfterTransitionTriggered",value:function(a){var b,c=this.getTotalTransitionDurations(a),f=Math.max.apply(Math,(0,d.default)(c));0===f?this.cleanAfterTransition():((b=this._transitionProperties).push.apply(b,(0,d.default)(this.getWorkingTransitionProperties(a,c))),this.startErrorTimer(f+1E3))}},{key:"getTotalTransitionDurations", value:function(a){a=window.getComputedStyle(a);var b=a.transitionDelay;return r(a.transitionDuration.split(","),b.split(",")).map(function(a){a=(0,f.default)(a,2);var b=a[1];return 1E3*(parseFloat(a[0])+parseFloat(b))})}},{key:"getWorkingTransitionProperties",value:function(a,b){var d=window.getComputedStyle(a);return d.transitionProperty.split(", ").filter(function(c,f){return 0<b[f]&&"all"!==c&&""!==a.style[c]&&a.style[c]!==d[c]})}}]);return b}(a(453));c.exports=a},function(c,b,a){var e=a(11);b= a(131).loadStyles;var f=b("CSSTG-Dissolve",{".dissolve":{overflow:"hidden",transition:"opacity .33s ease, min-height .33s ease, max-height .33s ease"},".leave":{overflow:"hidden",position:"absolute",top:0,left:0,right:0,bottom:0},".dissolve.async":{transition:"opacity .33s ease .66s, min-height .33s ease .33s, max-height .33s ease .33s"},".leave.async":{transition:"opacity .33s ease"}}),d=function(a){var b=a.nextSibling||a.previousSibling;return b?b.scrollHeight+"px":a.scrollHeight+"px"},g=function(a){return a.scrollHeight+ "px"};b=function(a){return{appear:{className:e(f.dissolve,a),from:{opacity:0},to:{opacity:1}},enter:{className:e(f.dissolve,a),from:{opacity:0,height:g,minHeight:d,maxHeight:d},to:{opacity:1,minHeight:function(a){return a.style.height},maxHeight:function(a){return a.style.height}}},leave:{className:e(f.dissolve,f.leave,a),from:{opacity:1,minHeight:g,maxHeight:g},to:{opacity:0,minHeight:d,maxHeight:d}}}};c.exports={transitions:b(),async:b(f.async)}},function(c,b,a){b=a(11);a=a(131).loadStyles;a=a("CSSTG-ExpandCollapse", {".expand":{overflow:"hidden",transition:"max-height .2s ease-in-out, opacity .24s ease .08s"},".collapse":{overflow:"hidden",transition:"max-height .2s ease-in-out, opacity .16s ease"}});var e={opacity:1,maxHeight:function(a){return a.scrollHeight+"px"}},f={opacity:0,maxHeight:"0px"};c.exports={transitions:{appear:{className:b(a.expand,void 0),from:f,to:e},enter:{className:b(a.expand,void 0),from:f,to:e},leave:{className:b(a.collapse,void 0),from:e,to:f}}}},function(c,b,a){var e=a(11);b=a(131);var f= b.convertTranslateToMatrix;a=b.loadStyles;var d=b.normalizeStyleProperty,g=a("CSSTG-Reorderable",{".enter":{transition:"opacity .3s ease .2s"},".leave":{position:"absolute !important",top:"0",left:"0",transition:"opacity .3s ease"},".move":{transition:"transform .36s ease","z-index":"1"},".leave ~ .move":{"transition-delay":".2s"}}),h=function(a,b){var d=b.top,c=b.left,e=b.paddingTop,g=b.paddingLeft,h=window.getComputedStyle(a),t=h.marginTop,h=h.marginLeft,c=c-(parseInt(g,10)+parseInt(h,10)),d=d- (parseInt(e,10)+parseInt(t,10));return f(c.toFixed(3),d.toFixed(3))};c.exports={transitions:function(a){var b,c,n,s,q=d("transform"),r=d("transitionDelay");return{enter:{className:e(g.enter,a),from:{opacity:function(a){if(!a.style.opacity)return 0}},to:{opacity:1,transform:""}},leave:{className:e(g.leave,a),getParams:function(a){var b=a.getClientRects()[0],d=a.parentNode.getClientRects()[0];a=window.getComputedStyle(a.parentNode);return{top:b.top-d.top,left:b.left-d.left,paddingTop:a.paddingTop,paddingLeft:a.paddingLeft}}, from:(b={opacity:function(a){if(!a.style.opacity)return 1}},b[q]=h,b),to:(c={opacity:0},c[q]=function(a,b){return a.style[q]||b&&h(a,b)||f(0,0)},c)},reorder:{className:{to:e(g.move,a)},getParams:function(a,b,d){a=a.getClientRects()[0];return{top:a.top,left:a.left,endAbruptly:d}},from:(n={},n[q]=function(a,b){var d=a.getClientRects()[0],c=d.top,d=d.left,d=b?(b.left-d).toFixed(3):0,c=b?(b.top-c).toFixed(3):0;return f(d,c)},n[r]=function(a,b){return b&&b.endAbruptly?"0s":parseFloat(window.getComputedStyle(a)[r])+ "s"},n),to:(s={},s[q]=function(a){return f(0,0)},s)}}}()}},function(c,b,a){b=(b=a(13))&&b.__esModule?b:{"default":b};var e=a(11);a=a(131);var f=a.loadStyles,d=a.convertTranslateToMatrix,g=f("CSSTG-Slide",{".group":{overflow:"hidden"},".slide":{overflow:"hidden",transition:"transform .26s ease, min-height .26s ease, max-height .26s ease"},".leave":{overflow:"hidden",position:"absolute",top:0,left:0,right:0,bottom:0}}),h=function(a){var b=a.nextSibling||a.previousSibling;return b?b.scrollHeight+"px": a.scrollHeight+"px"},k=function(a){return a.scrollHeight+"px"};a=function(a,b){return{appear:{className:g.slide,from:{opacity:0},to:{opacity:1}},enter:{className:g.slide,from:{transform:function(c){return d(-a*(c.offsetWidth+1),-b*(c.offsetHeight+1))},height:k,minHeight:h,maxHeight:h},to:{transform:function(a){return d(0,0)},minHeight:function(a){return a.style.height},maxHeight:function(a){return a.style.height}}},leave:{className:e(g.slide,g.leave),from:{transform:function(a){return d(0,0)},minHeight:k, maxHeight:k},to:{transform:function(c){return d(a*(c.offsetWidth+1),b*(c.offsetHeight+1))},minHeight:h,maxHeight:h}}}};c.exports={className:g.group,transitions:(0,b.default)({},a(-1,0),{toLeft:a(-1,0),toRight:a(1,0),toTop:a(0,-1),toBottom:a(0,1)})}},function(c,b,a){b=a(909);var e=a(908),f=a(911);a=a(910);c.exports={ExpandCollapse:b,Dissolve:e,Slide:f,Reorderable:a}},function(c,b){var a={};c.exports=function(b,c){if(!a[b]){a[b]=!0;var d=document.createElement("style");d.setAttribute("type","text/css"); "textContent"in d?d.textContent=b:d.styleSheet.cssText=b;var g=document.getElementsByTagName("head")[0];c&&c.prepend?g.insertBefore(d,g.childNodes[0]):g.appendChild(d)}}},function(c,b,a){(function(a,b){c.exports=b()})(this,function(){return function(){var a;return a={perspective:function(a){return[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,-1/a,1]]},rotate:function(b){return a.rotateZ(b)},rotateX:function(b){return a.rotate3d(1,0,0,b)},rotateY:function(b){return a.rotate3d(0,1,0,b)},rotateZ:function(a){var b; b=Math.cos(a);a=Math.sin(a);return[[b,-a,0],[a,b,0]]},rotate3d:function(a,b,c,e){var k,l,m;m=a*a+b*b+c*c;k=Math.cos(e);l=Math.sin(e);e=1-k;l*=Math.sqrt(m);return[[(a*a+(b*b+c*c)*k)/m,(a*b*e-c*l)/m,(a*c*e+b*l)/m,0],[(a*b*e+c*l)/m,(b*b+(a*a+c*c)*k)/m,(b*c*e-a*l)/m,0],[(a*c*e-b*l)/m,(b*c*e+a*l)/m,(c*c+(a*a+b*b)*k)/m,0],[0,0,0,1]]},scale:function(a,b){return[[a,0,0],[0,b,0]]},scaleX:function(b){return a.scale(b,1)},scaleY:function(b){return a.scale(1,b)},scaleZ:function(b){return a.scale3d(1,1,b)},scale3d:function(a, b,c){return[[a,0,0,0],[0,b,0,0],[0,0,c,0],[0,0,0,1]]},skew:function(a,b){return[[1,Math.tan(a),0],[Math.tan(b),1,0]]},skewX:function(a){return[[1,Math.tan(a),0],[0,1,0]]},skewY:function(a){return[[1,0,0],[Math.tan(a),1,0]]},translate:function(a,b){return[[1,0,a],[0,1,b]]},translateX:function(b){return a.translate(b,0)},translateY:function(b){return a.translate(0,b)},translateZ:function(b){return a.translate3d(0,0,b)},translate3d:function(a,b,c){return[[1,0,0,a],[0,1,0,b],[0,0,1,c],[0,0,0,1]]}}}()})}, ,,,,,function(c,b,a){var e=a(25),f=a(143);c.exports={createMemberInvite:function(a){return e.post("/api/rest/member-invites",a)},readMemberInvites:function(){return e.get("/api/rest/member-invites")},updateMemberInvite:function(a){return e.put("/api/rest/member-invites/"+a.id,a)},deleteMemberInvite:function(a){return e.delete("/api/rest/member-invites/"+a)},readMemberPermissions:function(){return e.get("/api/rest/member-permissions")},updateMemberPermissions:function(a){return e.put("/api/rest/member-permissions/"+ a.id,a)},deleteMemberPermissions:function(a){return e.delete("/api/rest/member-permissions/"+a)},createBasicAuthor:function(a){return e.post("/api/member-accounts",a)},assignPermissionsToBasicAuthor:function(a){return e.post("/api/rest/member-permissions",{memberAccountId:a.data.id,permissions:[]})},updateAuthor:function(a){return e.put("/api/member-accounts/"+a.id,a)},replaceBasicAuthor:function(a,b){var c=f.stringify({replacementId:b});return e.post(["/api/member-accounts",a,"replace-author"].join("/"), c,{headers:{"Content-Type":"application/x-www-form-urlencoded"}})},deleteAuthor:function(a){return e.delete("/api/member-accounts/"+a)},transferOwner:function(a,b){var c=f.stringify({ownerId:a,password:b});return e.put("/api/settings/owner",c,{headers:{"Content-Type":"application/x-www-form-urlencoded"}})}}},function(c,b,a){var e=(b=a(19))&&b.__esModule?b:{"default":b},f=a(25),d=a(76),g="id firstName lastName displayName location websiteUrl bio email siteSubscriptions storeSubscriptions googlePlusProfile avatarId socialOptions developerAccount developerAccountMarketingDetails siteTemplateInstallationPreviews pseudonymAccount notificationsRead tutorialsCompleted phoneNumber guilds".split(" "); c.exports={sendVerificationEmail:function(a){return f.post("/api/member-accounts"+("/"+a+"/verification-email"))},editEmail:function(a,b,d){return f.put("/api/member-accounts/"+a+"/email",{email:b,password:d})},update:function(a){var b=a.notificationsRead,c=a.tutorialsCompleted,m=a.guilds;a=d(a,g);b&&(a.notificationsRead=(0,e.default)(b));c&&(a.tutorialsCompleted=(0,e.default)(c));m&&(a.guilds=(0,e.default)(m));return f.put("/api/member-accounts/"+a.id,a)},markTutorialCompleted:function(a){return f.post("/api/config/MarkMemberTutorialCompleted", {tutorial:a})}}},,function(c,b,a){b=a(32);var e=a(1202),f=a(1172),d=a(567),g=a(339),h=a(539),k=a(233),l=a(249).getWebsiteDomain,m=a(74),n=a(1115);c.exports=b({getStores:function(){return[d,f]},getDomainDestinationPickerConfig:function(){var a=f.getState(),b=a.disambiguationPhase;return a.disambiguationType===k.DOMAIN_FIRST?{isVisible:b===h.PRE_SELECT,onStartFresh:g.createParkingPage,onShowSites:g.showWebsiteSelector}:null},isInsideIFrame:function(){try{return window.self!==window.top}catch(a){return!0}}, createWebsiteSelectedCallback:function(a,b){var d=this.createRedirectCallback();return function(c){m.isFeatureEnabled("sentinel_auth_active")?d("https://"+l(c,a)+b):d(c.loginUrl+"&redirectUrl="+encodeURIComponent(b))}},createRedirectCallback:function(){return this.isInsideIFrame()?(this.frameMessageProducer||(this.frameMessageProducer=new n(window.parent,"www")),this.frameMessageProducer.requestRedirect.bind(this.frameMessageProducer)):g.redirect},createCloseCallback:function(){return this.isInsideIFrame()? (this.frameMessageProducer||(this.frameMessageProducer=new n(window.parent,"www")),this.frameMessageProducer.requestClose.bind(this.frameMessageProducer)):null},determineHeadingForType:function(a){return a===k.GOOGLE_DOMAINS||a===k.DOMAIN_FIRST?"Select a destination for your domain":"Please select a website"},getPropsFromStores:function(){var a=f.getState(),b=a.appDomain,c=a.currentWebsiteIdentifier,e=a.disambiguationType,p=a.disambiguationPhase,h=a.redirectPath,l=a.searchEnabled,a=a.searchQuery, m=this.getDomainDestinationPickerConfig(e),n=d.getWebsiteSummaries(),y=d.filter(a),h=this.createWebsiteSelectedCallback(b,h),B=this.createCloseCallback(),A=e===k.DOMAIN_FIRST?g.createParkingPage:null,z=this.determineHeadingForType(e);return{appDomain:b,currentWebsiteIdentifier:c,disambiguationType:e,disambiguationPhase:p,domainDestinationPickerConfig:m,filteredWebsiteSummaries:y,heading:z,onNoWebsites:A,onSearch:function(a){return g.search(a.target.value)},onRequestClose:B,onShowSites:g.showWebsiteSelector, onWebsiteSelected:h,searchEnabled:l,searchQuery:a,shouldShowListWhenOnlyOneWebsite:e!==k.DEFAULT,websiteSummaries:n}}},e)},function(c,b){c.exports={DOMAINS:"https://www.squarespace.com/domains-tos/",IMAGES:"https://www.squarespace.com/image-terms/",LOGO:"https://www.squarespace.com/logo-terms/",PRIVACY:"https://www.squarespace.com/privacy/",SERVICE:"https://www.squarespace.com/terms-of-service/",TEMPLATES:"https://www.squarespace.com/template-license/",TRADEMARK:"https://www.squarespace.com/trademark-guidelines/"}}, function(c,b){c.exports={OLDEST_FIRST:1,NEWEST_FIRST:2,MOST_LIKED:3,LEAST_LIKED:4,MOST_FLAGGED:5}},function(c,b){c.exports={ITEM:1,COLLECTION:2}},,,,,,,,,function(c,b,a){var e;(function(f){function d(){function a(b){if(!(this instanceof a))return void 0===b?d():new a(b);if(b instanceof a)this.s=b.s,this.e=b.e,this.c=b.c.slice();else{var c,f,e;0===b&&0>1/b?b="-0":r.test(b+="")||k(NaN);this.s="-"==b.charAt(0)?(b=b.slice(1),-1):1;if(-1<(c=b.indexOf(".")))b=b.replace(".","");0<(f=b.search(/e/i))?(0>c&& (c=f),c+=+b.slice(f+1),b=b.substring(0,f)):0>c&&(c=b.length);for(f=0;"0"==b.charAt(f);f++);if(f==(e=b.length))this.c=[this.e=0];else{for(;"0"==b.charAt(--e););this.e=c-f-1;this.c=[];for(c=0;f<=e;this.c[c++]=+b.charAt(f++));}}this.constructor=a}a.prototype=q;a.DP=l;a.RM=m;a.E_NEG=n;a.E_POS=s;return a}function g(a,b,d){var c=a.constructor,f=b-(a=new c(a)).e,e=a.c;e.length>++b&&h(a,f,c.RM);e[0]?d?f=b:(e=a.c,f=a.e+f+1):++f;for(;e.length<f;e.push(0));f=a.e;return 1===d||d&&(b<=f||f<=c.E_NEG)?(0>a.s&&e[0]? "-":"")+(1<e.length?e[0]+"."+e.join("").slice(1):e[0])+(0>f?"e":"e+")+f:a.toString()}function h(a,b,d,c){var f=a.c,e=a.e+b+1;1===d?c=5<=f[e]:2===d?c=5<f[e]||5==f[e]&&(c||0>e||void 0!==f[e+1]||f[e-1]&1):3===d?c=c||void 0!==f[e]||0>e:(c=!1,0!==d&&k("!Big.RM!"));if(1>e||!f[0])c?(a.e=-b,a.c=[1]):a.c=[a.e=0];else{f.length=e--;if(c)for(;9<++f[e];)f[e]=0,e--||(++a.e,f.unshift(1));for(e=f.length;!f[--e];f.pop());}return a}function k(a){a=Error(a);a.name="BigError";throw a;}var l=20,m=1,n=-7,s=21,q={},r=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, t;q.abs=function(){var a=new this.constructor(this);a.s=1;return a};q.cmp=function(a){var b=this.c,d=(a=new this.constructor(a)).c,c=this.s,f=a.s,e=this.e,g=a.e;if(!b[0]||!d[0])return!b[0]?!d[0]?0:-f:c;if(c!=f)return c;a=0>c;if(e!=g)return e>g^a?1:-1;c=-1;for(f=(e=b.length)<(g=d.length)?e:g;++c<f;)if(b[c]!=d[c])return b[c]>d[c]^a?1:-1;return e==g?0:e>g^a?1:-1};q.div=function(a){var b=this.constructor,d=this.c,c=(a=new b(a)).c,f=this.s==a.s?1:-1,e=b.DP;(e!==~~e||0>e||1E6<e)&&k("!Big.DP!");if(!d[0]|| !c[0])return d[0]==c[0]&&k(NaN),c[0]||k(f/0),new b(0*f);var g,l,r,t,m=c.slice(),s=g=c.length,n=d.length,q=d.slice(0,g),L=q.length,F=a,K=F.c=[],T=0,H=e+(F.e=this.e-a.e)+1;F.s=f;f=0>H?0:H;for(m.unshift(0);L++<g;q.push(0));do{for(l=0;10>l;l++){if(g!=(L=q.length))r=g>L?1:-1;else{t=-1;for(r=0;++t<g;)if(c[t]!=q[t]){r=c[t]>q[t]?1:-1;break}}if(0>r){for(a=L==g?c:m;L;){if(q[--L]<a[L]){for(t=L;t&&!q[--t];q[t]=9);--q[t];q[L]+=10}q[L]-=a[L]}for(;!q[0];q.shift());}else break}K[T++]=r?l:++l;q[0]&&r?q[L]=d[s]||0: q=[d[s]]}while((s++<n||void 0!==q[0])&&f--);!K[0]&&1!=T&&(K.shift(),F.e--);T>H&&h(F,e,b.RM,void 0!==q[0]);return F};q.eq=function(a){return!this.cmp(a)};q.gt=function(a){return 0<this.cmp(a)};q.gte=function(a){return-1<this.cmp(a)};q.lt=function(a){return 0>this.cmp(a)};q.lte=function(a){return 1>this.cmp(a)};q.sub=q.minus=function(a){var b,d;b=this.constructor;var c=this.s,f=(a=new b(a)).s;if(c!=f)return a.s=-f,this.plus(a);var e=this.c.slice();d=this.e;var g=a.c,h=a.e;if(!e[0]||!g[0])return g[0]? (a.s=-f,a):new b(e[0]?this:0);if(c=d-h){(b=0>c)?(c=-c,d=e):(h=d,d=g);d.reverse();for(f=c;f--;d.push(0));d.reverse()}else{d=((b=e.length<g.length)?e:g).length;for(c=f=0;f<d;f++)if(e[f]!=g[f]){b=e[f]<g[f];break}}b&&(d=e,e=g,g=d,a.s=-a.s);if(0<(f=(d=g.length)-(b=e.length)))for(;f--;e[b++]=0);for(f=b;d>c;){if(e[--d]<g[d]){for(b=d;b&&!e[--b];e[b]=9);--e[b];e[d]+=10}e[d]-=g[d]}for(;0===e[--f];e.pop());for(;0===e[0];)e.shift(),--h;e[0]||(a.s=1,e=[h=0]);a.c=e;a.e=h;return a};q.mod=function(a){var b,d=this, c=d.constructor,f=d.s,e=(a=new c(a)).s;a.c[0]||k(NaN);d.s=a.s=1;b=1==a.cmp(d);d.s=f;a.s=e;if(b)return new c(d);f=c.DP;e=c.RM;c.DP=c.RM=0;d=d.div(a);c.DP=f;c.RM=e;return this.minus(d.times(a))};q.add=q.plus=function(a){var b;b=this.constructor;var d=this.s,c=(a=new b(a)).s;if(d!=c)return a.s=-c,this.minus(a);var c=this.e,f=this.c,e=a.e,g=a.c;if(!f[0]||!g[0])return g[0]?a:new b(f[0]?this:0*d);f=f.slice();if(d=c-e){0<d?(e=c,b=g):(d=-d,b=f);for(b.reverse();d--;b.push(0));b.reverse()}0>f.length-g.length&& (b=g,g=f,f=b);d=g.length;for(c=0;d;)c=(f[--d]=f[d]+g[d]+c)/10|0,f[d]%=10;c&&(f.unshift(c),++e);for(d=f.length;0===f[--d];f.pop());a.c=f;a.e=e;return a};q.pow=function(a){var b=this,d=new b.constructor(1),c=d,f=0>a;(a!==~~a||-1E6>a||1E6<a)&&k("!pow!");for(a=f?-a:a;;){a&1&&(c=c.times(b));a>>=1;if(!a)break;b=b.times(b)}return f?d.div(c):c};q.round=function(a,b){var d=this,c=d.constructor;null==a?a=0:(a!==~~a||0>a||1E6<a)&&k("!round!");h(d=new c(d),a,null==b?c.RM:b);return d};q.sqrt=function(){var a, b,d,c=this.constructor;b=this.c;a=this.s;d=this.e;var f=new c("0.5");if(!b[0])return new c(this);0>a&&k(NaN);a=Math.sqrt(this.toString());0===a||a===1/0?(a=b.join(""),a.length+d&1||(a+="0"),b=new c(Math.sqrt(a).toString()),b.e=((d+1)/2|0)-(0>d||d&1)):b=new c(a.toString());a=b.e+(c.DP+=4);do d=b,b=f.times(d.plus(this.div(d)));while(d.c.slice(0,a).join("")!==b.c.slice(0,a).join(""));h(b,c.DP-=4,c.RM);return b};q.mul=q.times=function(a){var b;b=this.constructor;var d=this.c,c=(a=new b(a)).c,f=d.length, e=c.length,g=this.e,h=a.e;a.s=this.s==a.s?1:-1;if(!d[0]||!c[0])return new b(0*a.s);a.e=g+h;f<e&&(b=d,d=c,c=b,h=f,f=e,e=h);for(b=Array(h=f+e);h--;b[h]=0);for(g=e;g--;){e=0;for(h=f+g;h>g;)e=b[h]+c[g]*d[h-g-1]+e,b[h--]=e%10,e=e/10|0;b[h]=(b[h]+e)%10}e&&++a.e;b[0]||b.shift();for(g=b.length;!b[--g];b.pop());a.c=b;return a};q.toString=q.valueOf=q.toJSON=function(){var a=this.constructor,b=this.e,d=this.c.join(""),c=d.length;if(b<=a.E_NEG||b>=a.E_POS)d=d.charAt(0)+(1<c?"."+d.slice(1):"")+(0>b?"e":"e+")+ b;else if(0>b){for(;++b;d="0"+d);d="0."+d}else if(0<b)if(++b>c)for(b-=c;b--;d+="0");else b<c&&(d=d.slice(0,b)+"."+d.slice(b));else 1<c&&(d=d.charAt(0)+"."+d.slice(1));return 0>this.s&&this.c[0]?"-"+d:d};q.toExponential=function(a){null==a?a=this.c.length-1:(a!==~~a||0>a||1E6<a)&&k("!toExp!");return g(this,a,1)};q.toFixed=function(a){var b,d=this.constructor,c=d.E_NEG,f=d.E_POS;d.E_NEG=-(d.E_POS=1/0);null==a?b=this.toString():a===~~a&&(0<=a&&1E6>=a)&&(b=g(this,this.e+a),0>this.s&&(this.c[0]&&0>b.indexOf("-"))&& (b="-"+b));d.E_NEG=c;d.E_POS=f;b||k("!toFix!");return b};q.toPrecision=function(a){if(null==a)return this.toString();(a!==~~a||1>a||1E6<a)&&k("!toPre!");return g(this,a-1,2)};t=d();!(e=function(){return t}.call(b,a,b,c),void 0!==e&&(c.exports=e))})(this)},,,,,,,,function(c,b){YUI.add("squarespace-dialog-text-template",function(a){var b=a.Handlebars;(function(){var a=b.template;(b.templates=b.templates||{})["dialog-text.html"]=a(function(a,b,c,f,e){this.compilerInfo=[4,">= 1.0.0"];c=this.merge(c,a.helpers); e=e||{};a="";var m,n=this.escapeExpression;if((f=c["if"].call(b,(m=b.strings,null==m||!1===m?m:m.title),{hash:{},inverse:this.noop,fn:this.program(1,function(a,b){var d,c;return d=""+('\n <div class="title">'+n((c=(c=a.strings,null==c||!1===c?c:c.title),"function"===typeof c?c.apply(a):c))+"</div>\n")},e),data:e}))||0===f)a+=f;a+='\n\n<input type="text" ';if((f=c["if"].call(b,b.maxLength,{hash:{},inverse:this.noop,fn:this.program(3,function(a,b){var d,f;d='maxlength="';(f=c.maxLength)?f=f.call(a, {hash:{},data:b}):(f=a.maxLength,f="function"===typeof f?f.apply(a):f);return d+=n(f)+'"'},e),data:e}))||0===f)a+=f;a+="\n ";if((f=c["if"].call(b,b.name,{hash:{},inverse:this.noop,fn:this.program(5,function(a,b){var d,f;d='name="';(f=c.name)?f=f.call(a,{hash:{},data:b}):(f=a.name,f="function"===typeof f?f.apply(a):f);return d+=n(f)+'"'},e),data:e}))||0===f)a+=f;a+="\n ";if((f=c["if"].call(b,b.testAttribute,{hash:{},inverse:this.noop,fn:this.program(7,function(a,b){var d,f;d='data-test="'; (f=c.testAttribute)?f=f.call(a,{hash:{},data:b}):(f=a.testAttribute,f="function"===typeof f?f.apply(a):f);return d+=n(f)+'"'},e),data:e}))||0===f)a+=f;a+="\n ";if((f=c["if"].call(b,b.readOnly,{hash:{},inverse:this.noop,fn:this.program(9,function(a,b){return'readonly="readonly"'},e),data:e}))||0===f)a+=f;a+="\n ";if((f=c["if"].call(b,b.selectAllOnFocus,{hash:{},inverse:this.noop,fn:this.program(11,function(a,b){return'onClick="this.select()"'},e),data:e}))||0===f)a+=f;a+="/>\n\n";if((f= c["if"].call(b,(m=b.strings,null==m||!1===m?m:m.description),{hash:{},inverse:this.noop,fn:this.program(13,function(a,b){var d,c,f;d='\n\n\t<div class="description">\n ';if((f=(c=(c=a.strings,null==c||!1===c?c:c.description),"function"===typeof c?c.apply(a):c))||0===f)d+=f;return d+"\n </div>\n\n"},e),data:e}))||0===f)a+=f;return a+"\n"})})();a.Handlebars.registerPartial("dialog-text.html".replace("/","."),b.templates["dialog-text.html"])},"1.0",{requires:["handlebars-base"]})},,,,function(c, b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(46);var f=e(b);b=a(4);var d=e(b);b=a(7);var g=e(b);b=a(51);var h=e(b);b=a(50);var k=e(b);b=a(26).Record;var l=a(103);a=function(a){function b(a){(0,d.default)(this,b);a=(0,h.default)(this,(0,f.default)(b).call(this,a));a.type||console.warn("[ItemBundle] Missing type field.");return a}(0,k.default)(b,a);(0,g.default)(b,[{key:"clean",value:function(){var a;a=this.delete("upload");a=a.delete("job");return a=a.delete("item")}},{key:"isClean", value:function(){var a=this.job,b=this.item;return!this.upload&&!a&&!b}},{key:"isUploading",value:function(){var a=this.upload;return!!a&&(a.get("isInProgress")||a.get("errors"))}},{key:"isProcessing",value:function(){var a=this.job;return!!a&&a.get("status")!==l.SUCCESS}}]);return b}(b({index:void 0,isGlobal:!1,item:void 0,job:void 0,type:void 0,upload:void 0}));c.exports=a},function(c,b){c.exports={IMAGE_META:1,IMAGE_FULL:2}},,,,,,,,,,,,,,,,,,function(c,b){(function(a,b,c,d,g,h){function k(a,b){var d= typeof a[b];return"function"==d||!!("object"==d&&a[b])||"unknown"==d}function l(){if(!p(navigator.plugins)&&"object"==typeof navigator.plugins["Shockwave Flash"]){var a=navigator.plugins["Shockwave Flash"].description;a&&(!p(navigator.mimeTypes)&&navigator.mimeTypes["application/x-shockwave-flash"]&&navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)&&(H=a.match(/\d+/g))}if(!H){var b;try{b=new ActiveXObject("ShockwaveFlash.ShockwaveFlash"),H=Array.prototype.slice.call(b.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1)}catch(d){}}if(!H)return!1;a=parseInt(H[0],10);b=parseInt(H[1],10);S=9<a&&0<b;return!0}function m(){if(!E){E=!0;for(var a=0;a<U.length;a++)U[a]();U.length=0}}function n(a,b){E?a.call(b):U.push(function(){a.call(b)})}function s(){var a=parent;if(""!==N)for(var b=0,d=N.split(".");b<d.length;b++)a=a[d[b]];return a.easyXDM}function q(a){var b=a.toLowerCase().match(C);a=b[2];var d=b[3],b=b[4]||"";if("http:"==a&&":80"==b||"https:"==a&&":443"==b)b="";return a+"//"+d+b}function r(a){a=a.replace(O,"$1/"); if(!a.match(/^(http||https):\/\//)){var b="/"===a.substring(0,1)?"":c.pathname;"/"!==b.substring(b.length-1)&&(b=b.substring(0,b.lastIndexOf("/")+1));a=c.protocol+"//"+c.host+b+a}for(;I.test(a);)a=a.replace(I,"");return a}function t(a,b){var d="",c=a.indexOf("#");-1!==c&&(d=a.substring(c),a=a.substring(0,c));var c=[],f;for(f in b)b.hasOwnProperty(f)&&c.push(f+"="+h(b[f]));return a+(T?"#":-1==a.indexOf("?")?"?":"&")+c.join("&")+d}function p(a){return"undefined"===typeof a}function u(a,b,d){var c,f; for(f in b)b.hasOwnProperty(f)&&(f in a?(c=b[f],"object"===typeof c?u(a[f],c,d):d||(a[f]=b[f])):a[f]=b[f]);return a}function v(a){if(p(K)){var d=b.body.appendChild(b.createElement("form")),c=d.appendChild(b.createElement("input"));c.name=F+"TEST"+A;K=c!==d.elements[c.name];b.body.removeChild(d)}K?d=b.createElement('<iframe name="'+a.props.name+'"/>'):(d=b.createElement("IFRAME"),d.name=a.props.name);d.id=d.name=a.props.name;delete a.props.name;"string"==typeof a.container&&(a.container=b.getElementById(a.container)); a.container||(u(d.style,{position:"absolute",top:"-2000px",left:"0px"}),a.container=b.body);c=a.props.src;a.props.src="javascript:false";u(d,a.props);d.border=d.frameBorder=0;d.allowTransparency=!0;a.container.appendChild(d);a.onLoad&&Q(d,"load",a.onLoad);if(a.usePost){var f=a.container.appendChild(b.createElement("form")),g;f.target=d.name;f.action=c;f.method="POST";if("object"===typeof a.usePost)for(var h in a.usePost)a.usePost.hasOwnProperty(h)&&(K?g=b.createElement('<input name="'+h+'"/>'):(g= b.createElement("INPUT"),g.name=h),g.value=a.usePost[h],f.appendChild(g));f.submit();f.parentNode.removeChild(f)}else d.src=c;a.props.src=c;return d}function x(d){var g=d.protocol,h;d.isHost=d.isHost||p(G.xdm_p);T=d.hash||!1;d.props||(d.props={});if(d.isHost)d.remote=r(d.remote),d.channel=d.channel||"default"+A++,d.secret=Math.random().toString(16).substring(2),p(g)&&(g=q(c.href)==q(d.remote)?"4":k(a,"postMessage")||k(b,"postMessage")?"1":d.swf&&k(a,"ActiveXObject")&&l()?"6":"Gecko"===navigator.product&& "frameElement"in a&&-1==navigator.userAgent.indexOf("WebKit")?"5":d.remoteHelper?"2":"0");else{d.channel=G.xdm_c.replace(/["'<>\\]/g,"");d.secret=G.xdm_s;d.remote=G.xdm_e.replace(/["'<>\\]/g,"");var g=G.xdm_p,m;if(m=d.acl){a:{m=d.acl;var s=d.remote;"string"==typeof m&&(m=[m]);for(var n,v=m.length;v--;)if(n=m[v],n=RegExp("^"==n.substr(0,1)?n:"^"+n.replace(/(\*)/g,".$1").replace(/\?/g,".")+"$"),n.test(s)){m=!0;break a}m=!1}m=!m}if(m)throw Error("Access denied for "+d.remote);}d.protocol=g;switch(g){case "0":u(d, {interval:100,delay:2E3,useResize:!0,useParent:!1,usePolling:!1},!0);if(d.isHost){if(!d.local){g=c.protocol+"//"+c.host;h=b.body.getElementsByTagName("img");for(s=h.length;s--;)if(m=h[s],m.src.substring(0,g.length)===g){d.local=m.src;break}d.local||(d.local=a)}g={xdm_c:d.channel,xdm_p:0};d.local===a?(d.usePolling=!0,d.useParent=!0,d.local=c.protocol+"//"+c.host+c.pathname+c.search,g.xdm_e=d.local,g.xdm_pa=1):g.xdm_e=r(d.local);d.container&&(d.useResize=!1,g.xdm_po=1);d.remote=t(d.remote,g)}else u(d, {channel:G.xdm_c,remote:G.xdm_e,useParent:!p(G.xdm_pa),usePolling:!p(G.xdm_po),useResize:d.useParent?!1:d.useResize});h=[new D.stack.HashTransport(d),new D.stack.ReliableBehavior({}),new D.stack.QueueBehavior({encode:!0,maxLength:4E3-d.remote.length}),new D.stack.VerifyBehavior({initiate:d.isHost})];break;case "1":h=[new D.stack.PostMessageTransport(d)];break;case "2":d.remoteHelper=r(d.remoteHelper);h=[new D.stack.NameTransport(d),new D.stack.QueueBehavior,new D.stack.VerifyBehavior({initiate:d.isHost})]; break;case "3":h=[new D.stack.NixTransport(d)];break;case "4":h=[new D.stack.SameOriginTransport(d)];break;case "5":h=[new D.stack.FrameElementTransport(d)];break;case "6":H||l(),h=[new D.stack.FlashTransport(d)]}h.push(new D.stack.QueueBehavior({lazy:d.lazy,remove:!0}));return h}function w(a){for(var b,d={incoming:function(a,b){this.up.incoming(a,b)},outgoing:function(a,b){this.down.outgoing(a,b)},callback:function(a){this.up.callback(a)},init:function(){this.down.init()},destroy:function(){this.down.destroy()}}, c=0,f=a.length;c<f;c++)b=a[c],u(b,d,!0),0!==c&&(b.down=a[c-1]),c!==f-1&&(b.up=a[c+1]);return b}function y(a){a.up.down=a.down;a.down.up=a.up;a.up=a.down=null}var B=this,A=Math.floor(1E4*Math.random()),z=Function.prototype,C=/^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/,I=/[\-\w]+\/\.\.\//,O=/([^:])\/\//g,N="",D={},L=a.easyXDM,F="easyXDM_",K,T=!1,H,S,Q,J;if(k(a,"addEventListener"))Q=function(a,b,d){a.addEventListener(b,d,!1)},J=function(a,b,d){a.removeEventListener(b,d,!1)};else if(k(a,"attachEvent"))Q=function(a, b,d){a.attachEvent("on"+b,d)},J=function(a,b,d){a.detachEvent("on"+b,d)};else throw Error("Browser not supported");var E=!1,U=[],M;"readyState"in b?(M=b.readyState,E="complete"==M||~navigator.userAgent.indexOf("AppleWebKit/")&&("loaded"==M||"interactive"==M)):E=!!b.body;if(!E){if(k(a,"addEventListener"))Q(b,"DOMContentLoaded",m);else if(Q(b,"readystatechange",function(){"complete"==b.readyState&&m()}),b.documentElement.doScroll&&a===top){var R=function(){if(!E){try{b.documentElement.doScroll("left")}catch(a){d(R, 1);return}m()}};R()}Q(a,"load",m)}var G=function(a){a=a.substring(1).split("&");for(var b={},d,c=a.length;c--;)d=a[c].split("="),b[d[0]]=g(d[1]);return b}(/xdm_e=/.test(c.search)?c.search:c.hash),V=function(){var a={},b={a:[1,2,3]};if("undefined"!=typeof JSON&&"function"===typeof JSON.stringify&&'{"a":[1,2,3]}'===JSON.stringify(b).replace(/\s/g,""))return JSON;Object.toJSON&&'{"a":[1,2,3]}'===Object.toJSON(b).replace(/\s/g,"")&&(a.stringify=Object.toJSON);"function"===typeof String.prototype.evalJSON&& (b='{"a":[1,2,3]}'.evalJSON(),b.a&&(3===b.a.length&&3===b.a[2])&&(a.parse=function(a){return a.evalJSON()}));return a.stringify&&a.parse?(V=function(){return a},a):null};u(D,{version:"2.4.16.3",query:G,stack:{},apply:u,getJSONObject:V,whenReady:n,noConflict:function(b){a.easyXDM=L;(N=b)&&(F="easyXDM_"+N.replace(".","_")+"_");return D}});D.DomHelper={on:Q,un:J,requiresJSON:function(d){"object"==typeof a.JSON&&a.JSON||b.write('<script type="text/javascript" src="'+d+'">\x3c/script>')}};(function(){var a= {};D.Fn={set:function(b,d){a[b]=d},get:function(b,d){var c=a[b];d&&delete a[b];return c}}})();D.Socket=function(a){var b=w(x(a).concat([{incoming:function(b,d){a.onMessage(b,d)},callback:function(b){if(a.onReady)a.onReady(b)}}])),d=q(a.remote);this.origin=q(a.remote);this.destroy=function(){b.destroy()};this.postMessage=function(a){b.outgoing(a,d)};b.init()};D.Rpc=function(a,b){if(b.local)for(var d in b.local)if(b.local.hasOwnProperty(d)){var c=b.local[d];"function"===typeof c&&(b.local[d]={method:c})}var f= w(x(a).concat([new D.stack.RpcBehavior(this,b),{callback:function(b){if(a.onReady)a.onReady(b)}}]));this.origin=q(a.remote);this.destroy=function(){f.destroy()};f.init()};D.stack.SameOriginTransport=function(a){var b,e,g,h;return b={outgoing:function(a,b,d){g(a);d&&d()},destroy:function(){e&&(e.parentNode.removeChild(e),e=null)},onDOMReady:function(){h=q(a.remote);a.isHost?(u(a.props,{src:t(a.remote,{xdm_e:c.protocol+"//"+c.host+c.pathname,xdm_c:a.channel,xdm_p:4}),name:F+a.channel+"_provider"}), e=v(a),D.Fn.set(a.channel,function(a){g=a;d(function(){b.up.callback(!0)},0);return function(a){b.up.incoming(a,h)}})):(g=s().Fn.get(a.channel,!0)(function(a){b.up.incoming(a,h)}),d(function(){b.up.callback(!0)},0))},init:function(){n(b.onDOMReady,b)}}};D.stack.FlashTransport=function(a){function g(a,b){d(function(){p.up.incoming(a,l)},0)}function h(d){var c=a.swf+"?host="+a.isHost,f="easyXDM_swf_"+Math.floor(1E4*Math.random());D.Fn.set("flash_loaded"+d.replace(/[\-.]/g,"_"),function(){D.stack.FlashTransport[d].swf= m=s.firstChild;for(var a=D.stack.FlashTransport[d].queue,b=0;b<a.length;b++)a[b]();a.length=0});a.swfContainer?s="string"==typeof a.swfContainer?b.getElementById(a.swfContainer):a.swfContainer:(s=b.createElement("div"),u(s.style,S&&a.swfNoThrottle?{height:"20px",width:"20px",position:"fixed",right:0,top:0}:{height:"1px",width:"1px",position:"absolute",overflow:"hidden",right:0,top:0}),b.body.appendChild(s));var g="callback=flash_loaded"+d.replace(/[\-.]/g,"_")+"&proto="+B.location.protocol+"&domain="+ B.location.href.match(C)[3]+"&port="+(B.location.href.match(C)[4]||"")+"&ns="+N;s.innerHTML="<object height='20' width='20' type='application/x-shockwave-flash' id='"+f+"' data='"+c+"'><param name='allowScriptAccess' value='always'></param><param name='wmode' value='transparent'><param name='movie' value='"+c+"'></param><param name='flashvars' value='"+g+"'></param><embed type='application/x-shockwave-flash' FlashVars='"+g+"' allowScriptAccess='always' wmode='transparent' src='"+c+"' height='1' width='1'></embed></object>"} var p,k,l,m,s;return p={outgoing:function(b,d,c){m.postMessage(a.channel,b.toString());c&&c()},destroy:function(){try{m.destroyChannel(a.channel)}catch(b){}m=null;k&&(k.parentNode.removeChild(k),k=null)},onDOMReady:function(){l=a.remote;D.Fn.set("flash_"+a.channel+"_init",function(){d(function(){p.up.callback(!0)})});D.Fn.set("flash_"+a.channel+"_onMessage",g);a.swf=r(a.swf);var b=a.swf.match(C)[3],e=function(){D.stack.FlashTransport[b].init=!0;m=D.stack.FlashTransport[b].swf;m.createChannel(a.channel, a.secret,q(a.remote),a.isHost);a.isHost&&(S&&a.swfNoThrottle&&u(a.props,{position:"fixed",right:0,top:0,height:"20px",width:"20px"}),u(a.props,{src:t(a.remote,{xdm_e:q(c.href),xdm_c:a.channel,xdm_p:6,xdm_s:a.secret}),name:F+a.channel+"_provider"}),k=v(a))};D.stack.FlashTransport[b]&&D.stack.FlashTransport[b].init?e():D.stack.FlashTransport[b]?D.stack.FlashTransport[b].queue.push(e):(D.stack.FlashTransport[b]={queue:[e]},h(b))},init:function(){n(p.onDOMReady,p)}}};D.stack.PostMessageTransport=function(b){function e(a){var d; if(a.origin)d=q(a.origin);else if(a.uri)d=q(a.uri);else if(a.domain)d=c.protocol+"//"+a.domain;else throw"Unable to retrieve the origin of the event";d==k&&a.data.substring(0,b.channel.length+1)==b.channel+" "&&g.up.incoming(a.data.substring(b.channel.length+1),d)}var g,h,p,k;return g={outgoing:function(a,d,c){p.postMessage(b.channel+" "+a,d||k);c&&c()},destroy:function(){J(a,"message",e);h&&(p=null,h.parentNode.removeChild(h),h=null)},onDOMReady:function(){k=q(b.remote);if(b.isHost){var l=function(c){c.data== b.channel+"-ready"&&(p="postMessage"in h.contentWindow?h.contentWindow:h.contentWindow.document,J(a,"message",l),Q(a,"message",e),d(function(){g.up.callback(!0)},0))};Q(a,"message",l);u(b.props,{src:t(b.remote,{xdm_e:q(c.href),xdm_c:b.channel,xdm_p:1}),name:F+b.channel+"_provider"});h=v(b)}else Q(a,"message",e),p="postMessage"in a.parent?a.parent:a.parent.document,p.postMessage(b.channel+"-ready",k),d(function(){g.up.callback(!0)},0)},init:function(){n(g.onDOMReady,g)}}};D.stack.FrameElementTransport= function(g){var h,p,k,l;return h={outgoing:function(a,b,d){k.call(this,a);d&&d()},destroy:function(){p&&(p.parentNode.removeChild(p),p=null)},onDOMReady:function(){l=q(g.remote);g.isHost?(u(g.props,{src:t(g.remote,{xdm_e:q(c.href),xdm_c:g.channel,xdm_p:5}),name:F+g.channel+"_provider"}),p=v(g),p.fn=function(a){delete p.fn;k=a;d(function(){h.up.callback(!0)},0);return function(a){h.up.incoming(a,l)}}):(b.referrer&&q(b.referrer)!=G.xdm_e&&(a.top.location=G.xdm_e),k=a.frameElement.fn(function(a){h.up.incoming(a, l)}),h.up.callback(!0))},init:function(){n(h.onDOMReady,h)}}};D.stack.NameTransport=function(a){function b(d){p.contentWindow.sendMessage(d,a.remoteHelper+(h?"#_3":"#_2")+a.channel)}function c(){h?(2===++l||!h)&&g.up.callback(!0):(b("ready"),g.up.callback(!0))}function f(a){g.up.incoming(a,s)}function e(){m&&d(function(){m(!0)},0)}var g,h,p,k,l,m,s,x;return g={outgoing:function(a,d,c){m=c;b(a)},destroy:function(){p.parentNode.removeChild(p);p=null;h&&(k.parentNode.removeChild(k),k=null)},onDOMReady:function(){h= a.isHost;l=0;s=q(a.remote);a.local=r(a.local);h?(D.Fn.set(a.channel,function(b){h&&"ready"===b&&(D.Fn.set(a.channel,f),c())}),x=t(a.remote,{xdm_e:a.local,xdm_c:a.channel,xdm_p:2}),u(a.props,{src:x+"#"+a.channel,name:F+a.channel+"_provider"}),k=v(a)):(a.remoteHelper=a.remote,D.Fn.set(a.channel,f));var b=function(){var f=p||this;J(f,"load",b);D.Fn.set(a.channel+"_load",e);(function aa(){"function"==typeof f.contentWindow.sendMessage?c():d(aa,50)})()};p=v({props:{src:a.local+"#_4"+a.channel},onLoad:b})}, init:function(){n(g.onDOMReady,g)}}};D.stack.HashTransport=function(b){function c(){if(l){var a=l.location.href,b="",d=a.indexOf("#");-1!=d&&(b=a.substring(d));b&&b!=p&&(p=b,f.up.incoming(p.substring(p.indexOf("_")+1),t))}}var f,e,g,h,p,k,l,r,m,t;return f={outgoing:function(a,d){if(r){var c=b.remote+"#"+k++ +"_"+a;(e||!m?r.contentWindow:r).location=c}},destroy:function(){a.clearInterval(g);(e||!m)&&r.parentNode.removeChild(r);r=null},onDOMReady:function(){e=b.isHost;h=b.interval;p="#"+b.channel;k= 0;m=b.useParent;t=q(b.remote);if(e){u(b.props,{src:b.remote,name:F+b.channel+"_provider"});if(m)b.onLoad=function(){l=a;g=setInterval(c,h);f.up.callback(!0)};else{var s=0,n=b.delay/50;(function $(){if(++s>n)throw Error("Unable to reference listenerwindow");try{l=r.contentWindow.frames[F+b.channel+"_consumer"]}catch(a){}l?(g=setInterval(c,h),f.up.callback(!0)):d($,50)})()}r=v(b)}else l=a,g=setInterval(c,h),m?(r=parent,f.up.callback(!0)):(u(b,{props:{src:b.remote+"#"+b.channel+new Date,name:F+b.channel+ "_consumer"},onLoad:function(){f.up.callback(!0)}}),r=v(b))},init:function(){n(f.onDOMReady,f)}}};D.stack.ReliableBehavior=function(a){var b,d,c=0,f=0,e="";return b={incoming:function(a,g){var h=a.indexOf("_"),p=a.substring(0,h).split(",");a=a.substring(h+1);p[0]==c&&(e="",d&&(d(!0),d=null));0<a.length&&(b.down.outgoing(p[1]+","+c+"_"+e,g),f!=p[1]&&(f=p[1],b.up.incoming(a,g)))},outgoing:function(a,g,h){e=a;d=h;b.down.outgoing(f+","+ ++c+"_"+a,g)}}};D.stack.QueueBehavior=function(a){function b(){if(a.remove&& 0===f.length)y(c);else if(!e&&!(0===f.length||l)){e=!0;var g=f.shift();c.down.outgoing(g.data,g.origin,function(a){e=!1;g.callback&&d(function(){g.callback(a)},0);b()})}}var c,f=[],e=!0,k="",l,r=0,m=!1,t=!1;return c={init:function(){p(a)&&(a={});a.maxLength&&(r=a.maxLength,t=!0);a.lazy?m=!0:c.down.init()},callback:function(a){e=!1;var d=c.up;b();d.callback(a)},incoming:function(b,d){if(t){var f=b.indexOf("_"),e=parseInt(b.substring(0,f),10);k+=b.substring(f+1);0===e&&(a.encode&&(k=g(k)),c.up.incoming(k, d),k="")}else c.up.incoming(b,d)},outgoing:function(d,e,g){a.encode&&(d=h(d));var p=[],k;if(t){for(;0!==d.length;)k=d.substring(0,r),d=d.substring(k.length),p.push(k);for(;k=p.shift();)f.push({data:p.length+"_"+k,origin:e,callback:0===p.length?g:null})}else f.push({data:d,origin:e,callback:g});m?c.down.init():b()},destroy:function(){l=!0;c.down.destroy()}}};D.stack.VerifyBehavior=function(a){function b(){c=Math.random().toString(16).substring(2);d.down.outgoing(c)}var d,c,f;return d={incoming:function(e, g){var h=e.indexOf("_");-1===h?e===c?d.up.callback(!0):f||(f=e,a.initiate||b(),d.down.outgoing(e)):e.substring(0,h)===f&&d.up.incoming(e.substring(h+1),g)},outgoing:function(a,b,f){d.down.outgoing(c+"_"+a,b,f)},callback:function(d){a.initiate&&b()}}};D.stack.RpcBehavior=function(a,b){function d(a){a.jsonrpc="2.0";e.down.outgoing(g.stringify(a))}function c(a,b){var f=Array.prototype.slice;return function(){var c=arguments.length,e,g={method:b};0<c&&"function"===typeof arguments[c-1]?(1<c&&"function"=== typeof arguments[c-2]?(e={success:arguments[c-2],error:arguments[c-1]},g.params=f.call(arguments,0,c-2)):(e={success:arguments[c-1]},g.params=f.call(arguments,0,c-1)),k[""+ ++h]=e,g.id=h):g.params=f.call(arguments,0);a.namedParams&&1===g.params.length&&(g.params=g.params[0]);d(g)}}function f(a,b,c,e){if(c){var g,h;b?(g=function(a){g=z;d({id:b,result:a})},h=function(a,c){h=z;var f={id:b,error:{code:-32099,message:a}};c&&(f.error.data=c);d(f)}):g=h=z;"[object Array]"!==Object.prototype.toString.call(e)&& (e=[e]);try{var k=c.method.apply(c.scope,e.concat([g,h]));p(k)||g(k)}catch(l){h(l.message)}}else b&&d({id:b,error:{code:-32601,message:"Procedure not found."}})}var e,g=b.serializer||V(),h=0,k={};return e={incoming:function(a,c){var e=g.parse(a);if(e.method)b.handle?b.handle(e,d):f(e.method,e.id,b.local[e.method],e.params);else{var h=k[e.id];e.error?h.error&&h.error(e.error):h.success&&h.success(e.result);delete k[e.id]}},init:function(){if(b.remote)for(var d in b.remote)b.remote.hasOwnProperty(d)&& (a[d]=c(b.remote[d],d));e.down.init()},destroy:function(){for(var d in b.remote)b.remote.hasOwnProperty(d)&&a.hasOwnProperty(d)&&delete a[d];e.down.destroy()}}};B.easyXDM=D})(window,document,location,window.setTimeout,decodeURIComponent,encodeURIComponent);c.exports=window.easyXDM},,,,,,,,,,,,,,,,,,,,function(c,b){var a={mailcheck:{threshold:3,defaultDomains:"yahoo.com google.com hotmail.com gmail.com me.com aol.com mac.com live.com comcast.net googlemail.com msn.com hotmail.co.uk yahoo.co.uk facebook.com verizon.net sbcglobal.net att.net gmx.com mail.com outlook.com icloud.com".split(" "), defaultTopLevelDomains:"co.jp co.uk com net org info edu gov mil ca".split(" "),run:function(b){b.domains=b.domains||a.mailcheck.defaultDomains;b.topLevelDomains=b.topLevelDomains||a.mailcheck.defaultTopLevelDomains;b.distanceFunction=b.distanceFunction||a.sift3Distance;var c=function(a){return a},d=b.suggested||c,c=b.empty||c;return(b=a.mailcheck.suggest(encodeURI(b.email),b.domains,b.topLevelDomains,b.distanceFunction))?d(b):c()},suggest:function(a,b,d,c){a=a.toLowerCase();a=this.splitEmail(a); if(b=this.findClosestDomain(a.domain,b,c)){if(b!=a.domain)return{address:a.address,domain:b,full:a.address+"@"+b}}else if(d=this.findClosestDomain(a.topLevelDomain,d),a.domain&&d&&d!=a.topLevelDomain)return b=a.domain,b=b.substring(0,b.lastIndexOf(a.topLevelDomain))+d,{address:a.address,domain:b,full:a.address+"@"+b};return!1},findClosestDomain:function(a,b,d){var c,h=99,k=null;if(!a||!b)return!1;d||(d=this.sift3Distance);for(var l=0;l<b.length;l++){if(a===b[l])return a;c=d(a,b[l]);c<h&&(h=c,k=b[l])}return h<= this.threshold&&null!==k?k:!1},sift3Distance:function(a,b){if(null==a||0===a.length)return null==b||0===b.length?0:b.length;if(null==b||0===b.length)return a.length;for(var d=0,c=0,h=0,k=0;d+c<a.length&&d+h<b.length;){if(a.charAt(d+c)==b.charAt(d+h))k++;else for(var l=h=c=0;5>l;l++){if(d+l<a.length&&a.charAt(d+l)==b.charAt(d)){c=l;break}if(d+l<b.length&&a.charAt(d)==b.charAt(d+l)){h=l;break}}d++}return(a.length+b.length)/2-k},splitEmail:function(a){a=a.split("@");if(2>a.length)return!1;for(var b= 0;b<a.length;b++)if(""===a[b])return!1;var d=a.pop(),c=d.split("."),h="";if(0==c.length)return!1;if(1==c.length)h=c[0];else{for(b=1;b<c.length;b++)h+=c[b]+".";2<=c.length&&(h=h.substring(0,h.length-1))}return{topLevelDomain:h,domain:d,address:a.join("@")}}}};"undefined"!==typeof c&&c.exports&&(c.exports=a.mailcheck);"undefined"!==typeof window&&window.jQuery&&function(b){b.fn.mailcheck=function(b){var d=this;if(b.suggested){var c=b.suggested;b.suggested=function(a){c(d,a)}}if(b.empty){var e=b.empty; b.empty=function(){e.call(null,d)}}b.email=this.val();a.mailcheck.run(b)}}(jQuery)},,,,,,,,,,,,,,,,,,,function(c,b,a){var e=a(1);YUI.add("squarespace-dialog-description",function(a){a.namespace("Squarespace.DialogFields");var b=a.Squarespace.DialogFields.Description=a.Squarespace.DialogFields.DescriptionField=a.Base.create("DescriptionField",a.Squarespace.DialogField2,[],{destructor:function(){this._descEl=null},renderUI:function(){b.superclass.renderUI.call(this);var c=this.get("padding");this._descEl= this.get("contentBox").one(".custom-field-description");a.Lang.isArray(c)&&0<c.length&&this._descEl.setStyles({paddingTop:c[0],paddingBottom:c[1]});this._attachNode("title");this._attachNode("text")},bindUI:function(){b.superclass.bindUI.call(this);this.after(["titleChange","textChange"],this.syncUI,this)},syncUI:function(){b.superclass.syncUI.call(this);this._descEl.empty();this._attachNode("title");this._attachNode("text")},_attachNode:function(b){var d=this.get(b);a.Lang.isString(d)&&0<d.length&& (attrNode=a.Node.create('<div class="'+b+'">'+d+"</div>"),this._descEl.append(attrNode))},_getAsString:function(b){return!a.Lang.isValue(b)?"":b+""},setTitle:function(a){this.set("title",a)},setText:function(a){this.set("text",a)}},{CSS_PREFIX:"sqs-description",TEMPLATE:'<div class="custom-field-description"></div>',ATTRS:{title:{value:e(""),getter:this._getAsString},text:{value:"",getter:this._getAsString},className:{value:"",validator:a.Lang.isString},padding:{value:[],validator:a.Lang.isArray}, focusable:{value:!1}}})},"1.0",{requires:["base","node","squarespace-dialog-field-2"]})},function(c,b){YUI.add("squarespace-dialog-check",function(a){a.namespace("Squarespace.DialogFields");var b=a.Squarespace.DialogFields.Check=a.Base.create("check",a.Squarespace.DialogField2,[],{initializer:function(b){!a.Lang.isValue(b.data)&&a.Lang.isValue(b.defaultValue)&&this.set("data",b.defaultValue)},bindUI:function(){b.superclass.bindUI.call(this);a.Squarespace.Utils.onPointerAction(this.get("boundingBox"), this._createEventHandler(this._toggleActive));this.get("boundingBox").after("mousedown",this._createEventHandler(),this)},syncUI:function(){b.superclass.syncUI.call(this);this.get("contentBox").empty().setHTML(this.renderTemplate());a.Lang.isValue(this.get("strings.description"))?this.get("boundingBox").addClass("has-description"):this.get("boundingBox").addClass("has-no-description")},_createEventHandler:function(b){return a.bind(function(a){this.get("haltClick")&&a.halt();b&&b.call(this,a)},this)}, _toggleActive:function(a){this.get("disabled")||this.set("data",!this.get("data"),{click:a})}},{CSS_PREFIX:"sqs-check",HANDLEBARS_TEMPLATE:"dialog-check.html",ATTRS:{data:{value:!1},haltClick:{value:!0}}})},"1.0",{requires:["base","event-tap","squarespace-dialog-check-template","squarespace-dialog-field-2","squarespace-util"]})},function(c,b){YUI.add("squarespace-dialog-label",function(a){a.namespace("Squarespace.Plugin").DialogFieldLabel=a.Base.create("dialogFieldLabel",a.Plugin.Base,[],{initializer:function(a){this.afterHostMethod("renderUI", this._render,this);this.afterHostMethod("syncUI",this.syncLabel,this)},destructor:function(){a.detach(this.get("id")+"|*");var b=this.get("host"),c=b.get("boundingBox");b.get("rendered")&&(c&&c._node)&&b.get("boundingBox").removeClass(a.Squarespace.Plugin.DialogFieldLabel.CSS_PREFIX+"-plugged")},_render:function(){this.renderLabel();this.bindLabel();this.syncLabel();this.get("host").get("boundingBox").addClass(a.Squarespace.Plugin.DialogFieldLabel.CSS_PREFIX+"-plugged")},renderLabel:function(){this._labelNode= a.Node.create("<label></label>");this._labelNode.addClass(a.Squarespace.Plugin.DialogFieldLabel.CSS_PREFIX);var b=this._labelNode;this.get("inField");var c=this.get("renderNode");this.get("strings.text");var d=this.get("className"),g=this.get("forNode"),h=this.get("host").get("contentBox");d&&b.addClass(d);c?(a.Lang.isString(c)&&(c=h.one(c)),c.appendChild(b)):g?(a.Lang.isString(g)&&(g=h.one(g)),(c=g.getAttribute("id"))&&b.setAttribute("for",c),g.insert(b,"before")):(h.one("input")||h.one("select")|| h.one("textarea")||h.one("button")).insert(b,"before")},bindLabel:function(){var a=this.get("id");this.on(a+"|classNameChange",function(a){this._labelNode.removeClass(a.prevVal);this._labelNode.addClass(a.newVal)},this)},syncLabel:function(){this._labelNode.setContent(this.get("strings.text"))}},{NS:"label",CSS_PREFIX:"sqs-dialog-field-label",ATTRS:{strings:{value:{text:""}},renderNode:{value:null},className:{value:null},forNode:{value:null}}});a.namespace("Squarespace.DialogFields").DialogFieldLabel= function(b){a.Do.before(function(){this.plug(a.Squarespace.Plugin.DialogFieldLabel,a.merge({renderNode:b.labelRenderNode||null,forNode:b.labelForNode||null,className:b.labelClassName||null,"strings.text":this.get("strings.label")},b.labelConfig||{},this.getProperty("LABEL_CONFIG")||{}))},this,"renderUI",this)};a.Squarespace.DialogFields.DialogFieldLabel.NAME="dialogFieldLabel"},"1.0",{requires:["base","node","plugin","squarespace-dialog-field-2"]})},function(c,b,a){var e=a(1),f=a(711);YUI.add("squarespace-dialog-text", function(a){a.namespace("Squarespace.DialogFields");var b=a.Squarespace.DialogFields.Text=a.Squarespace.DialogFields.TextField=a.Base.create("text",a.Squarespace.DialogField2,[],{destructor:function(){this._textField&&this._textField.remove(!0);this._textField=null},renderUI:function(){b.superclass.renderUI.call(this);this.get("name");var a=this.get("autocompleteType");this._textField=this.get("contentBox").one("input[type]");this.get("dialog")&&this._textField.setAttribute("tabindex",this.get("dialog").getNextTabIndex()); this._textField.set("type",this.get("password")?"password":"text");a&&this._textField.setAttribute("x-autocompletetype",a);this.get("autocompleteEnabled")||(this.get("password")&&this.get("contentBox").prepend('<input type="password" tabindex="-1" class="sqs-offscreen" />'),this._textField.setAttribute("autocomplete","off"));this._set("errorFlyoutAnchor",this._textField);this._textField.set("value",this.get("data"))},bindUI:function(){b.superclass.bindUI.call(this);this.get("id");this.after("dataChange", this._afterDataChange);this._textField.after("valuechange",this._afterValueChange,this);this.after("disabledChange",this.syncUI);this._textField.on("blur",this.hideError,this);var c=this._textField.getDOMNode(),f="addEventListener";a.Lang.isFunction(c.attachEvent)&&(f="attachEvent");c[f]("focus",a.bind(this._afterFocus,this));c[f]("blur",a.bind(this._afterBlur,this));this._textField.on("click",function(a){a.halt()});this._textField.after("keyup",function(a){13===a.keyCode&&this.get("submitOnEnter")? (this.fire("submit"),(a=this.get("dialog"))&&a.saveAndClose()):27===a.keyCode?a.halt():this.fire("keyup",a)},this);this._textField.on("keypress",this.applyKeyFilter,this);!0===this.get("mailcheck")&&this._textField.plug(a.Squarespace.Plugin.MailCheck,{field:this});this.on("readOnlyChange",function(a){a.newVal?this._textField.setAttribute("readonly","readonly"):this._textField.removeAttribute("readonly")},this)},syncUI:function(){b.superclass.syncUI.call(this);var a=this.get("strings.placeholder"); a&&this._textField.setAttribute("placeholder",a);this.get("disabled")?this._textField.setAttribute("disabled","disabled"):this._textField.removeAttribute("disabled")},getErrors:function(){var a=this.get("data");return this.get("validator")(a)?this.get("required")&&this.isEmpty()?[this.get("strings.requiredFieldEmptyMessage")]:[]:[this.get("strings.validationFailMessage")]},isEmpty:function(){return""===this.get("data")},focus:function(){b.superclass.focus.call(this);this.get("rendered")&&this._textField.focus()}, select:function(){this.get("rendered")&&this._textField.select()},blur:function(){b.superclass.blur.call(this);this.get("rendered")&&this._textField&&this._textField.blur()},disable:function(){b.superclass.disable.call(this);this.get("rendered")&&this._textField.setAttribute("disabled","disabled")},enable:function(){b.superclass.enable.call(this);this.get("rendered")&&this._textField.removeAttribute("disabled")},applyKeyFilter:function(b){var c=this.get("keyFilter"),f=this.get("keyFilterExplanation"), e;if(c&&(0===a.UA.gecko||b._event.isChar)&&!(13===b.charCode&&this.get("submitOnEnter")))e=String.fromCharCode(b.which),!e.match(RegExp(c))&&0<e.length&&(f&&this.showError(f),b.halt())},_afterDataChange:function(a){a.dataSync||this._textField.set("value",a.newVal||"",{dataSync:!0});this.hideError();this.toggleError()},_afterValueChange:function(a){a.dataSync||this.set("data",a.newVal,{dataSync:!0})},_afterFocus:function(){"undefined"!==typeof CONFIG_PANEL&&CONFIG_PANEL.set("allowContextMenu",!0); a.UA.ie||this.focus()},_afterBlur:function(){"undefined"!==typeof CONFIG_PANEL&&CONFIG_PANEL.set("allowContextMenu",!1);this._textField&&this.set("data",this._textField.get("value"),{dataSync:!0});this.blur()}},{CSS_PREFIX:"sqs-text",HANDLEBARS_TEMPLATE:"dialog-text.html",ATTRS:{strings:{value:{placeholder:e(""),validationFailMessage:e("This must be a string."),requiredFieldEmptyMessage:e("This is a required field.")}},data:{value:"",setter:function(b){a.Lang.isValue(b)||(b="");return b},validator:function(b){return a.Lang.isString(b)|| !a.Lang.isValue(b)}},validator:{value:a.Lang.isString},password:{value:!1,validator:a.Lang.isBoolean},submitOnEnter:{value:!1,validator:a.Lang.isBoolean},disabled:{value:!1,validator:a.Lang.isBoolean},autocompleteType:{value:null,writeOnce:"initOnly",validators:a.Squarespace.AttrValidators.isNullOrValueIn(f)},autocompleteEnabled:{value:!0,validator:a.Lang.isBoolean,writeOnce:"initOnly"},mailcheck:{value:!1,validator:a.Lang.isBoolean},keyFilter:{},keyFilterExplanation:{value:""},maxLength:{value:null}, readOnly:{value:!1},selectAllOnFocus:{value:!1}}});a.Squarespace.DialogFields.LabeledText=a.Base.create("labeledText",a.Squarespace.DialogFields.Text,[a.Squarespace.DialogFields.DialogFieldLabel],{},{CSS_PREFIX:"sqs-labeled-text",LABEL_CONFIG:{forNode:"input[type]"}});var c=a.Squarespace.DialogFields.Email=a.Base.create("emailText",a.Squarespace.DialogFields.Text,[],{renderUI:function(){c.superclass.renderUI.call(this);this.get("contentBox").one("input").setAttribute("type","email")}},{CSS_PREFIX:"sqs-email-text", ATTRS:{mailcheck:{value:!0}}}),k=a.Squarespace.DialogFields.Url=a.Base.create("urlText",a.Squarespace.DialogFields.Text,[],{renderUI:function(){k.superclass.renderUI.call(this);this._textField.wrap('<div class="sqs-input-wrapper-content"></div>');var a=this.get("contentBox").one(".sqs-input-wrapper-content");a.wrap('<div class="sqs-input-wrapper"></div>');a.prepend('<div class="prefix">'+this.get("prefix")+"</div>")},bindUI:function(){k.superclass.bindUI.call(this);this._textField.after("keyup",this.onKeyUp, this)},onKeyUp:function(b){var c=this.get("filter"),f;if("url-slug"===c||"url-slug-with-slash"==c)f=this._textField.get("value"),c="url-slug"===c?a.Squarespace.UrlUtils.createUrl(f):a.Squarespace.UrlUtils.createUrlWithSlash(f),b=this._textField.selectionStart-(32==b.keyCode?0:1),f!=c&&(this._textField.set("value",c),this._textField.selectionStart=b,this._textField.selectionEnd=b)}},{CSS_PREFIX:"sqs-url-text",ATTRS:{filter:{value:"url-slug-with-slash"},prefix:{value:"/"}}})},"1.0",{requires:"base squarespace-attr-validators squarespace-dialog-field-2 squarespace-dialog-label squarespace-dialog-text-template squarespace-mailcheck squarespace-url-utils".split(" ")})}, function(c,b){YUI.add("squarespace-form-utils",function(a){var b=a.namespace("Squarespace.FormUtils");b.setData=function(b,d){a.Lang.isValue(d)&&a.Array.each(b,function(b){var c=d[b.get("name")];a.Lang.isUndefined(c)||b.set("data",c)})};b.getData=function(b){b=b||[];return a.Array.reduce(b,{},function(b,c){var f=c.get("data");!a.Lang.isUndefined(f)&&a.Lang.isValue(c.get("name"))&&(b[c.get("name")]=f);return b})};b.template=function(b,d){a.Lang.isArray(d)?a.Array.each(d,function(a){var d=a.get("name"), c=b.one('[data-field-name="'+d+'"]');c?a.render(c):console.warn('No target node found for widget "'+d+'".')}):a.Lang.isObject(d)&&a.Object.each(d.groups||{},function(d,c){var e=b.one('[data-field-group="'+c+'"]');e&&a.Array.each(d,function(a){a.render(e)})})};b.validate=function(b){return a.Array.reduce(b,{},function(b,c){if(a.Lang.isFunction(c.getErrors)){var f=c.getErrors();f.length&&(b[c.get("name")]=f[0])}return b})};b.showErrors=function(b,d){a.Array.each(b,function(b){var c=d[b.get("name")]; a.Lang.isValue(c)&&""!==c&&a.Lang.isFunction(b.showError)&&b.showError(c)})};b.hideErrors=function(b){a.Array.each(b,function(b){a.Lang.isFunction(b.hideError)&&b.hideError()})}},"1.0",{requires:["array-extras","node"]})},function(c,b,a){var e=a(1),f=a(20);YUI.add("squarespace-mailcheck",function(b){var c=a(986);b.namespace("Squarespace.Plugin");b.Squarespace.Plugin.MailCheck=b.Base.create("MailCheck",b.Plugin.Base,[],{initializer:function(a){this._host=a.host;this._host.on("blur",this.checkMailAddress, this)},checkMailAddress:function(a){a=this._host.get("value");null!==a&&3<a.length&&c.run({topLevelDomains:[],email:a,suggested:b.bind(this.emailSuggestions,this),empty:b.bind(this.noEmailSuggestions,this)})},emailSuggestions:function(a){this._host.hasPlugin("flyoutPlugin")||this._host.plug(b.Squarespace.Animations.Flyout,{duration:0.3});this.get("field").showError(f(e('Did you mean <a class="corrected-email" href="#">{sub1}</a>?'),{sub1:a.full}));if(b.one(".corrected-email"))b.one(".corrected-email").once("click", this._onClick,this)},noEmailSuggestions:function(a){(a=this._host.flyoutPlugin)&&a.hide()},_onClick:function(a){a.preventDefault();a.halt();if(a=this._host.flyoutPlugin)this._host.set("value",a.get("node").one("a").getHTML()),a.hide(),this.get("field").clearError()},destructor:function(){}},{NS:"mailCheck",ATTRS:{field:{}}})},"1.0",{requires:["base","squarespace-node-flyout"]})},function(c,b,a){var e=a(185),f=a(272),d=a(279);YUI.add("squarespace-models-member-account",function(a){var b=a.namespace("Squarespace.Models").MemberAccount= a.Base.create("MemberAccount",a.Model,[a.Squarespace.ModelSync.REST],{root:"/api/member-accounts",serialize:function(){return a.JSON.stringify(this._getServerRelevantFields())},_getServerRelevantFields:function(){var b=a.Array.reduce("id firstName lastName displayName location websiteUrl bio email siteSubscriptions storeSubscriptions googlePlusProfile avatarId socialOptions developerAccount developerAccountMarketingDetails siteTemplateInstallationPreviews pseudonymAccount notificationsRead tutorialsCompleted phoneNumber guilds".split(" "), {},function(a,b){a[b]=this.get(b);return a},this);a.Lang.isObject(b.notificationsRead)&&(b.notificationsRead=a.Object.keys(b.notificationsRead));a.Lang.isObject(b.tutorialsCompleted)&&(b.tutorialsCompleted=a.Object.keys(b.tutorialsCompleted));return b},isMe:function(){return this.get("id")==Static.SQUARESPACE_CONTEXT.authenticatedAccount.id},sendVerificationEmail:function(){var b=this.getURL();return a.Squarespace.Promises.create(function(d,c){a.Data.post({secure:!0,url:b+"/verification-email",success:d, failure:c})})},setEmail:function(b,d){var c=this.getURL();return a.Squarespace.Promises.create(function(f,e){a.Data.put({url:c+"/email",data:{email:b,password:d},json:!0,secure:!0,success:f,failure:e})})},setPassword:function(b,d,c){return new a.Promise(a.bind(function(f,e){a.Data.put({secure:!0,url:this.getURL()+"/password",data:{newPassword:b,newPasswordConfirm:d,currentPassword:c},success:function(){this.set("emailAccount",!0);f()},failure:function(a){e(a)}},this)},this))},requestActivation:function(b){a.Data.post({url:this.getURL("update")+ "/activation-emails",success:function(a){b()},failure:function(a){b(a)}})},replaceAuthor:function(b,d){a.Data.post({url:this.getURL()+"/replace-author",data:{replacementId:b},success:function(a){d()},failure:function(a){d(a)}})},setPreviewInstallationId:function(b){var d=a.Object.getValue(Static,["SQUARESPACE_CONTEXT","website","id"]);a.Lang.isValue(b)?this.set("siteTemplateInstallationPreviews."+d,b):(b=this.get("siteTemplateInstallationPreviews"),delete b[d],this.set("siteTemplateInstallationPreviews", b))},getPreviewInstallationId:function(){return this.get("siteTemplateInstallationPreviews."+a.Object.getValue(Static,["SQUARESPACE_CONTEXT","website","id"]))},createTwoFactorAuthSetting:function(){var b=this.getURL();return a.Squarespace.Promises.create(function(d,c){a.Data.post({secure:!0,url:b+"/two-factor-settings",json:!0,success:d,failure:c})})},getTwoFactorAuthSettings:function(){var b=this.getURL();return a.Squarespace.Promises.create(function(d,c){a.Data.get({secure:!0,url:b+"/two-factor-settings", success:d,failure:c})})},setTwoFactorAuthSettings:function(b){var d=this.getURL(),c=this;return a.Squarespace.Promises.create(function(f,e){a.Data.put({secure:!0,url:d+"/two-factor-settings",json:!0,data:b,success:function(a){c.set("twoFactorAuthEnabled",b.enabled);f(a)},failure:e})})},updateScratchCodes:function(){var b=this.getURL();return a.Squarespace.Promises.create(function(d,c){a.Data.post({secure:!0,url:b+"/two-factor-settings/scratch-codes",json:!0,success:d,failure:c})})}},{ATTRS:{notificationsRead:{value:{}}}}); a.namespace("Squarespace.Singletons");if(Static&&Static.SQUARESPACE_CONTEXT&&Static.SQUARESPACE_CONTEXT.authenticatedAccount){var c=a.Squarespace.Singletons.AuthenticatedMemberAccount=new b(Static.SQUARESPACE_CONTEXT.authenticatedAccount),l=!0,m=!0,n=d.listen(function(a){l&&(m=!1,c.setAttrs(a.toJSON()));l=!0}),s=c.after("change",function(a){m&&(a=e(a.changed,function(a){return a.newVal}),l=!1,f.update(a));m=!0});a.on("beforeunload",function(){s.detach();n()},this)}else a.Squarespace.Singletons.AuthenticatedMemberAccount= new b({})},"1.0",{requires:"base model promise squarespace-attr-validators squarespace-model-sync-rest squarespace-promises".split(" ")})},function(c,b,a){var e=a(1);YUI.add("squarespace-object-builder",function(a){function b(){var d=Array.prototype.slice.call(arguments),c=d.shift(),e=d[d.length-1],g="prependArrays"==e;"prependArrays"==e||"appendArrays"==e?d.pop():e=null;for(var h=0,p=d.length;h<p;h++)if(d[h])for(var k in d[h])e&&d[h][k]&&a.Lang.isArray(d[h][k])?c[k]=(g?d[h][k]:c[k]||[]).concat((g? c[k]:d[h][k])||[]):c[k]=d[h][k];return c}function c(b,d){for(var e in b)if(Object.prototype.hasOwnProperty.call(b,e)&&!(b[e]instanceof a.Base)&&!(b[e]instanceof a.Node)&&!a.Lang.isFunction(b[e])){for(var h=b[e],k=0;k<d.length;k++){if("undefined"===typeof d[k].test||d[k].test(b[e],e,b))d[k].each&&d[k].each(b[e],e,b),d[k].map&&(b[e]=d[k].map(b[e],e,b));if("undefined"===typeof b[e])break}null!==b[e]&&("object"===typeof b[e]&&!h.$dontRecurse)&&c(b[e],d);if(b[e]instanceof Array)for(h=0;h<d.length;h++)if("undefined"=== typeof d[h].postTest||d[h].postTest(b[e]))d[h].post&&(b[e]=d[h].post(b[e],e,b))}return b}function h(e,h,k){var l={include:{test:function(a){return a&&a.$include},map:function(c){var e,g=c.$include;!a.Lang.isArray(g)&&!a.Lang.isObject(g[0])&&(g=[g]);for(var h=0,l=g.length;h<l;h++){var r=g[h],m;if("string"===typeof r){var s=r.split(".");m=k;for(var n=0,z=s.length;n<z;n++)if(m[s[n]])m=a.clone(m[s[n]]);else throw Error("Bad path `"+r+"`: `"+s[n]+"` not found.");}else{if("object"===typeof r)for(var C in r)if("string"== typeof C&&-1!==C.indexOf(".")){s=C.split(".");for(n=m;0!==s.length;)if(z=s.shift(),0===s.length){n[z]=r[C];break}else{var I=[z].concat(s).join(".");n.hasOwnProperty(I)?s=[I]:(n.hasOwnProperty(z)||(n[z]={}),n=n[z])}delete r[C]}m=r}e=b(e||(a.Lang.isArray(m)?[]:{}),m,"prependArrays")}c.$update&&(e.$update=c.$update);c.$concat&&(e.$concat=c.$concat);c.$when&&(e.$when=c.$when);return e}},update:{test:function(a){return a&&a.$update},each:function(b){function d(a,b){return function(d,c){return c===a&&d=== b}}function e(b){return function(d,c,e){a.mix(e,b,!0)}}var h=[],k=b.$update;delete b.$update;for(var l in k)"."==l[0]?h.push({test:d("name",l.slice(1)),each:e(k[l])}):h.push({test:d("type",l),each:e(k[l])});return c(b,h)}},when:{test:function(a){return a&&a.$when},map:function(b){if(a.Lang.isFunction(b.$when)&&b.$when(k)){if(b.$value)return b.$value;delete b.$when;return b}}},value:{test:function(a){return a&&a.$value},map:function(a){return k[a.$value]}},valueFn:{test:function(a){return a&&a.$valueFn}, map:function(a){var b=a.$valueFn(k);a.$concat&&(b.$concat=a.$concat);return b}},template:{test:function(b,d,c){return a.Squarespace.StringTemplate&&"string"===typeof b&&!c.$escape},map:function(b){return a.Squarespace.StringTemplate.template(b,k)}},concat:{postTest:function(a){var b=!1;if(a&&a instanceof Array)for(var d=0;d<a.length;d++)a[d]&&(a[d]instanceof Array&&a[d].$concat)&&(b=b||a[d].$concat);return b},post:function(a,b,d){b=[];for(d=0;d<a.length;d++)a[d]&&a[d]instanceof Array&&a[d].$concat? b=b.concat(a[d]):b.push(a[d]);return b}},trim:{postTest:function(b){return a.Lang.isArray(b)},post:function(b,d,c){d=b.filter(function(b){return!a.Lang.isUndefined(b)});b.$concat&&(d.$concat=b.$concat);return d}}};return c(a.merge(h),e.map(function(a){return l[a]}))}function k(a,b,d){a=h(["include","update"],a,b);return a=h("when value valueFn template concat trim".split(" "),a,d)}var l=a.namespace("Squarespace.StringTemplate");l.filters={lower:function(a){return(a||"").toLowerCase()},capitalize:function(a){return 1>= a.length?a:a.charAt(0).toUpperCase()+a.slice(1)},withIndefiniteArticle:function(a){var b=["a","e","i","o","u"];return 0===a.length?a:-1!==b.indexOf(a.charAt(0).toLowerCase())?e("an ")+a:"a "+a}};l.template=function(b,d,c){c=a.merge(l.filters,c);return b.replace(/\{(\s*)([^\s|]+)((?:\|[^}]+)?)(\s*)\}/g,function(a,b,f,e,g){var h=d[f],k=!1;"undefined"==typeof h&&(k=!0);if(e){e=e.split("|").filter(function(a){return a});for(var l=0,m=e.length;l<m;l++){var n=e[l].split(/[:,\s]+/g),z=n.shift();if(z)if(c[z])h= c[z](h,n,d);else if("'"==z[0]&&"'"===z[z.length-1]||'"'==z[9]&&'"'===z[z.length-1])h||(h=z.slice(1,-1));else throw Error("Unknown filter: `"+z+'` in "'+a+'"');}}k&&!h&&console.warn("Template var `"+f+'` not found in context. String: "'+a+'" Context:',d);return b+(h||"")+g})};var m=a.namespace("Squarespace.ObjectBuilder");m.operations="include update when value template concat trim".split(" ");m.walkObject=c;m.build=h;m.make=k;m.makeArray=function(a,b,d){var c=[];c.push({obj:a});b&&c.push(b);d&&c.push(d); return k.apply(m,c).obj}},"1.0",{requires:["oop"]})},function(c,b){YUI.add("squarespace-plugin-progress-bar",function(a){a.namespace("Squarespace.Plugin");var b=a.Squarespace.Plugin.ProgressBar=a.Base.create("ProgressBar",a.Squarespace.Plugin.ProgressBase,[],{_renderContent:function(){b.superclass._renderContent.call(this);this._syncProgressBar()},_bindAttributeChanges:function(){b.superclass._bindAttributeChanges.call(this);this.after("progressChange",this._syncProgressBar,this)},_syncProgressBar:function(){var a= this._meterEl.one(".bar-inner"),b=this.get("progress"),b=Math.max(0,Math.min(100,0+b));a.setStyle("width",b+"%")}},{NS:"progress-bar",PROGRESS_METER_TEMPLATE:'<div class="bar"><div class="bar-inner"></div></div>',ATTRS:{progress:{value:0,validator:function(b,d){return a.Lang.isNumber(b)&&0<=b&&100>=b}}}})},"1.0",{requires:["base","squarespace-plugin-progress-base"]})},function(c,b){YUI.add("squarespace-plugin-progress-base",function(a){a.namespace("Squarespace.Plugin");a.Squarespace.Plugin.ProgressBase= a.Base.create("ProgressBase",a.Plugin.Base,[],{initializer:function(){this._renderContent();this._bindAttributeChanges();this._setClasses();this._bindContent()},destructor:function(){var b=this._contentEl;b&&b.getDOMNode()&&(b.setStyle("opacity",0),a.later(this.get("unplugDelay"),b,b.remove));this._cancelEl=this._meterEl=this._contentEl=null;this.get("host").removeClass("progress-show-meter");this.get("host").removeClass("progress-show-cancel")},_renderContent:function(){var b=this._contentEl=a.Node.create('<div class="progress-container"><div class="progress"><div class="cancel-process">Cancel</div></div></div>'), c=b.one(".progress");this._meterEl=a.Node.create(this.constructor.PROGRESS_METER_TEMPLATE);c.prepend(this._meterEl);this._cancelEl=b.one(".cancel-process");c=this.get("host");this.get("append")?c.append(b):c.prepend(b)},_bindAttributeChanges:function(){this.after(["showChange","showCancelChange"],this._setClasses,this)},_setClasses:function(){var a=this.get("host"),b=this.get("show"),d=this.get("showCancel");a.toggleClass("progress-show-meter",b);this._meterEl.toggleClass("visible",b);a.toggleClass("progress-show-cancel", d);this._cancelEl.toggleClass("visible",d)},_bindContent:function(){this._cancelEl.on("click",function(a){a.halt();this.fire("cancel")},this)}},{NS:"progress",PROGRESS_METER_TEMPLATE:"",ATTRS:{show:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},showCancel:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},unplugDelay:{value:300,validator:a.Squarespace.AttrValidators.isNumber},append:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"}}})},"1.0",{requires:["base", "node","plugin","squarespace-attr-validators"]})},,,,,,,function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d=a(1355);a=function(){function a(){(0,e.default)(this,a);this.generateActions("success","clearErrorMessage")}(0,f.default)(a,[{key:"recover",value:function(a){var b=this;this.dispatch();d.recover({websiteIdentifier:a}).then(function(){b.actions.success()},function(a){b.actions.failure(a)}).catch(function(a){return console.error(a)})}}, {key:"failure",value:function(a){this.dispatch(a.data.message)}}]);return a}();c.exports=b.createActions(a)},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b,a){function e(a){return a&&a.__esModule?a:{"default":a}}b=a(13);var f=e(b);b=a(18);var d=e(b);b=a(19);var g=e(b),h=a(2);b=a(231);var k=b.CSSTransitionGroup,l=b.CSSTransitionGroupPresets,m=a(1205),n=a(125),s=a(1207),q=a(1224);a=a(28);a=h.createClass({displayName:"WebsiteList",propTypes:{memberAccountId:h.PropTypes.string,items:h.PropTypes.array, currentWebsiteIdentifier:h.PropTypes.string.isRequired,addIndicator:h.PropTypes.shape({label:h.PropTypes.string,onClick:h.PropTypes.func}),deleteEnabled:h.PropTypes.bool,onItemSelect:h.PropTypes.func,onItemDelete:h.PropTypes.func,onItemRemoveAccess:h.PropTypes.func,appDomain:h.PropTypes.string.isRequired,theme:a.isRequired},getDefaultProps:function(){return{theme:"damask"}},removeHttpAndWwwFromUrl:function(a){return a.replace(/(?:https?:\/\/)?(?:www\.)?(.*)\/?$/i,"$1")},generateLabel:function(a){return(0, g.default)(s).find(function(b){return 0<=s[b].indexOf(a)})},generateDescription:function(a,b,d,c){var f=this.props.appDomain;return d===n.ACTIVE_PARKING_PAGE?(a=c.length,""+a+" "+(1===a?"Domain":"Domains")):b?this.removeHttpAndWwwFromUrl(b):a?a+"."+f:""},render:function(){var a=this,b=this.props,c=b.items,e=b.appDomain,g=b.currentWebsiteIdentifier,s=b.memberAccountId,w=b.addIndicator,y=b.theme,B=b.deleteEnabled,A=b.onItemSelect,z=b.onItemDelete,C=b.onItemRemoveAccess;return h.createElement(k,(0,f.default)({className:q.websites, wrapChildWithTag:!1},l.Reorderable),c.map(function(b){var c=b.identifier,k=b.siteTitle,p=b.ownerMemberAccountId,l=b.siteStatus,t=(0,d.default)(b,["identifier","siteTitle","ownerMemberAccountId","siteStatus"]),q=c===g,p=s===p,k=l===n.ACTIVE_PARKING_PAGE?a.removeHttpAndWwwFromUrl(t.url):k;return h.createElement(m,(0,f.default)({title:k,description:a.generateDescription(c,t.url,l,t.domains),label:a.generateLabel(l),key:c,identifier:c,siteStatus:l,theme:y,isCurrent:q,isSiteOwner:p,isDeleteEnabled:B,onSelect:function(){A(b, c===g)},onDelete:function(a){a.preventDefault();a.stopPropagation();z(b)},onRemoveAccess:function(a){a.preventDefault();a.stopPropagation();C(b)},appDomain:e},t))}).concat([w&&h.createElement(m,{key:"addIndicator",identifier:"addIndicator",title:w.label,currentWebsiteIdentifier:g,onAddIndicatorClick:w.onClick})]))}});c.exports=a},,function(c,b){c.exports=["squarespace","google","twitter","facebook","guest"]},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b,a){var e=(b=a(4))&& b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b},d=a(249).getDomainForIdentifier,g=a(541);a=function(){function a(b,c){(0,e.default)(this,a);this.target=b;this.domain=c?"https://"+d(c):document.referrer}(0,f.default)(a,[{key:"send",value:function(a){this.target.postMessage(a,this.domain)}},{key:"requestClose",value:function(){this.send({type:g.CLOSE})}},{key:"requestRedirect",value:function(a){this.send({type:g.REDIRECT,location:a})}}]);return a}();c.exports=a},,,,,,,,,function(c, b,a){b=c.exports=a(3)();b.i(a(142),void 0);b.i(a(23),void 0);b.push([c.id,".Navigation-container-2FsbB {\n box-sizing: border-box;\n padding: 22px 11px;\n width: 100%;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n}\n.Navigation-container-2FsbB.Navigation-damask-JAKNA {\n padding: 0;\n padding-top: 22px;\n}\n.Navigation-buttonWrapper-1cFpN {\n width: 50%;\n}\n.Navigation-buttonWrapper-1cFpN.Navigation-left-3T3Ow {\n padding-right: 11px;\n}\n.Navigation-buttonWrapper-1cFpN.Navigation-right-1ZnUI {\n padding-left: 11px;\n}\n.Navigation-leftButton_midnight-3QqM6 {\n}\n.Navigation-rightButton_midnight-2KgIl {\n}\n.Navigation-leftButton_damask-cQnnd {\n}\n.Navigation-rightButton_damask-176IJ {\n}\n.Navigation-forceStack-_mrWJ.Navigation-container-2FsbB,\n.Navigation-damask-JAKNA.Navigation-container-2FsbB {\n -webkit-flex-wrap: wrap-reverse;\n -ms-flex-wrap: wrap-reverse;\n flex-wrap: wrap-reverse;\n}\n.Navigation-forceStack-_mrWJ .Navigation-buttonWrapper-1cFpN,\n.Navigation-damask-JAKNA .Navigation-buttonWrapper-1cFpN {\n width: 100%;\n padding: 0;\n}\n.Navigation-forceStack-_mrWJ .Navigation-leftButton-1N6CO,\n.Navigation-damask-JAKNA .Navigation-leftButton-1N6CO {\n margin-top: 11px;\n}\n.Navigation-damask-JAKNA.Navigation-container-2FsbB .Navigation-leftButton-1N6CO {\n display: none;\n}\n@media screen and (max-width: 600px) {\n .Navigation-container-2FsbB {\n -webkit-flex-wrap: wrap-reverse;\n -ms-flex-wrap: wrap-reverse;\n flex-wrap: wrap-reverse;\n }\n .Navigation-buttonWrapper-1cFpN.Navigation-left-3T3Ow,\n .Navigation-buttonWrapper-1cFpN.Navigation-right-1ZnUI {\n width: 100%;\n padding: 0;\n }\n .Navigation-leftButton-1N6CO {\n margin-top: 11px;\n }\n}\n", ""]);b.locals={container:"Navigation-container-2FsbB",damask:"Navigation-damask-JAKNA",buttonWrapper:"Navigation-buttonWrapper-1cFpN",left:"Navigation-left-3T3Ow",right:"Navigation-right-1ZnUI",leftButton_midnight:"Navigation-leftButton_midnight-3QqM6 "+a(142).locals.minor+"",rightButton_midnight:"Navigation-rightButton_midnight-2KgIl "+a(142).locals.primary+"",leftButton_damask:"Navigation-leftButton_damask-cQnnd "+a(23).locals.minor+"",rightButton_damask:"Navigation-rightButton_damask-176IJ "+a(23).locals.primary+ "",forceStack:"Navigation-forceStack-_mrWJ",leftButton:"Navigation-leftButton-1N6CO"}},function(c,b,a){b=c.exports=a(3)();b.i(a(45),void 0);b.push([c.id,".DomainFirst-midnight-3nWy7.DomainFirst-narrowPane-mPgeN {\n margin: 0 25%;\n}\n@media screen and (max-width: 902px) {\n .DomainFirst-midnight-3nWy7.DomainFirst-narrowPane-mPgeN {\n margin: 0 15%;\n }\n}\n@media screen and (max-width: 600px) {\n .DomainFirst-midnight-3nWy7.DomainFirst-narrowPane-mPgeN {\n margin: 0;\n }\n}\n.DomainFirst-midnight-3nWy7 .DomainFirst-header-o5hLb {\n padding-top: 22px;\n color: #ffffff;\n text-align: center;\n}\n.DomainFirst-midnight-3nWy7 .DomainFirst-body-3f7X9 {\n margin: 0;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-flex-wrap: wrap;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n padding-bottom: 22px;\n}\n.DomainFirst-heading_damask-MolHm {\n}\n", ""]);b.locals={midnight:"DomainFirst-midnight-3nWy7",narrowPane:"DomainFirst-narrowPane-mPgeN",header:"DomainFirst-header-o5hLb",body:"DomainFirst-body-3f7X9",heading_damask:"DomainFirst-heading_damask-MolHm "+a(45).locals.headlineLarge+""}},function(c,b,a){b=a(1124);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,,,,function(c,b,a){var e=a(266),f=a(156),d=a(70),g=a(225);c.exports=function(a,b,c){if(null==a)return a;var m=b+"";b=null!=a[m]||f(b,a)?[m]:g(b);for(var m= -1,n=b.length,s=n-1,q=a;null!=q&&++m<n;){var r=b[m];d(q)&&(m==s?q[r]=c:null==q[r]&&(q[r]=e(b[m+1])?[]:{}));q=q[r]}return a}},,,,,,,,,,,,function(c,b){YUI.add("squarespace-abtest",function(a){function b(e,v){function x(b){b=a.JSON.stringify({name:b.name,totalFrequencyUnits:b.totalFrequencyUnits,variations:b.variations});return a.Squarespace.MurmurHash.hash(b)}function w(a){for(var b={name:a.name,totalFrequencyUnits:a._total_units,variations:[],conversionGoal:a._conversion_goal},d=0;d<a._variations.length;d++){var c= a._variations[d];b.variations.push({name:c.name,frequency:c.units,item:null==c.item?null:c.item.toString()})}b.variations.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0});b.hash=x(b);return b}function y(a){if(!a._finalized){if(2>a._variations.length)throw Error("Must have at least two variations defined.");a._variations.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0});var b=0,d=[],c=[];a._variations.forEach(function(a){a.units!=s?(b+=a.units,d.push(a)):c.push(a)});if(0< c.length){if(b>=a._total_units)throw Error("Total units for variations excluding the REMAINDER variations must be less than total units of "+a._total_units+", instead of "+b);var f=a._total_units-b,e=Math.floor(f/c.length),g=f%c.length;if(1>e)throw Error("Remaining "+f+" units cannot be distributed among "+c.length+" variations.");for(f=0;f<c.length;f++){var h=c[f];h.units=f+1==c.length?e+g:e;b+=h.units;d.push(h)}}if(b!=a._total_units)throw Error("Total units for all variations must equal the specified total units of "+ a._total_units+", instead of "+b);a._variations=d;if(null==a._conversion_goal)throw Error("Must define a conversionGoal for a test");a._description=w(a);a._finalized=!0}}if(!c.test(e))throw Error("Test name must match regex "+c);if(void 0===v)v=100;else if(!("number"===typeof v&&Math.floor(v)===v)||2>v)throw Error("Units must be an integer > 2, not: "+v);this.name=e;this._variations=[];this._conversion_goal=null;this._total_units=v;this._selection_listeners=[];this._participation_filters=[];this._item_for_non_participant= null;this._finalized=!1;this.variation=function(a,b,c){var f;if(2==arguments.length)c=b,f=s;else if(f=parseInt(b,10),isNaN(f)||1>f)throw Error("Units must be a number > 0, not: "+b);if(!d.test(a))throw Error("Variation name must match regex "+d);if(this._finalized)throw Error("Cannot add a variation to a test already finalized and used for selection");for(var e=0;e<this._variations.length;e++)if(a==this._variations[e].name)throw Error("Already have a test variation with name: "+a);this._variations.push({name:a, units:f,item:c});return this};this.conversionGoal=function(a,b){if(null!=this._conversion_goal)throw Error("Already defined a conversion goal: "+this._conversion_goal);if(!g.test(a))throw Error("Conversion goal name must match regex "+g);void 0===b&&(b=m);if(isNaN(b))throw Error("percent_change_target for a conversion goal must be number");if(1<b||-1>b)throw Error("percent_change_target is a fraction, e.g. 0.10 for 10%. Cannot exceed 1 or be less than -1.");this._conversion_goal={metric:a,targetPercentChange:b}; return this};this.filter=function(a,b){this._participation_filters.push(a);1<arguments.length&&(this._item_for_non_participant=b);return this};this.filterOutParticipantsInOtherTests=function(a,b){return 1<arguments.length?this.filter(t(a),b):this.filter(t(a))};this.requireParticipationInOtherTests=function(a,b){return 1<arguments.length?this.filter(p(a),b):this.filter(p(a))};this.itemForNonParticipant=function(a){this._item_for_non_participant=a;return this};this.addSelectionListener=function(a){this._selection_listeners.push(a); return this};this.removeSelectionListener=function(a){a=this._selection_listeners.indexOf(a);0<=a&&this._selection_listeners.splice(a,1);return this};this.pastParticipationKey=function(){y(this);return this.name+":"+this._description.hash};this.select=function(){y(this);var b,d=a.Cookie.get(k);b=null==d?{}:a.QueryString.parse(d);var c=a.Cookie.get(h)||"",f=null,e=null,d=!0;if(void 0!==b[this.pastParticipationKey()])a:{for(var f=this._variations,g=b[this.pastParticipationKey()],p=0;p<f.length;p++)if(f[p].name== g){f=f[p];break a}f=null}if(null==f){f=!1;for(g=0;g<this._participation_filters.length;g++)if(!this._participation_filters[g](c,b)){f=!0;break}if(f)f={name:r,units:q,item:this._item_for_non_participant},d=!1;else{for(var e=(Math.abs(a.Squarespace.MurmurHash.hash(c+this.name,l))&65535)%this._total_units,f=this._variations,g=null,m=p=0,t=0;t<f.length;t++){g=f[t];m=p+g.units;if(e>=p&&e<m)break;p=m}if(!g)throw Error("No variation found for bucket id: "+e);f=g;b[this.pastParticipationKey()]=f.name}}b= {test:this,selected:f,bucket_id:e,user:c,participations:b};if(d)try{a.Cookie.set(k,a.QueryString.stringify(b.participations)),a.io("/api/events/ABTest",{data:{variation:b.selected.name,selectionCriteria:b.user,description:a.JSON.stringify(b.test._description)},on:{}})}catch(s){console.log("ABTest selection recording error: "+s)}for(d=0;d<n.length;d++)try{n[d](b)}catch(v){console.log("Global selection listener error: "+v)}for(d=0;d<this._selection_listeners.length;d++)try{this._selection_listeners[d](b)}catch(u){console.log("Selection listener error: "+ u)}return f.item};return this}a.namespace("Squarespace");var c=/^[a-zA-Z]\w{0,63}$/,d=/^[a-zA-Z0-9][\w ]{0,63}$/,g=/^[a-zA-Z0-9].{0,250}$/,h="SS_MID",k="SS_ABPP",l=42,m=0.1,n=[],s=-1,q=0,r="__non_participant__",t=function(b){if(!a.Array.test(b)||!b.length)throw Error("Must provide a non-empty array of test names");var d=a.Array(b);return function(b,c){return!a.Object.some(c,function(b,c){var f=c.indexOf(":");if(0>f)return!1;var e=c.substring(0,f);return a.Array.some(d,function(a){return e==a})?!0: !1})}},p=function(b){if(!a.Array.test(b)||!b.length)throw Error("Must provide a non-empty array of test names");var d={};a.Array.each(b,function(a){d[a]=!1});return function(b,c){a.Object.each(c,function(b,c){var f=c.indexOf(":");if(0>f)return!1;f=c.substring(0,f);a.Object.hasKey(d,f)&&(d[f]=!0)});return!a.Object.some(d,function(a,b){return!a})}};a.Squarespace.ABTest={newTest:function(a,d){return new b(a,d)},addSelectionListener:function(a){n.push(a)},removeSelectionListener:function(a){a=n.indexOf(a); 0<=a&&n.splice(a,1)}}},"1.0",{requires:"cookie io-base json querystring-parse-simple querystring-stringify-simple squarespace-murmurhash".split(" ")})},,function(c,b){YUI.add("squarespace-dialog-hidden",function(a){var b=function(){};a.namespace("Squarespace.DialogFields").Hidden=a.Base.create("hidden",a.Squarespace.DialogField2,[],{initializer:function(){this.unplug(a.Plugin.WidgetAnim)},focus:null,enable:null,disable:null,blur:null,renderUI:b,bindUI:b,syncUI:b},{CSS_PREFIX:"sqs-hidden",ATTRS:{visible:{value:!1}, focusable:{value:!1}}});a.Squarespace.DialogFields.HiddenField=a.Squarespace.DialogFields.Hidden},"1.0",{requires:["base","squarespace-dialog-field-2"]})},,function(c,b){YUI.add("squarespace-json-template",function(a){function b(a){return a.replace(/([\{\}\(\)\[\]\|\^\$\-\+\?])/g,"\\$1")}function c(a,d){var f=q[a+d];void 0===f&&(f="("+b(a)+"\\S.*?"+b(d)+"\n?)",f=RegExp(f,"g"));return f}function d(a,b){var d=[{context:a,index:-1}];return{PushSection:function(a){if(void 0===a||null===a)return null; a="@"==a?d[d.length-1].context:d[d.length-1].context[a]||null;d.push({context:a,index:-1});return a},Pop:function(){d.pop()},next:function(){var a=d[d.length-1];-1==a.index&&(a={context:null,index:0},d.push(a));var b=d[d.length-2].context;if(a.index==b.length)d.pop();else return a.context=b[a.index++],!0},_Undefined:function(a){return void 0===b?null:b},_LookUpStack:function(a){for(var b=d.length-1;;){var c=d[b];if("@index"==a){if(-1!=c.index)return c.index}else if(c=c.context,"object"===typeof c&& (c=c[a],void 0!==c))return c;b--;if(-1>=b)return this._Undefined(a)}},get:function(a){if("@"==a)return d[d.length-1].context;var b=a.split("."),c=this._LookUpStack(b[0]);if(1<b.length)for(var f=1;f<b.length;f++){if(null===c)return"[JSONT: Can't resolve '"+a+"'.]";c=c[b[f]];if(void 0===c)return this._Undefined(b[f])}return c}}}function g(a,b,d){for(var c=0;c<a.length;c++){var f=a[c];if("string"==typeof f)d(f);else(0,f[0])(f[1],b,d)}}function h(a,b,d){var c;c=b.get(a.name);for(var f=0;f<a.formatters.length;f++){var e= a.formatters[f];c=(0,e[0])(c,b,e[1])}d(c)}function k(a,b,d){var c=b.PushSection(a.section_name),f=!1;c&&(f=!0);c&&0===c.length&&(f=!1);f?(g(a.Statements(),b,d),b.Pop()):(b.Pop(),g(a.Statements("or"),b,d))}function l(a,b,d){for(var c=b.get("@"),f=0;f<a.clauses.length;f++){var e=a.clauses[f],h=e[1];if((0,e[0][0])(c,b,e[0][1])){g(h,b,d);break}}}function m(a,b,d){var c=b.PushSection(a.section_name);if(c&&0<c.length){var c=c.length-1,f=a.Statements();a=a.Statements("alternate");for(var e=0;void 0!==b.next();e++)g(f, b,d),e!=c&&g(a,b,d)}else g(a.Statements("or"),b,d);b.Pop()}function n(b,d){function e(b){if(b.startsWith(s)){var c=d.partials[b.substr(s.length)];if(c)return[function(b,d,f){return a.JSONTemplate.evaluateJsonTemplate(c,b)},null];throw{name:"BadPartialInclude",message:b.substr(s)+" is not a valid partial. Remember, loops are not supported (a partial include cannot be included inside itself)."};}var f=n.lookup(b);if(!f[0])throw{name:"BadFormatter",message:b+" is not a valid formatter"};return f}function g(a){var b= u.lookup(a);if(!b[0])throw{name:"BadPredicate",message:a+" is not a valid predicate"};return b}var n=new p([r(a.JSONTemplate.DEFAULT_FORMATTERS),t(a.JSONTemplate.DEFAULT_PREFIX_FORMATTERS)]),u=p([r(a.JSONTemplate.DEFAULT_PREDICATES),t(a.JSONTemplate.DEFAULT_PARAMETRIC_PREDICATES)]),q=d.format_char||"|";if(":"!=q&&"|"!=q)throw{name:"ConfigurationError",message:"Only format characters : and | are accepted"};var F=d.meta||"{}",K=F.length;if(1==K%2)throw{name:"ConfigurationError",message:F+" has an odd number of metacharacters"}; for(var T=F.substring(0,K/2),F=F.substring(K/2,K),K=c(T,F),H=v({}),S=[H],Q=T.length,J,E,U=0;;){J=K.exec(b);if(null===J)break;else E=J[0];J.index>U&&(U=b.slice(U,J.index),H.Append(U));U=K.lastIndex;J=!1;"\n"==E.slice(-1)&&(E=E.slice(null,-1),J=!0);E=E.slice(Q,-Q);if("#"!=E.charAt(0)){if("."==E.charAt(0)){E=E.substring(1,E.length);var M={"meta-left":T,"meta-right":F,space:" ",tab:"\t",newline:"\n"}[E];if(void 0!==M){H.Append(M);continue}if(M=E.match(y)){E=M[3];M[1]?(J=m,E=x({section_name:E})):(J=k, E=v({section_name:E}));H.Append([J,E]);S.push(E);H=E;continue}var R;if(M=E.match(B)){J=(R=M[1])?g(R):null;H.NewOrClause(J);continue}var M=!1,G=E.match(A);if(G){if(R=G[1],M=!0,-1==R.indexOf("?")){J=[function(a){return function(b,d){var c,f,e;if(-1!==a.indexOf(" || ")){c=a.split("||");for(e=0;e<c.length;e++)if(f=c[e].trim(),d.get(f))return!0;return!1}if(-1!==a.indexOf(" && ")){c=a.split(" && ");for(e=0;e<c.length;e++)if(f=c[e].trim(),!d.get(f))return!1;return!0}return d.get(a)}}(R),null];E=w();E.NewOrClause(J); H.Append([l,E]);S.push(E);H=E;continue}}else if("?"==E.charAt(E.length-1)||"?"==E.split(" ")[0].charAt(E.split(" ")[0].length-1))R=E,M=!0;if(M){J=R?g(R):null;E=w();E.NewOrClause(J);H.Append([l,E]);S.push(E);H=E;continue}if("alternates with"==E){H.AlternatesWith();continue}if("end"==E){S.pop();if(0<S.length)H=S[S.length-1];else throw{name:"TemplateSyntaxError",message:"Got too many {end} statements"};continue}}G=E.split(q);if(1==G.length)M=[e("str")];else{M=[];for(E=1;E<G.length;E++)M.push(e(G[E])); E=G[0]}H.Append([h,{name:E,formatters:M}]);J&&H.Append("\n")}}H.Append(b.slice(U));if(1!==S.length)throw{name:"TemplateSyntaxError",message:"Got too few {end} statements."};return H}a.namespace("JSONTemplate");var s="apply ",q={};a.JSONTemplate.DEFAULT_FORMATTERS=a.Squarespace.TEMPLATE_FORMATTERS;a.JSONTemplate.DEFAULT_PREFIX_FORMATTERS=[].concat(a.Squarespace.TEMPLATE_PREFIX_FORMATTERS,[{name:"pluralize",func:function(a,b,d){switch(d.length){case 0:b="";d="s";break;case 1:b="";d=d[0];break;case 2:b= d[0];d=d[1];break;default:throw{name:"EvaluationError",message:"pluralize got too many args"};}return 1==a?b:d}},{name:"encode-space",func:function(a,b,d){return a.replace(/\s/g,"&nbsp;")}},{name:"truncate",func:function(a,b,d){b=d[0]||100;d=d[1]||"...";a&&a.length>b&&(a=a.substring(0,b),a=a.replace(/\w+$/,""),a+=d);return a}},{name:"date",func:function(b,d,c){var f=0,f=(new Date(b)).getTimezoneOffset();if(!a.Lang.isNumber(b))return"Invalid date.";if("undefined"!==typeof TimezoneJS){var e;try{e=new TimezoneJS.Date(b, d.get("website.timeZone"))}catch(g){return"Invalid Timezone"}f=(isNaN(e.getTimezoneOffset())?0:e.getTimezoneOffset())-f}else d=-parseInt(d.get("website.timeZoneOffset"),10)/6E4,e=(new Date).getTimezoneOffset(),f=d-e;b=new Date(b-6E4*f);c=c.join(" ");return a.DataType.Date.format(b,{format:c})}},{name:"image",func:function(b,d,c){var f;b.mediaFocalPoint&&(f=b.mediaFocalPoint.x+","+b.mediaFocalPoint.y);return'<img class="'+(c[0]?c[0]:"thumb-image")+'" '+(b.title?'alt="'+a.Squarespace.Escaping.escapeForHtmlTag(b.title)+ '" ':"")+' data-image="'+b.assetUrl+'" data-image-dimensions="'+b.originalSize+'" data-image-focal-point="'+f+'"/>'}},{name:"timesince",func:function(b,d,c){if(!a.Lang.isNumber(b))return"Invalid date.";c.join(" ");return'<span class="timesince" data-date="'+b+'">'+a.Squarespace.DateUtils.humanizeDate(b)+"</span>"}},{name:"resizedHeightForWidth",func:function(a,b,d){b=a.split("x");if(2!=b.length)return"Invalid source parameter. Pass in 'originalSize'.";a=parseInt(b[0],10);b=parseInt(b[1],10);d=parseInt(d[0], 10)/a;return parseInt(b*d,10)}},{name:"resizedWidthForHeight",func:function(a,b,d){b=a.split("x");if(2!=b.length)return"Invalid source parameter. Pass in 'originalSize'.";a=parseInt(b[0],10);b=parseInt(b[1],10);d=parseInt(d[0],10)/b;return parseInt(a*d,10)}},{name:"squarespaceThumbnailForWidth",func:function(b,d,c){return a.Squarespace.Rendering.getSquarespaceSizeForWidth(parseInt(c[0],10))}},{name:"squarespaceThumbnailForHeight",func:function(b,d,c){d=b.split("x");if(2!=d.length)return"Invalid source parameter. Pass in 'originalSize'."; b=parseInt(d[0],10);d=parseInt(d[1],10);c=parseInt(c[0],10)/d;c=parseInt(b*c,10);return a.Squarespace.Rendering.getSquarespaceSizeForWidth(c)}},{name:"cycle",func:function(a,b,d){return d[(a-1)%d.length]}}]);var r=function(a){return{lookup:function(b){return[a[b]||null,null]}}},t=function(a){return{lookup:function(b){for(var d=0;d<a.length;d++){var c=a[d].name,f=a[d].func;if(b.slice(0,c.length)==c)return d=b.charAt(c.length),b=""===d?[]:b.split(d).slice(1),[f,b]}return[null,null]}}},p=function(a){return{lookup:function(b){for(var d= 0;d<a.length;d++){var c=a[d].lookup(b);if(c[0])return c}return[null,null]}}},u=function(a){var b={current_clause:[],Append:function(a){b.current_clause.push(a)},AlternatesWith:function(){throw{name:"TemplateSyntaxError",message:"{.alternates with} can only appear with in {.repeated section ...}"};},NewOrClause:function(a){throw{name:"NotImplemented"};}};return b},v=function(a){var b=u(a);b.statements={"default":b.current_clause};b.section_name=a.section_name;b.Statements=function(a){return b.statements[a|| "default"]||[]};b.NewOrClause=function(a){if(a)throw{name:"TemplateSyntaxError",message:"{.or} clause only takes a predicate inside predicate blocks"};b.current_clause=[];b.statements.or=b.current_clause};return b},x=function(a){var b=v(a);b.AlternatesWith=function(){b.current_clause=[];b.statements.alternate=b.current_clause};return b},w=function(a){var b=u(a);b.clauses=[];b.NewOrClause=function(a){a=a||[function(a){return!0},null];b.current_clause=[];b.clauses.push([a,b.current_clause])};return b}, y=/(repeated)?\s*(section)\s+(\S+)?/,B=/^or(?:[\s\-]+(.+))?/,A=/^if(?:[\s\-]+(.+))?/;a.JSONTemplate.Template=Class.create({initialize:function(a,b,d){a=this.removeMultilineComments(a);this._options=b||{};this._program=n(a,this._options)},removeMultilineComments:function(a){for(var b=a.search("{##"),d;0<=b;)d=a.substr(b),a=a.substr(0,b)+d.substr(d.search("##}")+3),b=a.search("{##");return a},render:function(a,b){var c=d(a,this._options.undefined_str);g(this._program.Statements(),c,b)},expand:function(a){var b= [];this.render(a,function(a){b.push(a)});return b.join("")}});a.JSONTemplate.DEFAULT_PREDICATES=a.Squarespace.TEMPLATE_PREDICATES;a.JSONTemplate.DEFAULT_PARAMETRIC_PREDICATES=a.Squarespace.TEMPLATE_PARAMETRIC_PREDICATES;a.JSONTemplate.evaluateJsonTemplate=function(b,d,c){return"string"!=typeof b?"JSON Template Error: Processing failed because no input was provided. (type: "+typeof b+", template: "+JSON.stringify(b)+", dictionary: "+JSON.stringify(d)+", partials: "+JSON.stringify(c)+")":(new a.JSONTemplate.Template(b, {partials:c})).expand(d)}},"1.0",{requires:"datatype-date-format json squarespace-common squarespace-date-utils squarespace-escaping-utils squarespace-rendering squarespace-template-helpers squarespace-util".split(" ")})},,,,,,,,,,,,,function(c,b){YUI.add("squarespace-models-model-list",function(a){a.namespace("Squarespace.Models");var b=a.Squarespace.Models.ModelList=a.Base.create("ModelList",a.ModelList,[a.Squarespace.ModelSync.REST],{parse:function(c){c=b.superclass.parse.call(this,c);var d=this._getResponseAttrs(c); a.Object.each(d,function(a,b){this._set(b,a)},this);return c.results},_getResponseAttrs:function(a){return{}}})},"1.0",{requires:["base","model-list","squarespace-model-sync-rest"]})},,,,,function(c,b){YUI.add("squarespace-murmurhash",function(a){function b(a){a=a.replace(/[\u0080-\u07ff]/g,function(a){a=a.charCodeAt(0);return String.fromCharCode(192|a>>6,128|a&63)});return a=a.replace(/[\u0800-\uffff]/g,function(a){a=a.charCodeAt(0);return String.fromCharCode(224|a>>12,128|a>>6&63,128|a&63)})}a.namespace("Squarespace"); a.Squarespace.MurmurHash={hash:function(a,d){var c=b(a),h,k,l,m,n;h=c.length&3;k=c.length-h;l=d;for(n=0;n<k;)m=c.charCodeAt(n)&255|(c.charCodeAt(++n)&255)<<8|(c.charCodeAt(++n)&255)<<16|(c.charCodeAt(++n)&255)<<24,++n,m=3432918353*(m&65535)+((3432918353*(m>>>16)&65535)<<16)&4294967295,m=m<<15|m>>>17,m=461845907*(m&65535)+((461845907*(m>>>16)&65535)<<16)&4294967295,l^=m,l=l<<13|l>>>19,l=5*(l&65535)+((5*(l>>>16)&65535)<<16)&4294967295,l=(l&65535)+27492+(((l>>>16)+58964&65535)<<16);m=0;switch(h){case 3:m^= (c.charCodeAt(n+2)&255)<<16;case 2:m^=(c.charCodeAt(n+1)&255)<<8;case 1:m^=c.charCodeAt(n)&255,m=3432918353*(m&65535)+((3432918353*(m>>>16)&65535)<<16)&4294967295,m=m<<15|m>>>17,l^=461845907*(m&65535)+((461845907*(m>>>16)&65535)<<16)&4294967295}l^=c.length;l^=l>>>16;l=2246822507*(l&65535)+((2246822507*(l>>>16)&65535)<<16)&4294967295;l^=l>>>13;l=3266489909*(l&65535)+((3266489909*(l>>>16)&65535)<<16)&4294967295;return l^l>>>16}}},"1.0",{requires:[]})},function(c,b){YUI.add("querystring-parse-simple", function(a,b){var c=a.namespace("QueryString");c.parse=function(a,b,e){e=e||"=";var k={},l=0;a=a.split(b||"&");b=a.length;for(var m;l<b;l++)m=a[l].split(e),0<m.length&&(k[c.unescape(m.shift())]=c.unescape(m.join(e)));return k};c.unescape=function(a){return decodeURIComponent(a.replace(/\+/g," "))}},"3.17.2",{requires:["yui-base"]})},,,function(c,b,a){var e=a(2),f=a(578),d=a(11),g=a(529),h=a(1222),k=a(126),l=a(57);b=a(28);b=e.createClass({displayName:"DomainDestinationPicker",propTypes:{onShowSites:e.PropTypes.func.isRequired, onStartFresh:e.PropTypes.func.isRequired,isVisible:e.PropTypes.bool,theme:b,isLoading:e.PropTypes.bool},getDefaultProps:function(){return{isVisible:!1,isLoading:!1,theme:"midnight"}},componentDidMount:function(){setTimeout(function(){k("domain_first_view",{step:"domain_destination_picker"})},0)},renderBody:function(){var a=this.props,b=a.onShowSites,c=a.onStartFresh,a=a.theme;return e.createElement("div",{className:g[a]},e.createElement("div",{className:d(g.header,h.header)},e.createElement("h1", null,"Use an existing site"),e.createElement("div",null,"Do you want to add this domain to one of your existing sites?")),e.createElement("div",{className:g.body},e.createElement(f,{leftButtonLabel:"No, Just buy a domain",onLeftButtonClick:c,rightButtonLabel:"Yes, Choose which site",onRightButtonClick:b,theme:a,forceStack:!0})))},renderLoading:function(){return e.createElement(l,{size:"extra-large",isCentered:!0,color:"light"})},render:function(){var a,b=this.props,c=b.isLoading,b=b.isVisible;return e.createElement("div", {className:h.overlay},e.createElement("div",{className:d(h.container,(a={},a[h.shown]=b,a[h.loading]=c,a))},c?this.renderLoading():this.renderBody()))}});c.exports=b},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d=a(339),g=a(44),h=a(539),k=a(233),l="/config";a=function(){function a(){(0,e.default)(this,a);this.bindActions(d);this.state={appDomain:null,disambiguationType:null,disambiguationPhase:null,redirectPath:l,currentWebsiteIdentifier:"www", searchQuery:"",searchEnabled:!0};this.bindListeners({onBootstrap:g.BOOTSTRAP})}(0,f.default)(a,[{key:"onShowWebsiteSelector",value:function(){this.setState({disambiguationPhase:h.SELECT_WEBSITE})}},{key:"onRedirect",value:function(){this.setState({disambiguationPhase:h.REDIRECT})}},{key:"onSearch",value:function(a){this.setState({searchQuery:a})}},{key:"onBootstrap",value:function(a){var b=a.disambiguationType;this.setState({appDomain:a.appDomain,currentWebsiteIdentifier:a.currentWebsiteIdentifier, disambiguationPhase:b===k.DOMAIN_FIRST?h.PRE_SELECT:h.SELECT_WEBSITE,disambiguationType:b,redirectPath:a.redirectPath})}}]);return a}();c.exports=b.createStore(a,"WebsiteDisambiguatorStore")},,function(c,b,a){var e=a(2),f=a(1055),d=a(219).Search;b=a(28);var g=a(57),h=a(11),k=a(1226);a=e.createClass({displayName:"WebsiteSelector",propTypes:{appDomain:e.PropTypes.string,heading:e.PropTypes.string,currentWebsiteIdentifier:e.PropTypes.string,websiteSummaries:e.PropTypes.array,hasCloseButton:e.PropTypes.bool, isLoading:e.PropTypes.bool,onSelectWebsite:e.PropTypes.func,onRequestClose:e.PropTypes.func,searchEnabled:e.PropTypes.bool,searchString:e.PropTypes.string,onSearch:e.PropTypes.func,theme:b,shouldShowListWhenOnlyOneWebsite:e.PropTypes.bool},getDefaultProps:function(){return{websiteSummaries:[],isLoading:!0,hasCloseButton:!1,searchEnabled:!0,theme:"midnight",appDomain:"",currentWebsiteIdentifier:"www",shouldShowListWhenOnlyOneWebsite:!0}},componentWillMount:function(){var a=this.props,b=a.websiteSummaries, d=a.onSelectWebsite;!a.shouldShowListWhenOnlyOneWebsite&&1===b.length&&d(b[0])},renderSearchBar:function(){var a=this.props,b=a.onSearch,c=a.searchString,f=a.websiteSummaries;return a.searchEnabled&&1<f&&e.createElement("div",{className:k.search},e.createElement(d,{onChange:b,value:c,placeholder:"Search sites and domains",className:k.searchField}))},render:function(){var a=this.props,b=a.appDomain,d=a.currentWebsiteIdentifier,c=a.hasCloseButton,q=a.heading,r=a.websiteSummaries,t=a.onSelectWebsite, p=a.onRequestClose,u=a.searchString,v=a.shouldShowListWhenOnlyOneWebsite,x=a.theme;if(a.isLoading||1===r.length&&!v)return e.createElement(g,{className:k.spinner,color:"light",isCentered:!0,size:"extra-large"});a="https://www."+b+"/websites?source="+d+"&channel=account-picker";u=!!u&&0<u.length;return e.createElement("div",{className:h(k.container,k[x])},e.createElement("div",{className:k.header},e.createElement("h3",{className:k.heading},q),this.renderSearchBar(),c&&e.createElement("div",{className:k.closeWrapper}, e.createElement("div",{className:k.closeButton,onClick:p}))),e.createElement("div",{className:k.body},0<r.length&&e.createElement(f,{items:r,onItemSelect:t,currentWebsiteIdentifier:d,appDomain:b,theme:x}),0===r.length&&!u&&e.createElement("div",{className:k.noItems},e.createElement("div",{className:k.description},"Your account needs a website."),e.createElement("a",{href:a},"Get started here."))))}});c.exports=a},,,,,,,,,,function(c,b,a){var e=a(271),f=a(161),d=a(73);b=Object.prototype;var g=b.hasOwnProperty, h=b.toString;c.exports=function(a){var b;if(!d(a)||("[object Object]"!=h.call(a)||f(a))||!g.call(a,"constructor")&&(b=a.constructor,"function"==typeof b&&!(b instanceof b)))return!1;var c;e(a,function(a,b){c=b});return void 0===c||g.call(a,c)}},function(c,b,a){var e=a(278),f=a(265),d=a(161),g=a(27),h=a(266),k=a(156),l=a(92),m=a(321),n=a(225),s=Object.prototype.hasOwnProperty;c.exports=function(a,b){if(null==a)return!1;var c=s.call(a,b);if(!c&&!k(b)){b=n(b);a=1==b.length?a:e(a,f(b,0,-1));if(null== a)return!1;b=m(b);c=s.call(a,b)}return c||l(a.length)&&h(b,a.length)&&(g(a)||d(a))}},,,,,,,,,,,,,,function(c,b,a){var e=a(25),f=a(230);c.exports={load:function(a){return e.get("/api/website-summaries",{params:{status:f(a)?a:null}})},deleteWebsite:function(a){return e.delete("/api/rest/websites/"+a)},removeWebsiteAccess:function(a){return e.delete("/api/rest/websites/"+a+"/member-permissions/mine")}}},,,function(c,b,a){b=(b=a(154))&&b.__esModule?b:{"default":b};var e=a(2),f=e.PropTypes,d=a(1171),g= a(1174),h=a(539),k=a(1223);a=e.createClass({displayName:"WebsiteDisambiguator",propTypes:{appDomain:f.string,disambiguationPhase:f.oneOf((0,b.default)(h)),filteredWebsiteSummaries:e.PropTypes.arrayOf(e.PropTypes.shape({identifier:e.PropTypes.string.isRequired})),heading:f.string,onSearch:f.func,onWebsiteSelected:f.func,onNoWebsites:f.func,currentWebsiteIdentifier:f.string,onRequestClose:f.func,domainDestinationPickerConfig:f.shape({onShowSites:e.PropTypes.func.isRequired,onStartFresh:e.PropTypes.func.isRequired, isVisible:e.PropTypes.bool}),searchEnabled:f.bool,searchQuery:f.string,websiteSummaries:e.PropTypes.arrayOf(e.PropTypes.shape({identifier:e.PropTypes.string.isRequired})),shouldShowListWhenOnlyOneWebsite:e.PropTypes.bool},getDefaultProps:function(){return{shouldShowListWhenOnlyOneWebsite:!0}},componentWillMount:function(){var a=this.props,b=a.onNoWebsites,a=a.websiteSummaries;b&&0===a.length&&b()},renderDomainDestinationPicker:function(){return e.createElement(d,this.props.domainDestinationPickerConfig)}, renderWebsiteSelector:function(){var a=this.props,b=a.onRequestClose;return e.createElement(g,{appDomain:a.appDomain,websiteSummaries:a.filteredWebsiteSummaries,onSelectWebsite:a.onWebsiteSelected,heading:a.heading,currentWebsiteIdentifier:a.currentWebsiteIdentifier,onRequestClose:b,hasCloseButton:null!==b,searchString:a.searchQuery,onSearch:a.onSearch,searchEnabled:a.searchEnabled,shouldShowListWhenOnlyOneWebsite:a.shouldShowListWhenOnlyOneWebsite,isLoading:a.disambiguationPhase===h.REDIRECT})}, render:function(){return e.createElement("div",{className:k.disambiguatorOverlay},this.props.disambiguationPhase===h.PRE_SELECT?this.renderDomainDestinationPicker():this.renderWebsiteSelector())}});c.exports=a},,,function(c,b,a){var e=(b=a(16))&&b.__esModule?b:{"default":b},f=a(11),d=a(2),g=a(879).invert;b=a(879).values;var h=a(28),k=a(125),l=a(94),m=a(267),n=a(1225);a=d.createClass({displayName:"WebsiteListItem",propTypes:{description:d.PropTypes.string,label:d.PropTypes.string,title:d.PropTypes.string.isRequired, id:d.PropTypes.string,identifier:d.PropTypes.string,isCurrent:d.PropTypes.bool,isSiteOwner:d.PropTypes.bool,isDeleteEnabled:d.PropTypes.bool,domains:d.PropTypes.array,siteStatus:d.PropTypes.number,websiteType:d.PropTypes.oneOf(b(l)),screenshotInfo:d.PropTypes.shape({url:d.PropTypes.string,errorCode:d.PropTypes.string}),onAddIndicatorClick:d.PropTypes.func,onSelect:d.PropTypes.func,onDelete:d.PropTypes.func,onRemoveAccess:d.PropTypes.func,theme:h.isRequired},getDefaultProps:function(){return{domains:[], theme:"damask",screenshotInfo:{}}},renderAddIndicator:function(){var a=this.props,b=a.title;return d.createElement("div",{className:n.container,onClick:a.onAddIndicatorClick},d.createElement("div",{className:n.wrapper},d.createElement("div",{className:n.addIndicator},d.createElement("span",null,"+")),d.createElement("div",{className:n.info},d.createElement("div",{className:n.title},b))))},render:function(){var a=this.props,b=a.description,c=a.domains,h=a.isCurrent,p=a.isSiteOwner,u=a.isDeleteEnabled, v=a.label,x=a.siteStatus,w=a.websiteType,y=a.screenshotInfo,B=a.onSelect,A=a.onDelete,z=a.onRemoveAccess,C=a.title,I=a.theme;if(a.onAddIndicatorClick)return this.renderAddIndicator();a=g(l)[w]||"";w=u&&!h&&!p;c=u&&!h&&p&&!c.some(function(a){return a.type===m.SQUARESPACE})&&(x===k.TRIAL||x===k.EXPIRED);h={};y.url&&!y.errorCode&&(h=(0,e.default)(h,{backgroundImage:"url("+y.url+")"}));return d.createElement("div",{className:f(n.container,n[I])},d.createElement("div",{className:n.wrapper,onClick:B},d.createElement("div", {className:f(n.preview,n[a.toLowerCase()]),style:h},(y.errorCode||!y.url)&&d.createElement("span",null,"Preview image coming soon")),d.createElement("div",{className:n.info},d.createElement("div",{className:n.title},C),d.createElement("div",{className:n.description},b),d.createElement("div",{className:n[v.toLowerCase()]},v)),c&&d.createElement("div",{className:n.deleteWrapper},d.createElement("div",{className:n.deleteButton,onClick:A})),w&&d.createElement("div",{className:n.deleteWrapper},d.createElement("div", {className:n.deleteButton,onClick:z}))))}});c.exports=a},,function(c,b,a){b=a(125);c.exports={active:[b.PAID,b.ACTIVE,b.V5_LINKED,b.PASTDUE,b.COMPED,b.INTERNAL],trial:[b.TRIAL],expired:[b.EXPIRED],removed:[b.REMOVED],domain:[b.ACTIVE_PARKING_PAGE]}},,,,,,,,,,function(c,b,a){b=c.exports=a(3)();b.i(a(142),void 0);b.push([c.id,".DomainDestinationPicker-overlay-2WFuA {\n position: fixed;\n width: 100%;\n height: 100%;\n}\n.DomainDestinationPicker-container-33aF6 {\n width: 440px;\n margin: auto;\n position: relative;\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.DomainDestinationPicker-container-33aF6.DomainDestinationPicker-shown-WtBhs {\n opacity: 1;\n}\n.DomainDestinationPicker-container-33aF6 h1 {\n font-family: 'Gotham A', 'Gotham SSm A', 'Gotham SSm B', 'Gotham', 'Gotham SSm', 'Proxima Nova', 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-weight: 100;\n font-size: 36px;\n line-height: 42px;\n}\n.DomainDestinationPicker-header-N3dvG {\n padding-bottom: 22px;\n}\n.DomainDestinationPicker-primaryButton-2Gjw2 {\n}\n.DomainDestinationPicker-minorButton-1MwF9 {\n margin-top: 22px;\n}\n@media screen and (max-width: 600px) {\n .DomainDestinationPicker-container-33aF6:not(.DomainDestinationPicker-loading-1MV32) {\n top: auto;\n -webkit-transform: none;\n -ms-transform: none;\n transform: none;\n width: 100%;\n padding: 22px;\n box-sizing: border-box;\n }\n .DomainDestinationPicker-container-33aF6:not(.DomainDestinationPicker-loading-1MV32) h1 {\n font-size: 30px;\n }\n}\n", ""]);b.locals={overlay:"DomainDestinationPicker-overlay-2WFuA",container:"DomainDestinationPicker-container-33aF6",shown:"DomainDestinationPicker-shown-WtBhs",header:"DomainDestinationPicker-header-N3dvG",primaryButton:"DomainDestinationPicker-primaryButton-2Gjw2 "+a(142).locals.primary+"",minorButton:"DomainDestinationPicker-minorButton-1MwF9 "+a(142).locals.minor+"",loading:"DomainDestinationPicker-loading-1MV32"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".WebsiteDisambiguator-disambiguatorOverlay-3jNQw {\n font: 400 normal 12px / 22px 'Gotham SSm A', 'Gotham SSm B', 'Gotham SSm', 'Proxima Nova', 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n letter-spacing: normal;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-justify-content: center;\n -ms-flex-pack: center;\n justify-content: center;\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n -webkit-overflow-scrolling: touch;\n -webkit-text-size-adjust: none;\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n background: #000000;\n background: transparent;\n color: #ffffff;\n}\n", ""]);b.locals={disambiguatorOverlay:"WebsiteDisambiguator-disambiguatorOverlay-3jNQw"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,".WebsiteList-websites-3mcvi {\n max-width: 2200px;\n margin: 0 auto;\n}\n",""]);b.locals={websites:"WebsiteList-websites-3mcvi"}},function(c,b,a){b=c.exports=a(3)();b.i(a(90),void 0);b.i(a(24),void 0);b.push([c.id," {\n /* @todo is this still referenced? i don't think so */\n}\n.WebsiteListItem-container-2u2cc {\n display: inline-block;\n width: 33.33333333%;\n box-sizing: border-box;\n padding: 0 44px;\n margin-bottom: 60px;\n vertical-align: top;\n}\n.WebsiteListItem-wrapper-QuP6u {\n position: relative;\n width: 100%;\n margin: 0 auto;\n cursor: pointer;\n border-radius: 4px;\n overflow: hidden;\n}\n.WebsiteListItem-wrapper-QuP6u:hover .WebsiteListItem-deleteWrapper-2ziaT {\n opacity: 1;\n}\n.WebsiteListItem-preview-2rYO- {\n position: relative;\n padding-bottom: 65%;\n background: #e0e0e0 top no-repeat;\n background-size: cover;\n text-align: center;\n}\n.WebsiteListItem-preview-2rYO- span {\n height: 22px;\n font-weight: 500;\n position: absolute;\n top: 50%;\n left: 0;\n right: 0;\n margin-top: -11px;\n}\n.WebsiteListItem-midnight-2uaNx .WebsiteListItem-preview-2rYO- span {\n color: #3e3e3e;\n}\n.WebsiteListItem-info-r-wxv {\n width: 100%;\n position: relative;\n padding-top: 22px;\n background: white;\n padding: 11px;\n box-sizing: border-box;\n min-height: 66px;\n}\n.WebsiteListItem-midnight-2uaNx .WebsiteListItem-info-r-wxv {\n color: #000000;\n}\n.WebsiteListItem-title-6yeQV {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n font-size: 16px;\n margin-right: 70px;\n}\n.WebsiteListItem-addIndicator-2VwNE + .WebsiteListItem-info-r-wxv .WebsiteListItem-title-6yeQV {\n width: auto;\n}\n.WebsiteListItem-description-mweuP {\n font-size: 11px;\n color: #797979;\n}\n.WebsiteListItem-statusBadge-JLLoi {\n position: absolute;\n top: 22px;\n right: 11px;\n}\n.WebsiteListItem-internal-xtglg,\n.WebsiteListItem-trial-2BOm7,\n.WebsiteListItem-comped-IaXXl,\n.WebsiteListItem-active-3s4Zi,\n.WebsiteListItem-paid-39THm,\n.WebsiteListItem-domain-2xBD5 {\n background-color: #e4e4e4;\n}\n.WebsiteListItem-expired-2dxCB,\n.WebsiteListItem-removed-2SJI8,\n.WebsiteListItem-pastdue-EfNZr {\n}\n.WebsiteListItem-bundleBadge-_6EMG {\n display: inline-block;\n position: absolute;\n top: 22px;\n right: 0;\n padding: 5.5px 11px;\n border-radius: 50%;\n background-color: #e4e4e4;\n letter-spacing: -1px;\n font-weight: 500;\n}\n.WebsiteListItem-addIndicator-2VwNE {\n box-sizing: border-box;\n border: 2px dashed #d0d0d0;\n padding-bottom: 65%;\n}\n.WebsiteListItem-addIndicator-2VwNE:hover {\n opacity: 1;\n}\n.WebsiteListItem-addIndicator-2VwNE span {\n display: none;\n}\n.WebsiteListItem-deleteWrapper-2ziaT {\n position: absolute;\n top: 11px;\n right: 11px;\n border-radius: 100%;\n background-color: #fff;\n width: 33px;\n height: 33px;\n opacity: 0;\n transition: opacity 0.1s ease-in-out;\n}\nhtml.touch .WebsiteListItem-deleteWrapper-2ziaT {\n opacity: 1;\n}\n.WebsiteListItem-deleteButton-2YaEH {\n display: inline-block;\n width: 33px;\n height: 33px;\n background-position: center;\n cursor: pointer;\n}\n@media screen and (min-width: 2101px) {\n .WebsiteListItem-container-2u2cc {\n width: 20%;\n }\n}\n@media screen and (max-width: 2100px) {\n .WebsiteListItem-container-2u2cc {\n width: 25%;\n }\n}\n@media screen and (max-width: 1700px) {\n .WebsiteListItem-container-2u2cc {\n width: 33.33333333%;\n }\n}\n@media screen and (max-width: 1100px) {\n .WebsiteListItem-container-2u2cc {\n width: 50%;\n }\n}\n@media screen and (max-width: 750px) {\n .WebsiteListItem-container-2u2cc {\n width: 100%;\n }\n}\n", ""]);b.locals={container:"WebsiteListItem-container-2u2cc",wrapper:"WebsiteListItem-wrapper-QuP6u",deleteWrapper:"WebsiteListItem-deleteWrapper-2ziaT",preview:"WebsiteListItem-preview-2rYO-",midnight:"WebsiteListItem-midnight-2uaNx",info:"WebsiteListItem-info-r-wxv",title:"WebsiteListItem-title-6yeQV",addIndicator:"WebsiteListItem-addIndicator-2VwNE "+a(24).locals.add+"",description:"WebsiteListItem-description-mweuP",statusBadge:"WebsiteListItem-statusBadge-JLLoi",internal:"WebsiteListItem-internal-xtglg "+ a(90).locals.pillNeue+" WebsiteListItem-statusBadge-JLLoi",trial:"WebsiteListItem-trial-2BOm7 "+a(90).locals.pillNeue+" WebsiteListItem-statusBadge-JLLoi",comped:"WebsiteListItem-comped-IaXXl "+a(90).locals.pillNeue+" WebsiteListItem-statusBadge-JLLoi",active:"WebsiteListItem-active-3s4Zi "+a(90).locals.pillNeue+" WebsiteListItem-statusBadge-JLLoi",paid:"WebsiteListItem-paid-39THm "+a(90).locals.pillNeue+" WebsiteListItem-statusBadge-JLLoi",domain:"WebsiteListItem-domain-2xBD5 "+a(90).locals.pillNeue+ " WebsiteListItem-statusBadge-JLLoi",expired:"WebsiteListItem-expired-2dxCB "+a(90).locals.pillNeueRed+" WebsiteListItem-statusBadge-JLLoi",removed:"WebsiteListItem-removed-2SJI8 "+a(90).locals.pillNeueRed+" WebsiteListItem-statusBadge-JLLoi",pastdue:"WebsiteListItem-pastdue-EfNZr "+a(90).locals.pillNeueRed+" WebsiteListItem-statusBadge-JLLoi",bundleBadge:"WebsiteListItem-bundleBadge-_6EMG",deleteButton:"WebsiteListItem-deleteButton-2YaEH "+a(24).locals.clear+""}},function(c,b,a){b=c.exports=a(3)(); b.i(a(24),void 0);b.push([c.id,".WebsiteSelector-container-6qnLP {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n padding-bottom: 44px;\n color: #ffffff;\n overflow-y: scroll;\n -webkit-overflow-scrolling: touch;\n}\n.WebsiteSelector-spinner-29jf6 {\n -webkit-align-self: center;\n -ms-flex-item-align: center;\n align-self: center;\n}\n.WebsiteSelector-header-21y9S {\n text-align: center;\n font-size: 24px;\n margin-top: 77px;\n margin-bottom: 88px;\n}\n.WebsiteSelector-header-21y9S h3 {\n font-weight: 100;\n}\n.WebsiteSelector-midnight-2xrJv .WebsiteSelector-header-21y9S {\n font-family: 'Gotham A', 'Gotham SSm A', 'Gotham SSm B', 'Gotham', 'Gotham SSm', 'Proxima Nova', 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-size: 36px;\n line-height: 42px;\n}\n.WebsiteSelector-body-1_OuW {\n height: 80%;\n}\n.WebsiteSelector-search-3SAAq {\n display: inline-block;\n min-width: 448px;\n margin: 0 auto;\n}\n.WebsiteSelector-noItems-2yn6f {\n font-size: 14px;\n line-height: 23px;\n text-align: center;\n}\n.WebsiteSelector-noItems-2yn6f .WebsiteSelector-description-2PJJe {\n color: #777;\n max-width: 500px;\n margin: 0 auto;\n padding: 10px;\n}\n.WebsiteSelector-closeWrapper-3_Yue {\n height: 100%;\n position: absolute;\n top: 0;\n right: 0;\n text-align: right;\n}\n.WebsiteSelector-closeButton-Z4_tN {\n display: inline-block;\n margin-top: 11px;\n margin-right: 11px;\n width: 44px;\n height: 44px;\n background-position: center;\n cursor: pointer;\n}\n.WebsiteSelector-closeButton-Z4_tN:hover {\n opacity: 1;\n}\n.WebsiteSelector-searchField-2g4-b {\n font-size: 12px;\n}\n@media screen and (max-width: 600px) {\n .WebsiteSelector-midnight-2xrJv .WebsiteSelector-header-21y9S {\n font-size: 30px;\n line-height: 36px;\n margin-top: 55px;\n margin-bottom: 22px;\n }\n .WebsiteSelector-search-3SAAq {\n width: 100%;\n min-width: initial;\n }\n}\n", ""]);b.locals={container:"WebsiteSelector-container-6qnLP",spinner:"WebsiteSelector-spinner-29jf6",header:"WebsiteSelector-header-21y9S",midnight:"WebsiteSelector-midnight-2xrJv",body:"WebsiteSelector-body-1_OuW",search:"WebsiteSelector-search-3SAAq",noItems:"WebsiteSelector-noItems-2yn6f",description:"WebsiteSelector-description-2PJJe",closeWrapper:"WebsiteSelector-closeWrapper-3_Yue",closeButton:"WebsiteSelector-closeButton-Z4_tN "+a(24).locals.clearLight+"",searchField:"WebsiteSelector-searchField-2g4-b"}}, function(c,b,a){b=a(1217);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(1218);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(1219);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(1220);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(1221);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b, {});b.locals&&(c.exports=b.locals)},,,,,,,,,function(c,b){c.exports=function(a,b){return void 0===a?b:a}},function(c,b,a){var e=a(78);c.exports=function(a,b,c){for(var h=-1,k=e(b),l=k.length;++h<l;){var m=k[h],n=a[m],s=c(n,b[m],m,a,b);if((s===s?s!==n:n===n)||void 0===n&&!(m in a))a[m]=s}return a}},,,function(c,b,a){var e=a(534);c.exports=function(a,b){for(var c=-1,h=b.length,k=-1,l=[];++c<h;){var m=b[c];e(a[m])&&(l[++k]=m)}return l}},function(c,b,a){function e(a,b,c,t,p){if(!k(a))return a;var u=h(b)&& (g(b)||m(b)),v=u?void 0:n(b);f(v||b,function(f,g){v&&(g=f,f=b[g]);if(l(f))t||(t=[]),p||(p=[]),d(a,b,g,e,c,t,p);else{var h=a[g],k=c?c(h,f,g,a,b):void 0,m=void 0===k;m&&(k=f);if((void 0!==k||u&&!(g in a))&&(m||(k===k?k!==h:h===h)))a[g]=k}});return a}var f=a(580),d=a(1241),g=a(27),h=a(62),k=a(70),l=a(73),m=a(618),n=a(78);c.exports=e},function(c,b,a){var e=a(744),f=a(161),d=a(27),g=a(62),h=a(1184),k=a(618),l=a(1244);c.exports=function(a,b,c,q,r,t,p){for(var u=t.length,v=b[c];u--;)if(t[u]==v){a[c]=p[u]; return}u=a[c];b=r?r(u,v,c,a,b):void 0;var x=void 0===b;x&&(b=v,g(v)&&(d(v)||k(v))?b=d(u)?u:g(u)?e(u):[]:h(v)||f(v)?b=f(u)?l(u):h(u)?u:{}:x=!1);t.push(v);p.push(b);if(x)a[c]=q(b,v,r,t,p);else if(b===b?b!==u:u===u)a[c]=b}},,function(c,b,a){function e(a,b){return void 0===a?b:f(a,b,e)}var f=a(535);c.exports=e},function(c,b,a){var e=a(1237),f=a(128);c.exports=function(a){return e(a,f(a))}},function(c,b,a){var e=a(937),f=a(1238),d=a(39);c.exports=function(a,b,c){var l=f(a);c&&d(a,b,c)&&(b=void 0);return b? e(l,b):l}},function(c,b,a){b=a(558);var e=a(1235);a=a(871)(b,e);c.exports=a},function(c,b,a){b=a(871);var e=a(535);a=a(1243);a=b(e,a);c.exports=a},function(c,b,a){c.exports=a(558)},function(c,b,a){b=a(323);a=a(598)(b);c.exports=a},function(c,b,a){b=a(554);a=a(1381)(b);c.exports=a},function(c,b,a){b=a(224);a=a(872)(b);c.exports=a},function(c,b,a){b=a(323);a=a(872)(b);c.exports=a},function(c,b,a){c.exports=a(880)},function(c,b,a){var e=a(278),f=a(265),d=a(534),g=a(156),h=a(321),k=a(225);c.exports=function(a, b,c){var s=null==a?void 0:a[b];void 0===s&&(null!=a&&!g(b,a)&&(b=k(b),a=1==b.length?a:e(a,f(b,0,-1)),s=null==a?void 0:a[h(b)]),s=void 0===s?c:s);return d(s)?s.call(a):s}},function(c,b,a){var e=a(556),f=a(128);c.exports=function(a){return e(a,f(a))}},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b){YUI.add("squarespace-dialog-password",function(a){a.namespace("Squarespace.DialogFields");var b=a.Squarespace.DialogFields.Password=a.Base.create("Password",a.Squarespace.DialogFields.Text,[],{initializer:function(){this.publish("forgot-password", {emitFacade:!0});this.get("strengthMeterVisible")&&typeof zxcvbn!==typeof Function&&a.Get.js("https://static."+Static.SQUARESPACE_CONTEXT.appDomain+"/universal/scripts-thirdparty/zxcvbn/zxcvbn-min.js",function(a){a?console.error("[Password strength] Error loading zxcvbn."):console.log("[Password strength] Loaded zxcvbn.")});this._barColor="red"},renderUI:function(){b.superclass.renderUI.call(this);var c=this.get("contentBox");this.get("strengthMeterVisible")&&(this._strengthMeter=c.plug(a.Squarespace.Plugin.ProgressBar, {show:!0,append:!0})[a.Squarespace.Plugin.ProgressBar.NS]);this._forgotNode=c.appendChild(this.getProperty("FORGOT_PASSWORD_TEMPLATE"))},bindUI:function(){b.superclass.bindUI.call(this);this._forgotNode.on("click",function(a){a.halt();this.fire("forgot-password")},this);this.get("strengthMeterVisible")&&this.after("dataChange",this._updateStrengthMeter,this)},syncUI:function(){b.superclass.syncUI.call(this);var c=this.get("boundingBox");c.toggleClass("has-title",a.Lang.isValue(this.get("strings.title"))); c.toggleClass("forgot-visible",this.get("forgotVisible")&&""===this.get("data").trim())},_updateStrengthMeter:function(){if(typeof zxcvbn===typeof Function){var a=this.get("data"),b=zxcvbn(a),b=100*((Math.log(b.crack_time)+7)/30),b=null===a||""===a?Math.max(Math.min(b,100),0):Math.max(Math.min(b,100),3);33>b?this._setBarColor("red"):33<=b&&67>b?this._setBarColor("yellow"):67<=b&&this._setBarColor("green");this._strengthMeter.set("progress",b)}},_setBarColor:function(a){var b=this._strengthMeter._meterEl.one(".bar-inner"); b.toggleClass(this._barColor,!1);b.toggleClass(a,!0);this._barColor=a}},{FORGOT_PASSWORD_TEMPLATE:'<a class="forgot">Forgot?</a>',CSS_PREFIX:"sqs-dialog-password",ATTRS:{forgotVisible:{value:!1,validator:a.Lang.isBoolean},strengthMeterVisible:{value:!1,validator:a.Lang.isBoolean,writeOnce:"initOnly"},password:{value:!0,readOnly:!0}}})},"1.0",{requires:["base","squarespace-dialog-text","squarespace-plugin-progress-bar"]})},function(c,b,a){var e=a(572),f=a(433),d=a(55);YUI.add("squarespace-domains-models-domain", function(a){a.namespace("Squarespace.Domains.Models");var b=a.Squarespace.Domains.Models.Domain=a.Base.create("Domain",a.Model,[a.Squarespace.ModelSync.REST],{root:a.Squarespace.REST_API_ROOT+"domains",serialize:function(){var c=b.superclass.toJSON.apply(this,arguments);delete c.discountExpiresOn;delete c.planLevel;c.basePrice instanceof d&&(c.basePrice=c.basePrice.toJson());return a.JSON.stringify(c)}},{ATTRS:{id:{validator:a.Squarespace.AttrValidators.isString},autoRenew:{validator:a.Squarespace.AttrValidators.isBoolean}, renewsOn:{validator:a.Squarespace.AttrValidators.isNullOrNumber},createdOn:{validator:a.Squarespace.AttrValidators.isNumber},discountExpiresOn:{setter:function(b){return b instanceof Date?b:a.Lang.isNumber(b)?new Date(b):null}},isVerified:{validator:a.Squarespace.AttrValidators.isBoolean},locked:{validator:a.Squarespace.AttrValidators.isBoolean},managedDomainExpiration:{validator:a.Squarespace.AttrValidators.isNullOrNumber},name:{validator:a.Squarespace.AttrValidators.isString},planLevel:{validator:a.Squarespace.AttrValidators.isValueIn(f)}, basePrice:{value:null,setter:function(b){a.Lang.isObject(b)&&!(b instanceof d)&&(b=d.fromJson(b));return null!==b&&!(b instanceof d)?a.Attribute.INVALID_VALUE:b}},providerId:{validator:a.Squarespace.AttrValidators.isNumber},purchasedGoogleApps:{validator:a.Squarespace.AttrValidators.isBoolean},revokable:{validator:a.Squarespace.AttrValidators.isBoolean},subscriptionId:{validator:a.Squarespace.AttrValidators.isString},subscriptionState:{validator:a.Squarespace.AttrValidators.isValueIn(e)},type:{validator:a.Squarespace.AttrValidators.isNumber}, verficationCode:{validator:a.Squarespace.AttrValidators.isNullOrString},withinPropagationWindow:{validator:a.Squarespace.AttrValidators.isBoolean},whoisPrivacy:{validator:a.Squarespace.AttrValidators.isNullOrBoolean}}})},"1.0",{requires:["base","model","squarespace-attr-validators","squarespace-model-sync-rest"]})},function(c,b,a){var e=a(293);YUI.add("squarespace-external-authentication",function(a){a.namespace("Squarespace");a.Squarespace.ExternalAuthentication=a.Base.create("externalAuthentication", a.Base,[],{initializer:function(){this.publish("completed")},openPopupWindow:function(b,c,e,k){b="/auth/ExternalAuthenticationInitiate?"+this._buildQueryParams(b,c,e,k);this.setAttrs({websites:null,website:null,memberAccount:null,socialConfig:null,messageReceived:!1});this._oauthWindow=window.open(b,"ConnectWithOAuth","location=0,status=0,scrollbars=1,width=1020,height=520");this._checkClosedOnInterval();b=window.addEventListener?"addEventListener":"attachEvent";(0,window[b])("attachEvent"==b?"onmessage": "message",a.bind(this._receiveMessage,this),!1)},_buildQueryParams:function(b,c,h,k){a.Lang.isString(b)&&(b=e[b.toUpperCase()]);var l="serviceProvider="+b;a.Lang.isValue(c)&&a.Lang.isValue(h)&&(l+="&"+c+"="+h);this.get("useLoginFlag")&&(l+="&loginFlag=true");this.get("includeWebsiteList")&&(l+="&includeWebsiteList=true");c=this.get("targetIdentifier");a.Lang.isString(c)&&(l+="&targetIdentifier="+c);c=this.get("authenticationType");a.Lang.isValue(c)&&(l+="&type="+c);(c=this._getInviteCode())&&(l+= "&"+c);this.get("startSubscription")&&(l+="&startSubscription=true");b===e.FACEBOOK&&(l+="&redirArgs="+encodeURIComponent("scopeuser_checkins,offline_access,manage_pages,publish_stream"));l+="&uuid="+this.get("uuid");k&&(l+="&"+a.QueryString.stringify(k));return l},_getInviteCode:function(){var b=document.location.search;"?"===b[0]&&(b=b.slice(1));return a.Array.find(b.split("&"),function(a){return 0===a.indexOf("invitation=")},this)},_receiveMessage:function(b){b=JSON.parse(b.data);a.Lang.isObject(b)&& this.setAttrs({websites:b.websites,website:b.website,memberAccount:b.memberAccount,socialConfig:b.socialConfig,messageReceived:!0})},_checkClosedOnInterval:function(){this._oauthWindow.closed||window.callbackFinished?(window.callbackFinished=!1,this.get("messageReceived")?this.fire("completed"):a.Data.get({url:"/auth/ExternalAuthenticationGetResult?uuid="+this.get("uuid"),success:function(a){this.setAttrs({websites:a.websites,memberAccount:a.memberAccount,website:a.website,socialConfig:a.socialConfig}); this.fire("completed")},failure:function(a){this.fire("completed")}},this)):a.later(200,this,this._checkClosedOnInterval)}},{ATTRS:{useLoginFlag:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},includeWebsiteList:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},targetIdentifier:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString},uuid:{value:null,valueFn:function(){var a=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(b){var c= (a+16*Math.random())%16|0;a=Math.floor(a/16);return("x"==b?c:c&7|8).toString(16)})},validator:a.Squarespace.AttrValidators.isNullOrString},authenticationType:{value:null},websites:{value:null},website:{value:null},memberAccount:{value:null},socialConfig:{value:null},messageReceived:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},startSubscription:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean}}})},"1.0",{requires:["base","querystring-stringify","squarespace-attr-validators", "squarespace-util"]})},function(c,b){YUI.add("squarespace-mixins-loadable",function(a){a.namespace("Squarespace.Mixins");a.Squarespace.Mixins.Loadable=a.Base.create("Loadable",a.Base,[],{initializer:function(){var b=this.get("loadable"),c=this.get("loadOnInitialize");a.Lang.isValue(b)?(this._bindLoadable(),c&&b.load()):c&&console.error("Squarespace.Mixins.Loadable: You set loadOnInitialize to true, but the loadable was not defined in the initializer.");this.after("loadableChange",this._bindLoadable, this)},destructor:function(){this._beforeLoadHandler&&this._beforeLoadHandler.detach();this._afterLoadHandler&&this._afterLoadHandler.detach();this._afterBindHandler&&this._afterBindHandler.detach()},_bindLoadable:function(){var b=this.get("loadable");this._beforeLoadHandler=a.Do.before(function(){this._set("loading",!0)},b,"load",this);this._afterLoadHandler=b.after(["load","error"],function(){this.get("destroyed")||this._set("loading",!1)},this);this._afterBindHandler=a.Do.after(function(){this.after("loadingChange", this.syncUI,this)},this,"bindUI",this)}},{ATTRS:{loadable:{value:null},loading:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,readOnly:!0},loadOnInitialize:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"}}})},"1.0",{requires:["base","event-custom","squarespace-attr-validators"]})},,,function(c,b){YUI.add("squarespace-session-storage",function(a){a.namespace("Squarespace");var b=function(){return a.Lang.isValue(window.localStorage)};a.Squarespace.SessionStorage= {saveSessionData:function(c,d,g){d={value:d};a.Lang.isDate(g)?d.expires=g.getTime():g=null;d=btoa(a.JSON.stringify(d));b()?window.localStorage.setItem(c,d):null===g?a.Cookie.set(c,d,{path:"/"}):a.Cookie.set(c,d,{path:"/",expires:g})},getSessionData:function(c){var d;d=b()?window.localStorage.getItem(c):a.Cookie.get(c);if(!a.Lang.isValue(d))return null;d=a.JSON.parse(atob(d));return a.Lang.isNumber(d.expires)&&d.expires<(new Date).getTime()?(b()&&window.localStorage.removeItem(c),null):d.value},removeSessionData:function(c){b()&& window.localStorage.removeItem(c);a.Cookie.remove(c)}}},"1.0",{requires:["base","cookie"]})},,function(c,b,a){var e=a(1),f=a(20);YUI.add("squarespace-widgets-password-recovery",function(a){var b={ctor:a.Squarespace.DialogFields.Text,config:{name:"email",submitOnEnter:!0,strings:{placeholder:e("Email Address")}}},c={ctor:a.Squarespace.DialogFields.Description,config:{name:"description",text:e("Please enter the email address that you used when creating your account.")}};a.namespace("Squarespace.Widgets"); var k=a.Squarespace.Widgets.PasswordRecovery=a.Base.create("passwordRecovery",a.Squarespace.EditingDialog,[],{initialize:function(){k.superclass.initialize.call(this);var a=this._passwordRecoveryDialogConfig();this.setParams(a);this.on("send-requested",this._onSubmit,this);this.on("cancel-click",this._onCancel,this)},_passwordRecoveryDialogConfig:function(){return{name:"password-recovery",style:"flyout",savingText:"Sending",overlay:0.5,width:370,zIndex:100001,closeOthers:!1,discardChangesConfirmation:!1, buttons:[{type:"cancel",title:e("Cancel")},{type:"saveAndClose",title:e("Send Email")}],tabs:[{title:e("Password Recovery"),fields:[c,b]}]}},_onSubmit:function(){var b=this._getEmail();this._isValidEmail(b)?this._sendPasswordReset(b).then(a.bind(this._sentSuccessfully,this),a.bind(this._sendFailed,this)):this.showErrors({email:e("You need a valid email address.")})},_getEmail:function(){return this.getData().email},_isValidEmail:function(b){return a.Lang.isString(b)&&0<b.indexOf("@")},_sentSuccessfully:function(){this.close(); var b=this._getEmail();(new a.Squarespace.Widgets.Alert({position:a.Squarespace.Widgets.Confirmation.ANCHOR.CENTER,"strings.title":e("Sent"),"strings.message":f(e("We've sent an email to {email} with further instructions on resetting your password."),{email:b}),"strings.confirm":e("Dismiss")})).on("confirm",this.destroy,this)},_sendFailed:function(b){a.Lang.isObject(b.errors)?this.showErrors(b.errors):new a.Squarespace.Widgets.Alert({"strings.title":e("An error occurred"),"strings.message":e("An error occurred while sending your email. Please try again.")})}, _onCancel:function(){this.destroy()},_sendPasswordReset:function(b){return new a.Promise(function(c,f){a.Data.post({url:"/api/auth/password-reset/email",secure:!0,json:!0,data:{email:b},success:c,failure:f})})}},{})},"1.0",{requires:["base","squarespace-dialog","squarespace-dialog-description","squarespace-dialog-text","squarespace-widgets-alert"]})},function(c,b,a){var e=a(1),f=a(576);YUI.add("squarespace-widgets-two-factor-auth",function(a){var b={name:"two-factor-auth",style:"flyout",savingText:"Checking", zIndex:2E5,width:400,height:190,closeOthers:!1,discardChangesConfirmation:!1,title:e("Enter your verification code"),disableOverlayCancel:!0,initialData:{email:{$value:"email"}},buttons:[{type:"cancel",title:e("Cancel")},{type:"saveAndClose",title:{$value:"saveButtonText"}}],fields:[{ctor:a.Squarespace.DialogFields.Description,config:{text:e('Open <a href="https://support.google.com/accounts/answer/1066447?hl=en" target="_blank">Google Authenticator</a> to view your code')}},{ctor:a.Squarespace.DialogFields.Text, config:{name:"code",submitOnEnter:!0,className:"large",strings:{placeholder:e("Verification Code")}}},{ctor:a.Squarespace.DialogFields.Description,config:{name:"sendSms",text:e('Click <a class="send-sms" href="" onclick="javascript:noop();">here</a> to send your code via SMS')}}]},c={saveButtonText:"Login",email:null};a.namespace("Squarespace.Widgets");var k=a.Squarespace.Widgets.TwoFactorAuth=a.Base.create("TwoFactorAuth",a.Squarespace.EditingDialog,[],{initialize:function(f){k.superclass.initialize.call(this); f=a.merge(c,f);f=a.Squarespace.ObjectBuilder.make(a.clone(b),{},f);this.setParams(f);this.on("send-requested",this._submit,this);this.onceAfter("ready",this._bindSendSms,this);this.publish("success",{emitFacade:!0})},_bindSendSms:function(){this.getField("sendSms").get("contentBox").one(".send-sms").on("click",this._sendSms,this)},_sendSms:function(b){b&&b.halt();var c=this.getData();a.Squarespace.Promises.create(function(b,f){a.Data.post({url:"/api/auth/two-factor/recovery-notifications/sms",secure:!0, json:!0,data:{email:c.email},success:b,failure:f})}).then(this._showSendSmsConfirm.bind(this),this._handleFailure.bind(this))},_showSendSmsConfirm:function(b){new a.Squarespace.Widgets.Alert({"strings.title":e("Code Sent"),"strings.message":e("We texted you a verification code.")})},_submit:function(b){b.halt();var c=this.getData();a.Squarespace.Promises.create(function(b,f){a.Data.post({url:"/api/auth/two-factor",secure:!0,json:!0,data:{email:c.email,code:c.code},success:b,failure:f})}).then(this._handleSuccess.bind(this), this._handleFailure.bind(this))},_handleSuccess:function(){this.fire("success")},_handleFailure:function(b){if(b.twoFactorAuthException)switch(b.exceptionCode){case f.LOGIN_REQUIRED:this.showErrors({code:e("Please log in again")});break;case f.INVALID_CODE:this.showErrors({code:e("Invalid code")});break;case f.NO_PHONE_NUMBER:new a.Squarespace.Widgets.Alert({"strings.title":e("No phone number"),"strings.message":e("We could not find a phone number for this account.")});break;default:console.warn("Unexcepted TwoFactorAuthExceptionType: "+ b.exceptionCode)}else new a.Squarespace.Widgets.Alert({"strings.title":e("An unexpected error occurred"),"strings.message":e("Please try again")})}})},"1.0",{requires:"base squarespace-dialog squarespace-dialog-description squarespace-dialog-text squarespace-object-builder squarespace-promises squarespace-widgets-alert".split(" ")})},,,,,,,,,,,,,,,,,,function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(a=a(7))&&a.__esModule?a:{"default":a},d=/https:\/\/[^.]*\.([^:]*)(:(\d{1,5}))?/;a=function(){function a(){(0, e.default)(this,a)}(0,f.default)(a,null,[{key:"isOriginValid",value:function(a){return a&&(a=a.match(d))&&2<=a.length?location.hostname.endsWith(a[1]):!1}},{key:"subscribe",value:function(b){window.addEventListener("message",function(c){var d=c.data;c=c.origin;a.isOriginValid(c)?b(d):console.error("Invalid origin on postMessage: "+c)})}}]);return a}();c.exports=a},,,,,,,,,,,,,,,,,,,,function(c,b){YUI.add("squarespace-widgets-create-account-template",function(a){var b=a.Handlebars;(function(){var a= b.template;(b.templates=b.templates||{})["widgets-create-account.html"]=a(function(a,b,c,f,e){this.compilerInfo=[4,">= 1.0.0"];c=this.merge(c,a.helpers);e=e||{};f=this.escapeExpression;a='<div class="wait-overlay ';if((c=c.unless.call(b,b.waiting,{hash:{},inverse:this.noop,fn:this.program(1,function(a,b){return"hidden"},e),data:e}))||0===c)a+=c;return a+='">\n\t<div class="loading-spinner"></div>\n</div>\n<div class="title-block">\n\t<div class="title-text">Create Account</div>\n</div>\n\n<div class="body-block">\n\t<div class="description">'+ f((c=(c=b.strings,null==c||!1===c?c:c.description),"function"===typeof c?c.apply(b):c))+'</div>\n\t<div class="name">\n\t\t<div class="display-first-name-field-wrapper" data-field-name="firstName"></div>\n\t\t<div class="display-last-name-field-wrapper" data-field-name="lastName"></div>\n\t</div>\n\t<div class="display-email-field-wrapper" data-field-name="email"></div>\n\t<div class="display-password-field-wrapper" data-field-name="password"></div>\n</div>\n\n<div class="footer" data-field-name="footer"> </div>\n\n<div class="controls-block">\n\t<div class="button-holder">\n\t\t<div class="cancel-block" data-action="cancel">Cancel</div>\n\t\t<div class="saveAndClose" data-action="submit">Create Account</div>\n\t</div>\n</div>\n'})})(); a.Handlebars.registerPartial("widgets-create-account.html".replace("/","."),b.templates["widgets-create-account.html"])},"1.0",{requires:["handlebars-base"]})},function(c,b){YUI.add("squarespace-widgets-login-template",function(a){var b=a.Handlebars;(function(){var a=b.template;(b.templates=b.templates||{})["widgets-login.html"]=a(function(a,b,c,f,e){function m(a,b,c){var d;return a=""+('\n <span data-login-method="'+t(typeof a===r?a.apply(a):a)+'" class="tab-item '+t(typeof a===r?a.apply(a): a)+" "+t((d=c.selectMode,typeof d===r?d.apply(a):d))+'"></span>\n ')}function n(a,b){return"arrow"}function s(a,b){var c,d;return c=""+('\n <a class="signup-link button button-knockout" href="/templates">'+t((d=(d=a.strings,null==d||!1===d?d:d.signupButtonTitle),typeof d===r?d.apply(a):d))+"</a>\n ")}this.compilerInfo=[4,">= 1.0.0"];c=this.merge(c,a.helpers);e=e||{};var q,r="function",t=this.escapeExpression,p=this,u=c.blockHelperMissing;a='<div class="login-wrapper">\n <div class="wait-overlay '; if((f=c.unless.call(b,b.waiting,{hash:{},inverse:p.noop,fn:p.program(1,function(a,b){return"hidden"},e),data:e}))||0===f)a+=f;a+='">\n <div class="loading-spinner"></div>\n </div>\n\n <div class="header ';q={hash:{},inverse:p.noop,fn:p.program(3,function(a,b){return"has-title"},e),data:e};(f=c.title)?f=f.call(b,q):(f=b.title,f=typeof f===r?f.apply(b):f);c.title||(f=u.call(b,f,q));if(f||0===f)a+=f;a+='">\n ';if((f=c["if"].call(b,b.title,{hash:{},inverse:p.noop,fn:p.program(5,function(a,b){var d, f;d='\n <div class="title">';(f=c.title)?f=f.call(a,{hash:{},data:b}):(f=a.title,f=typeof f===r?f.apply(a):f);if(f||0===f)d+=f;return d+"</div>\n "},e),data:e}))||0===f)a+=f;a+='\n </div>\n\n <div class="body ';(f=c.activeLoginMethod)?f=f.call(b,{hash:{},data:e}):(f=b.activeLoginMethod,f=typeof f===r?f.apply(b):f);a+=t(f)+'">\n ';if((f=c.unless.call(b,b.hideTab,{hash:{},inverse:p.noop,fn:p.program(7,function(a,b){var d,f;d='\n <div class="login-selector select-mode-';(f=c.selectMode)? f=f.call(a,{hash:{},data:b}):(f=a.selectMode,f=typeof f===r?f.apply(a):f);d+=t(f)+'">\n <div class="tabs">\n ';if((f=c.each.call(a,a.tabsEnabled,{hash:{},inverse:p.noop,fn:p.programWithDepth(8,m,b,a),data:b}))||0===f)d+=f;return d+"\n </div>\n </div>\n "},e),data:e}))||0===f)a+=f;a+='\n\n <div class="mode squarespace">\n <div class="email-field-wrapper">\n <div data-field-name="email"></div>\n\n <div class="email-address-recovery" data-action="email-address-recovery">Forgot?</div>\n </div>\n <div class="password-field-wrapper">\n <div data-field-name="password"></div>\n\n <div class="password-recovery" data-action="password-recovery">Forgot?</div>\n </div>\n\n <div class="primordial-options">\n '; if((f=c["if"].call(b,b.enableStayLoggedIn,{hash:{},inverse:p.noop,fn:p.program(10,function(a,b){return'\n <div class="stay-logged-in" data-field-name="stay-logged-in"></div>\n '},e),data:e}))||0===f)a+=f;a+="\n\n ";if((f=c["if"].call(b,b.enableGoogleLoginLink,{hash:{},inverse:p.noop,fn:p.program(12,function(a,b){return'\n <div class="login-with-google" data-action="login-with-google">Login with Google+</div>\n '},e),data:e}))||0===f)a+=f;a+="\n\n ";if((f= c.unless.call(b,b.enableGoogleLoginLink,{hash:{},inverse:p.noop,fn:p.program(14,function(a,b){var d,f,e;d='\n <div class="submit button ';if((e=c.unless.call(a,(f=a.strings,null==f||!1===f?f:f.loginButtonTitle),{hash:{},inverse:p.noop,fn:p.program(15,n,b),data:b}))||0===e)d+=e;return d+='" data-action="submit">'+t((f=(f=a.strings,null==f||!1===f?f:f.loginButtonTitle),typeof f===r?f.apply(a):f))+"</div>\n "},e),data:e}))||0===f)a+=f;a+='\n </div>\n </div>\n <div class="mode google social-login">\n <div class="social-login-button"></div>\n <div class="social-login-cancel" data-action="login-with-squarespace">Login with Squarespace</div>\n </div>\n <div class="mode facebook social-login">\n <div class="social-login-button"></div>\n <div class="social-login-cancel" data-action="login-with-squarespace">Login with Squarespace</div>\n </div>\n <div class="mode twitter social-login">\n <div class="social-login-button"></div>\n <div class="social-login-cancel" data-action="login-with-squarespace">Login with Squarespace</div>\n </div>\n <div class="mode guest">\n <div class="display-name-field-wrapper" data-field-name="displayName"></div>\n <div class="anon-email-field-wrapper" data-field-name="anonEmail"></div>\n <div class="author-url-field-wrapper" data-field-name="authorUrl"></div>\n <div class="buttons">\n <div class="submit button" data-action="submit">'+ t((f=(f=b.strings,null==f||!1===f?f:f.loginButtonTitle),typeof f===r?f.apply(b):f))+'</div>\n </div>\n </div>\n </div>\n\n <div class="footer ';(f=c.activeLoginMethod)?f=f.call(b,{hash:{},data:e}):(f=b.activeLoginMethod,f=typeof f===r?f.apply(b):f);a+=t(f)+'">\n <div class="buttons">\n ';if((f=c["if"].call(b,b.canCancel,{hash:{},inverse:p.noop,fn:p.program(17,function(a,b){return'\n <div class="cancel" data-action="cancel">Cancel</div>\n '},e),data:e}))||0===f)a+=f;a+= "\n\n ";if((f=c["if"].call(b,b.canCreateAccount,{hash:{},inverse:p.noop,fn:p.program(19,function(a,b){return'\n <div class="create-account" data-action="create-account">Create Squarespace Account</div>\n '},e),data:e}))||0===f)a+=f;a+="\n\n ";if((f=c["if"].call(b,b.enableGoogleLoginLink,{hash:{},inverse:p.noop,fn:p.program(21,function(a,b){var d,f,e;d='\n <div class="submit button ';if((e=c.unless.call(a,(f=a.strings,null==f||!1===f?f:f.loginButtonTitle),{hash:{},inverse:p.noop, fn:p.program(15,n,b),data:b}))||0===e)d+=e;d+='" data-action="submit">'+t((f=(f=a.strings,null==f||!1===f?f:f.loginButtonTitle),typeof f===r?f.apply(a):f))+"</div>\n ";if((e=c["if"].call(a,a.shouldShowSignupLink,{hash:{},inverse:p.noop,fn:p.program(22,s,b),data:b}))||0===e)d+=e;return d+"\n "},e),data:e}))||0===f)a+=f;return a+"\n </div>\n </div>\n</div>\n"})})();a.Handlebars.registerPartial("widgets-login.html".replace("/","."),b.templates["widgets-login.html"])},"1.0",{requires:["handlebars-base"]})}, function(c,b){YUI.add("squarespace-widgets-member-account-template",function(a){var b=a.Handlebars;(function(){var a=b.template;(b.templates=b.templates||{})["widgets-member-account.html"]=a(function(a,b,c,f,e){this.compilerInfo=[4,">= 1.0.0"];c=this.merge(c,a.helpers);e=e||{};var m=this.escapeExpression;a=' <div class="profile-image"></div>\n\n <div class="profile-info">\n <span class="name">';(f=c.displayName)?f=f.call(b,{hash:{},data:e}):(f=b.displayName,f="function"===typeof f?f.apply(b): f);a+=m(f)+'</span>\n <span class="email">';(f=c.email)?f=f.call(b,{hash:{},data:e}):(f=b.email,f="function"===typeof f?f.apply(b):f);return a+=m(f)+"</span>\n </div>\n"})})();a.Handlebars.registerPartial("widgets-member-account.html".replace("/","."),b.templates["widgets-member-account.html"])},"1.0",{requires:["handlebars-base"]})},function(c,b){YUI.add("squarespace-widgets-website-template",function(a){var b=a.Handlebars;(function(){var a=b.template;(b.templates=b.templates||{})["widgets-website.html"]= a(function(a,b,c,f,e){this.compilerInfo=[4,">= 1.0.0"];c=this.merge(c,a.helpers);e=e||{};f=this.escapeExpression;a='<div class="website" data-site-id="';(c=c.id)?c=c.call(b,{hash:{},data:e}):(c=b.id,c="function"===typeof c?c.apply(b):c);return a+=f(c)+'">\n\n <div class="favicon"><img src="'+f((c=b.faviconURL,"function"===typeof c?c.apply(b):c))+'" alt="'+f((c=b.siteTitle,"function"===typeof c?c.apply(b):c))+' favicon">\n </div>\n\n <div class="site-desc">\n <span class="title">'+f((c=b.siteTitle, "function"===typeof c?c.apply(b):c))+'</span>\n <span class="url">'+f((c=b.url,"function"===typeof c?c.apply(b):c))+"</span>\n </div>\n\n</div>\n"})})();a.Handlebars.registerPartial("widgets-website.html".replace("/","."),b.templates["widgets-website.html"])},"1.0",{requires:["handlebars-base"]})},function(c,b,a){var e=a(2);b=e.PropTypes;var f=a(1366),d=a(1312),g=a(1356),h=a(11);a=e.createClass({displayName:"AuthenticationFrame",propTypes:{isVisible:b.bool.isRequired,isLoading:b.bool.isRequired, shouldLoadIFrame:b.bool.isRequired,onIFrameLoaded:b.func,onMessageReceived:b.func,url:b.string.isRequired},getDefaultProps:function(){return{isVisible:!1,isIFrameLoaded:!1,isRedirecting:!1}},componentDidMount:function(){var a=this.props.onMessageReceived;a&&d.subscribe(a)},render:function(){var a,b,c=this.props,d=c.url,s=c.isVisible,q=c.shouldLoadIFrame,r=c.isLoading,c=c.onIFrameLoaded;return e.createElement("div",{className:h(f.overlay,(a={},a[f.shown]=s,a))},e.createElement(g,{isVisible:s&&r}), q&&e.createElement("iframe",{className:h((b={},b[f.show]=!r,b)),onLoad:c,src:d}))}});c.exports=a},function(c,b,a){b=a(32);var e=a(1336),f=a(1338),d=a(706);a=b({getStores:function(){return[f]},getPropsFromStores:function(){var a=f.getState();return{isLoading:a.isLoading,isVisible:a.isVisible,shouldLoadIFrame:a.shouldLoadIFrame,onIFrameLoaded:d.frameLoaded}}},e);c.exports=a},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d=a(706);a=function(){function a(){(0, e.default)(this,a);this.state={isVisible:!1,isLoading:!1,shouldLoadIFrame:!1};this.bindActions(d)}(0,f.default)(a,[{key:"onShow",value:function(){this.setState({isVisible:!0,shouldLoadIFrame:!0,isLoading:!0})}},{key:"onShowLoading",value:function(){this.setState({isLoading:!0,shouldLoadIFrame:!1})}},{key:"onFrameLoaded",value:function(){this.setState({isLoading:!1})}},{key:"onCloseFrame",value:function(){this.setState({isVisible:!1,isLoading:!1,shouldLoadIFrame:!1})}}]);return a}();c.exports=b.createStore(a, "AuthenticationFrameStore")},,,,,,,,,,,,,,,function(c,b,a){var e=a(2);b=e.PropTypes;var f=a(64),d=a(60),g=a(180),h=a(57),k=a(1354),l=a(1021);a=a(32);b=e.createClass({displayName:"EmailAddressRecoveryModal",propTypes:{isLoading:b.bool,defaultWebsiteIdentifier:b.string,emailRecoverySuccessful:b.bool,errorMessage:b.string,isVisible:b.bool},getDefaultProps:function(){return{isVisible:!1}},statics:{getStores:function(){return[k]},getPropsFromStores:function(){return k.getState()}},getInitialState:function(){return{recoveryDialogVisible:!1, confirmationVisible:!1,websiteIdentifier:this.props.defaultWebsiteIdentifier}},handleRecoveryDialogClose:function(){this.setState({recoveryDialogVisible:!1})},handleConfirmationClose:function(){this.setState({confirmationVisible:!1})},handleRecoverySubmit:function(){l.recover(this.state.websiteIdentifier)},componentDidUpdate:function(){this.props.errorMessage&&this.refs.websiteIdentifier.focus()},componentWillReceiveProps:function(a){var b=this;a.isVisible&&!this.state.recoveryDialogVisible&&this.setState({recoveryDialogVisible:!0}, function(){b.refs.websiteIdentifier.focus()});a.emailRecoverySuccessful&&(this.state.recoveryDialogVisible&&!a.isLoading)&&this.setState({confirmationVisible:!0,recoveryDialogVisible:!1})},handleKeyUp:function(a){g.isEnterKey(a)&&this.handleRecoverySubmit()},handleWebsiteIdentifierChange:function(a){this.setState({websiteIdentifier:a.target.value});l.clearErrorMessage()},renderSpinner:function(){if(this.props.isLoading)return e.createElement(h,{size:"default"})},render:function(){var a=this.state, b=a.confirmationVisible,c=a.websiteIdentifier,g=this.props.errorMessage;return e.createElement("div",null,e.createElement(d,{isOpen:a.recoveryDialogVisible,onRequestClose:this.handleRecoveryDialogClose,width:500},e.createElement(d.Header,null,"Email address recovery"),e.createElement(d.Body,null,e.createElement("p",null,"What is your domain?"),e.createElement("p",null,"For example, ",e.createElement("i",null,"www.mysite.com")," or ",e.createElement("i",null,"mysite.squarespace.com")),e.createElement(f, {type:"text",ref:"websiteIdentifier",onChange:this.handleWebsiteIdentifierChange,errorMessage:g,placeholder:"mysite.squarespace.com",value:c,onKeyUp:this.handleKeyUp}),this.renderSpinner(),e.createElement("p",null,"We'll send a recovery email to the site owner.")),e.createElement(d.Footer,null,e.createElement(d.Button,{onClick:this.handleRecoveryDialogClose},"Cancel"),e.createElement(d.Button,{onClick:this.handleRecoverySubmit},"Recover"))),e.createElement(d,{isOpen:b,onRequestClose:this.handleConfirmationClose}, e.createElement(d.Header,null,"Sent"),e.createElement(d.Body,null,"Thanks! We've sent an email to the site owner."),e.createElement(d.Footer,null,e.createElement(d.Button,{onClick:this.handleConfirmationClose},"OK"))))}});c.exports=a(b)},function(c,b,a){var e=(b=a(4))&&b.__esModule?b:{"default":b},f=(b=a(7))&&b.__esModule?b:{"default":b};b=a(9);var d=a(1021);a=function(){function a(){(0,e.default)(this,a);this.emailRecoverySuccessful=null;this.loading=!1;this.errorMessage=null;this.bindActions(d)} (0,f.default)(a,[{key:"onRecover",value:function(){this.loading=!0}},{key:"onSuccess",value:function(){this.loading=!1;this.errorMessage=null;this.emailRecoverySuccessful=!0}},{key:"onFailure",value:function(a){this.emailRecoverySuccessful=!1;this.errorMessage=a;this.loading=!1}},{key:"onClearErrorMessage",value:function(){this.errorMessage=null}}]);return a}();c.exports=b.createStore(a,"EmailAddressRecoveryStore")},function(c,b,a){var e=a(25);c.exports={recover:function(a){return e.post("/api/auth/recover-email", a)}}},function(c,b,a){var e=a(2);b=e.PropTypes;var f=a(57),d=a(1367),g=a(11);a=e.createClass({displayName:"LoadingPage",propTypes:{waitingText:b.string.isRequired,isVisible:b.bool},getDefaultProps:function(){return{waitingText:"Please wait\u2026",isVisible:!1}},render:function(){var a,b=this.props,c=b.waitingText,b=b.isVisible;return e.createElement("div",{className:g(d.overlay,(a={},a[d.shown]=b,a))},e.createElement(f,{isCentered:!0,color:"light",size:"extra-large"}),e.createElement("p",null,c))}}); c.exports=a},,,,,,,function(c,b,a){b=c.exports=a(3)();b.push([c.id,".AuthenticationFrame-overlay-2kBPr {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: -1000;\n background: #000000;\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.AuthenticationFrame-overlay-2kBPr.AuthenticationFrame-shown-3shUP {\n z-index: 10000;\n opacity: 0.9;\n}\n.AuthenticationFrame-overlay-2kBPr iframe {\n opacity: 0;\n height: 100%;\n width: 100%;\n border: 0;\n transition: opacity 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.AuthenticationFrame-overlay-2kBPr iframe.AuthenticationFrame-show-1sbL8 {\n opacity: 1.0;\n}\n", ""]);b.locals={overlay:"AuthenticationFrame-overlay-2kBPr",shown:"AuthenticationFrame-shown-3shUP",show:"AuthenticationFrame-show-1sbL8"}},function(c,b,a){b=c.exports=a(3)();b.push([c.id,"div.LoadingPage-overlay-1XmMd {\n background: transparent;\n color: #ffffff;\n padding-top: 30%;\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);\n display: none;\n width: 100%;\n height: 100%;\n}\ndiv.LoadingPage-overlay-1XmMd.LoadingPage-shown-27pio {\n display: block;\n opacity: 1.0;\n}\ndiv.LoadingPage-overlay-1XmMd p {\n text-align: center;\n font: 100 normal 16px / 22px 'Gotham SSm A', 'Gotham SSm B', 'Gotham SSm', 'Proxima Nova', 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n letter-spacing: normal;\n}\n", ""]);b.locals={overlay:"LoadingPage-overlay-1XmMd",shown:"LoadingPage-shown-27pio"}},,function(c,b,a){b=a(1363);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},function(c,b,a){b=a(1364);"string"===typeof b&&(b=[[c.id,b,""]]);a(6)(b,{});b.locals&&(c.exports=b.locals)},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b){YUI.add("squarespace-singletons-location",function(a){a.namespace("Squarespace.Singletons");var b=a.Base.create("damaskLocation",a.Base, [],{go:function(a){this.get("controller").get("router").push(a)},goBack:function(){this.get("controller").get("router").goBack()},getFrameUrl:function(){return this.get("controller").getFrameUrl()},getPanelPath:function(){return this.get("controller").getPanelPath()},setFrameUrl:function(a){this.get("controller").setFrameUrl(a)},setFrameUrlOrRefresh:function(a){this.get("controller").setFrameUrlOrRefresh(a)},requestFrameRefresh:function(){this.get("controller").requestFrameRefresh()},goToCollection:function(a, b){this.go("/pages/"+a,b)},goToContentItem:function(b,c){var e="/pages/"+b.get("collectionId")+"/"+b.get("id");this.go(e,a.merge({safeUrl:!0},c))},pointFrameToCollection:function(b,c){var e=a.Squarespace.Damask.Preview.ContentBridge.getCollectionUrl(b);c?this.setFrameUrlOrRefresh(e):this.setFrameUrl(e)},pointFrameToContentItem:function(a,b){var c=a.get("fullUrl");b?this.setFrameUrlOrRefresh(c):this.setFrameUrl(c)}},{ATTRS:{controller:{getter:function(b){return!a.Lang.isValue(b)?CONFIG_PANEL:b},validator:a.Squarespace.AttrValidators.isInstanceOf(a.Base)}}}); a.Lang.isValue(a.Squarespace.Singletons.Location)||(a.Squarespace.Singletons.Location=new b)},"1.0",{requires:["base","squarespace-attr-validators"]})},,,function(c,b){YUI.add("squarespace-dialog-multi-option",function(a){var b=a.namespace("Squarespace.DialogFields").MultiOption=a.Base.create("multiOption",a.Squarespace.DialogField2,[],{initializer:function(b){this.get("data");!this.get("data")&&!a.Lang.isUndefined(b.defaultValue)&&this.set("data",b.defaultValue);this._selectedOptionEl=null;this.publish("option-click", {broadcast:2})},renderUI:function(){b.superclass.renderUI.call(this);this._renderTitle();this._renderOptions()},bindUI:function(){this._registerEvent(this.get("contentBox").delegate("click",this._onOptionClick,".option",this));this.after("optionsChange",this._renderOptions);this.after("optionsChange",this.syncUI);this.after("stringsChange",this._renderTitle)},syncUI:function(){b.superclass.syncUI.call(this);this._setupOptionWidths();this._setHeight()},selectOption:function(a){this.get("contentBox").all(".option").each(function(b){this._optionMatchesData(b, a)&&this._selectOption(b)},this)},addOption:function(a){a=this.get("options");a.push(optionOjb);this.set("options",a)},_renderTitle:function(){var b=this.get("strings.title"),c=this.get("contentBox"),e=c.one(".title");b&&a.Lang.isNull(e)?c.append(a.Node.create('<div class="title">'+this.get("strings.title")+"</div>")):b?e.empty().setHTML(this.get("strings.title")):!b&&!a.Lang.isNull(e)&&e.remove(!0)},_renderOptions:function(){var b=this.get("contentBox"),c=this.get("options");b.all(".option").remove(); a.Array.each(c,function(c){if(c.section)b.append(a.Node.create('<div class="option-label">'+c.section+"</div>"));else{var d=a.Node.create(a.Lang.sub('<div class="option" data-value="{value}"><div class="option-content"><div class="option-title">{title}</div></div></div>',c));d.setData(c);var e=d.one(".option-content"),l=c.description;l&&e.append(a.Node.create('<div class="option-description">'+l+"</div>"));c.childNode instanceof a.Node&&e.append(c.childNode);c.icon?d.addClass("icon-"+c.icon):d.addClass("no-icon"); b.append(d);this._optionMatchesData(d)&&this._markSelected(d);c.upsellInfo&&(c.locked&&d.addClass("upgrade-locked"),this._registerEvent(d.on("click",function(){a.Squarespace.Upsell.showUpsellConfirmation(c.upsellInfo)})))}},this)},_setHeight:function(){var a=this.get("contentBox"),b=this.get("options"),c=a.one(".option");if(c){var e=parseFloat(c.getComputedStyle("height")),c=parseFloat(c.getComputedStyle("paddingTop"))+parseFloat(c.getComputedStyle("paddingBottom")),k=this.get("columns")||b.length, b=Math.ceil(b.length/k);a.setStyle("height",Math.ceil((e+c)*b))}},_selectOptions:function(){this.get("contentBox").all(".option").each(function(a){this._optionMatchesData(a)&&this._selectOption(a)},this)},_optionMatchesData:function(b,c){a.Lang.isUndefined(c)&&(c=this.get("data"));var e=b.getData("value");if(this.get("numeric"))return c===a.Number.parse(e);a.Lang.isObject(e)&&a.Lang.isObject(c)&&console.warn("Trying to compare to objects, which is a bit out of scope.");return c===e},_onOptionClick:function(b){b.halt(); b=b.target.hasClass("option")?b.target:b.target.ancestor(".option");var c=this.get("optionClickCb");b.hasClass("upgrade-locked")||this._selectOption(b);a.Lang.isFunction(c)&&c(this.get("data"));this.fire("option-click",{option:this.get("data")})},_markSelected:function(a){a!=this._selectedOptionEl&&(this._selectedOptionEl&&this._selectedOptionEl.removeClass("selected"),a.addClass("selected"),this._selectedOptionEl=a)},_selectOption:function(b){if(b!=this._selectedOptionEl){this._markSelected(b);b= b.getData("value");if(this.get("numeric")){var c=a.Number.parse(b);a.Lang.isNumber(c)&&(b=c)}this.set("data",b);this.get("submitOnSelect")&&(b=this.get("dialog"),a.Lang.isValue(b)&&b.saveAndClose())}},_setupOptionWidths:function(){var a=this.get("columns")||this.get("options").length;0<parseInt(a,10)&&this.get("boundingBox").addClass(this.getClassName("columns-"+a))}},{CSS_PREFIX:"sqs-multi-option",ATTRS:{data:{setter:function(b){return this.get("numeric")?a.Number.parse(b):b}},options:{value:null}, optionClickCb:{value:null,setter:function(b){return!a.Lang.isFunction(b)?null:b}},submitOnSelect:{value:!1},columns:{value:null},numeric:{value:!1,validator:a.Lang.isBoolean},readOnly:{value:!0}}})},"1.0",{requires:["base","datatype-number-parse","squarespace-dialog-field-2","squarespace-upsell-confirmation"]})},,,function(c,b,a){var e=a(1);YUI.add("squarespace-google-domains-consent-service",function(a){a.namespace("Squarespace");a.Squarespace.GoogleDomainsConsentService=new (a.Base.create("domainConsentService", a.Base,[],{initializer:function(){this._openWindows={};this._messageCallbacks={};this._messageEventHandler=window.addEventListener("message",a.bind(this._routeMessage,this))},destructor:function(){window.removeEventListener("message",this._messageEventHandler);this._endMonitor()},getConsent:function(b,c,e){return a.Squarespace.Promises.create(function(a,f){this._messageCallbacks[b]=function(b){b.consentGranted?a(b):f()};this._openConsentWindow(b,c,e)},this)},getConsentForNewSite:function(b,c){return a.Squarespace.Promises.create(function(a, f){this._messageCallbacks[b]=function(b){b.consentGranted?a(b):f()};this._openSignupConsentWindow(b,c)},this)},getConsentForDomain:function(b){return a.Squarespace.Promises.create(function(a,c){this._messageCallbacks[b]=function(b){b.consentGranted?a(b):c(b)};this._openListConsentWindow(b)},this)},getDomainOnlyConsent:function(b,c,e){return a.Squarespace.Promises.create(function(a,f){this._messageCallbacks[b]=function(b){b.consentGranted?a(b):f()};this._openDomainConsentOnlyWindow(b,c,e)},this)}, getConsentForList:function(){return a.Squarespace.Promises.create(function(b,c){var e=a.guid();this._messageCallbacks[e]=function(a){a.consentGranted?b(a):c()};this._openListConsentWindow(e)},this)},_routeMessage:function(b){var c=b.data.domain;if(a.Lang.isString(c)){var e=this._messageCallbacks[c];a.Lang.isFunction(e)&&(e.call(this,b.data),delete this._messageCallbacks[c])}},_registerOpenWindow:function(b,c){0>=a.Object.size(this._openWindows)&&this._beginMonitor();this._openWindows[b]=c},_unregisterOpenWindow:function(b){delete this._openWindows[b]; 0>=a.Object.size(this._openWindows)&&this._endMonitor()},_endMonitor:function(){this._monitor&&this._monitor.cancel()},_beginMonitor:function(){this._monitor=a.later(300,this,function(){var b=[];a.Object.each(this._openWindows,function(a,c){a.closed&&(this._routeMessage({data:{domain:c,consentGranted:!1}}),b.push(c))},this);a.Array.each(b,this._unregisterOpenWindow,this)},null,!0)},_openListConsentWindow:function(b){var c=a.Lang.sub("https://oauth.{appDomain}/auth/google-web-hosting/list-domains-consent-initialize?requestIdentifier={identifier}", {identifier:b,appDomain:Static.SQUARESPACE_CONTEXT.appDomain});this._openConsentPopup(c,b)},_openDomainConsentOnlyWindow:function(b,c,e){c=a.Lang.sub("https://oauth.{appDomain}/auth/google-web-hosting/domain-consent-initialize?domain={domain}&requestId={requestId}",{requestId:c,domain:b,websiteId:e,appDomain:Static.SQUARESPACE_CONTEXT.appDomain});this._openConsentPopup(c,b)},_openConsentWindow:function(b,c,e){c=a.Lang.sub("https://oauth.{appDomain}/auth/google-web-hosting/consent-initialize?domain={domain}&websiteId={websiteId}&userId={userId}", {domain:b,appDomain:Static.SQUARESPACE_CONTEXT.appDomain,websiteId:e||"",userId:c});this._openConsentPopup(c,b)},_openSignupConsentWindow:function(b,c){var e=a.Lang.sub("https://oauth.{appDomain}/auth/google-web-hosting/signup-consent-initialize?domain={domain}&userId={userId}",{domain:b,userId:c,appDomain:Static.SQUARESPACE_CONTEXT.appDomain});this._openConsentPopup(e,b)},_openConsentPopup:function(a,b){var c=window.open(a,e("Google Domains Consent"),"status=0,width=1020,height=520");this._registerOpenWindow(b, c)}}))},"1.0",{requires:["base","promise","squarespace-promises"]})},function(c,b,a){var e=a(1),f=a(20),d=a(267),g=a(610),h=a(2),k=a(33),l=a(923),m=a(339),n=a(249),s=a(454);a(567);var q=a(304),r=a(233),t=a(342);YUI.add("squarespace-google-domains-utils",function(a){a.namespace("Squarespace.GoogleDomains");var b=function(b){a.Lang.isString(b)||(b="");(new a.Squarespace.Lightbox({disableNormalClose:!0,clickAnywhereToExit:!1,content:f(e('<div class="bigtext"><div class="title">Failed to add domain</div><div class="description">{message}</div><div class="buttons"></div></div>'), {message:b}),margin:100,noHeightConstrain:!0})).show()};a.Squarespace.GoogleDomains.initialize=function(){var b=a.Squarespace.GoogleDomains.getGoogleDomainUrlParams();!a.Lang.isNull(b.userId)&&!a.Lang.isNull(b.domainName)&&a.Squarespace.SessionStorage.saveSessionData("googleDomain",b,(new Date).addDays(7))};a.Squarespace.GoogleDomains.getGoogleDomainUrlParams=function(){var b=a.QueryString.parse(window.location.search.substr(1));return{userId:b.userId||null,domainName:b.domainName||null}};a.Squarespace.GoogleDomains.getGoogleDomainSessionData= function(){return a.Squarespace.SessionStorage.getSessionData("googleDomain")};a.Squarespace.GoogleDomains.isGoogleDomainFlow=function(){var b=this.getGoogleDomainSessionData();if(a.Lang.isObject(b))return!0;b=a.Squarespace.GoogleDomains.getGoogleDomainUrlParams();return!a.Lang.isNull(b.userId)&&!a.Lang.isNull(b.domainName)?!0:!1};a.Squarespace.GoogleDomains.initiateWebsiteLink=function(b){s.loadSuccess(b);m.bootstrap({disambiguationType:r.GOOGLE_DOMAINS,redirectPath:this._getGoogleWebhostingConfirmUrl(), currentWebsiteIdentifier:q.WWW,appDomain:n.getAppDomain()});b=h.createElement(l,{});a.Squarespace.Analytics.trackInternal("engagement_site_disambiguation",{disambiguationType:"domain_linkage"});var c=a.one(".website-selector");c||(c=a.one(a.config.doc.body).appendChild('<div class="website-selector"></div>'));k.render(b,c.getDOMNode())};a.Squarespace.GoogleDomains._getGoogleWebhostingConfirmUrl=function(){var b=a.Squarespace.GoogleDomains.getGoogleDomainUrlParams();return"/auth/google-web-hosting/add-domain-confirmation?domainName="+ b.domainName+"&userId="+b.userId};a.Squarespace.GoogleDomains.showConfirmMessage=function(b,c,d){var g=a.Squarespace.GoogleDomains.getGoogleDomainUrlParams().userId,h="http://"+window.location.hostname,k=new a.Squarespace.Lightbox({disableNormalClose:!0,clickAnywhereToExit:!1,content:f(e('<div class="bigtext"><div class="title">Connect Domain: {domainName}</div><div class="description">Your site <b>{url}</b> will be available at <b>http://www.{domainName}</b>.</div><div class="buttons"><input type="button" class="login-button" name="login" value="Connect Domain"/></div></div>'), {domainName:c,url:h}),noHeightConstrain:!0});k.show();k.getContentEl().on("click",function(){k.hide();d(b,g,c)})};a.Squarespace.GoogleDomains.startConsentFlow=function(c,f,e){var h=new a.Squarespace.Spinner({color:"light",size:"large",render:a.one(".spinner-wrapper")});h.spin();a.Squarespace.Analytics.trackInternal("domain_link_google_domain_start");return a.Squarespace.GoogleDomainsConsentService.getConsent(e,f,c).then(function(c){(new a.Squarespace.Domains.Models.Domain({name:e,type:d.LINKED,providerId:g.GOOGLE, providerData:{userId:c.userId,accessToken:c.accessToken,subId:c.subId,email:c.email}})).save({},function(c){h.stop();a.Lang.isValue(c)?b(c.responseJSON.message):window.location="/config"+t.getDomainsRoot()})},function(c){a.Squarespace.Analytics.trackInternal("domain_link_domain_failure",{host:"google"});h.stop();b(c)})}},"1.0",{requires:"querystring squarespace-domains-models-domain squarespace-google-domains-consent-service squarespace-session-storage squarespace-spinner squarespace-ui-base squarespace-util".split(" ")})}, ,,,,function(c,b,a){var e=a(1),f=a(566);YUI.add("squarespace-upsell-confirmation",function(a){a.namespace("Squarespace.Upsell");a.Squarespace.Upsell.showUpsellConfirmation=function(b,c){var k;a:switch(b.destination){case f.SWITCH_PRODUCT:case f.TRIAL_SWITCH_PRODUCT:k=e("Switch Product");break a;case f.TRIAL_UPGRADE_PLAN:k="Subscribe";break a;default:k="Upgrade"}var l=b.isSoftWarning?e("Not Now"):"Cancel";k=new a.Squarespace.Widgets.Confirmation({"strings.title":b.title,"strings.message":b.message, "strings.cancel":l,"strings.confirm":k});k.on("confirm",function(){a.Squarespace.OPEN_DIALOGS&&a.Squarespace.OPEN_DIALOGS.forEach(function(a){a.close()});switch(b.destination){case f.TRIAL_UPGRADE_PLAN:a.Squarespace.Singletons.Location.go("/settings/billing/billing/upgrade");break;case f.TRIAL_SWITCH_PRODUCT:a.Squarespace.Singletons.Location.go("/settings/billing/switch-products");break;case f.SWITCH_PRODUCT:a.Squarespace.Singletons.Location.go("/settings/billing/switch-products");break;default:a.Squarespace.Singletons.Location.go("/settings/billing/billing/website/change-plan")}}); if(c)k.on("cancel",c)}},"1.0",{requires:["squarespace-dialog","squarespace-singletons-location","squarespace-widgets-confirmation"]})},function(c,b,a){var e=a(1),f=a(20),d=a(924);YUI.add("squarespace-widgets-create-account",function(a){var b={firstName:{ctor:a.Squarespace.DialogFields.Text,config:{name:"firstName",submitOnEnter:!0,className:"large",strings:{placeholder:e("First Name")}}},lastName:{ctor:a.Squarespace.DialogFields.Text,config:{name:"lastName",submitOnEnter:!0,className:"large",strings:{placeholder:e("Last Name")}}}, email:{ctor:a.Squarespace.DialogFields.Text,config:{name:"email",submitOnEnter:!0,className:"large",strings:{placeholder:e("Email Address")}}},password:{ctor:a.Squarespace.DialogFields.Password,name:"password",config:{required:!0,name:"password",className:"large","strings.placeholder":e("Password"),submitOnEnter:!0,strengthMeterVisible:!0}},footer:{ctor:a.Squarespace.DialogFields.Description,config:{className:"tos-footer",name:"footer",text:f(e('By creating an account, you agree to the <a target="new" href="{sub1}">Terms of Service</a> and <a target="new" href="{sub2}">Privacy Policy</a>.'), {sub1:d.SERVICE,sub2:d.PRIVACY})}}};a.namespace("Squarespace.Widgets");var c=a.Squarespace.Widgets.CreateAccount=a.Base.create("create-account",a.Squarespace.SSWidget,[],{delegatedEvents:{'[data-action="submit"]':{click:"_onSubmit"},'[data-action="cancel"]':{click:"_onCancel"}},initializer:function(a){this._initializeFields();this.publish("cancel",{emitFacade:!1})},_initializeFields:function(){var c=[];a.Object.each(b,function(b,d){b.config.errorFlyoutRenderTarget=this.get("boundingBox");var f=new b.ctor(a.merge(b.config)); c.push(f)},this);a.Squarespace.FormUtils.setData(c,this.getAttrs(["email","firstName","lastName"]));this._fields=c},renderUI:function(){c.superclass.renderUI.call(this);var b=this.get("contentBox");a.Squarespace.FormUtils.template(b,this._fields);(new a.Squarespace.Spinner({color:"dark",size:"large",render:b.one(".loading-spinner")})).spin();this._focusInput()},bindUI:function(){c.superclass.bindUI.call(this);this.after("waitingChange",this.syncUI,this);a.Array.each(this._fields,function(a){if("text"=== a.getType())a.on("submit",this._onSubmit,this)},this)},syncUI:function(){c.superclass.syncUI.call(this);this.get("contentBox").one(".wait-overlay").toggleClass("hidden",!this.get("waiting"))},getEmail:function(){return a.Squarespace.FormUtils.getData(this._fields).email},setEmail:function(a){this._fields.find(function(a){return"email"===a.get("name")}).setAttrs({data:a})},_focusInput:function(){a.Array.find(this._fields,function(a){return"firstName"===a.get("name")}).focus()},_onCancel:function(a){this.fire("cancel")}, _onSubmit:function(){this.set("waiting",!0);var b=a.Squarespace.FormUtils.getData(this._fields);a.Data.post({data:b,secure:!0,url:"/api/auth/CreateSquarespaceAccount",success:function(c){this.set("password",b.password);this.set("memberAccount",new a.Squarespace.Models.MemberAccount(c.memberAccount))},failure:function(b){this.set("waiting",!1);a.Squarespace.FormUtils.showErrors(this._fields,b.errors)}},this)}},{CSS_PREFIX:"sqs-widgets-create-account",HANDLEBARS_TEMPLATE:"widgets-create-account.html", ATTRS:{memberAccount:{value:null,validator:a.Squarespace.AttrValidators.isNullOrInstanceOf(a.Squarespace.Models.MemberAccount)},password:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString},email:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},firstName:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},lastName:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},waiting:{value:!1, validator:a.Squarespace.AttrValidators.isBoolean},strings:{value:{description:e("Below you can sign up for a Squarespace account. Squarespace accounts let you keep a profile for editing and commenting on Squarespace websites.")}}}})},"1.0",{requires:"base squarespace-attr-validators squarespace-dialog-password squarespace-dialog-text squarespace-form-utils squarespace-models-member-account squarespace-spinner squarespace-ss-widget squarespace-widgets-create-account-template".split(" ")})},,function(c, b,a){var e=a(1),f=a(20),d=a(293),g=a(2),h=a(33),k=a(1353),l=a(1057);YUI.add("squarespace-widgets-login",function(a){var b={};b[d.FACEBOOK]="Facebook";b[d.TWITTER]="Twitter";b[d.GOOGLEAUTH2]="Google";var c={email:{ctor:a.Squarespace.DialogFields.Email,config:{name:"email",submitOnEnter:!0,className:"large",strings:{placeholder:e("Email Address")}}},password:{ctor:a.Squarespace.DialogFields.Text,config:{name:"password",submitOnEnter:!0,className:"large",strings:{placeholder:e("Password")},password:!0}}, "stay-logged-in":{ctor:a.Squarespace.DialogFields.Check,config:{name:"stay-logged-in","strings.title":e("Stay Logged In"),data:!0}},displayName:{ctor:a.Squarespace.DialogFields.Text,config:{name:"displayName",required:!0,submitOnEnter:!0,className:"large",strings:{placeholder:e("Your Name")}}},anonEmail:{ctor:a.Squarespace.DialogFields.Email,config:{name:"anonEmail",required:!1,submitOnEnter:!0,mailcheck:!0,className:"large",strings:{placeholder:e("Email (Optional)")}}},authorUrl:{ctor:a.Squarespace.DialogFields.Text, config:{name:"authorUrl",required:!1,submitOnEnter:!0,className:"large",strings:{placeholder:e("Website URL (Optional)")}}}};a.namespace("Squarespace.Widgets");var q=a.Squarespace.Widgets.Login=a.Base.create("login",a.Squarespace.SSWidget,[],{delegatedEvents:{'[data-action="submit"]':{click:"_onSubmit"},'[data-action="cancel"]':{click:"_onCancel"},".tabs:not(.single-tab) .tab-item":{click:"_onTabClick"},".social-login-button":{click:"_onSubmit"},".login-with-google":{click:"_activateGoogleLogin"}, '[data-action="login-with-squarespace"]':{click:"_activateSquarespaceLogin"},".password-recovery":{click:"_onPasswordRecoveryClick"},".email-address-recovery":{click:"_onEmailAddressRecoveryClick"},".create-account":{click:"_onCreateAccountClick"}},initializer:function(b){b&&"undefined"!==typeof b.canSignup&&this.set("shouldShowSignupLink",b.canSignup);this._initializeFields();this.externalAuth=new a.Squarespace.ExternalAuthentication({includeWebsiteList:!0});this.publish("loginSuccess",{emitFacade:!0}); this.publish("cancel",{emitFacade:!0})},_initializeFields:function(){var b=[];a.Object.each(c,function(c,d){c.config.errorFlyoutRenderTarget=this.get("boundingBox");var f=new c.ctor(a.merge(c.config));b.push(f)},this);a.Squarespace.FormUtils.setData(b,{email:this.get("email")});var d=a.Array.find(b,function(a){return"email"===a.get("name")});d&&d.setAttrs({disabled:this.get("disableEmailChange"),data:this.get("email"),mailcheck:!1});this.get("enableStayLoggedIn")||(d=a.Array.find(b,function(a){return"stay-logged-in"=== a.get("name")}),b.remove(d));this._fields=b},renderUI:function(){q.superclass.renderUI.call(this);var b=this.get("contentBox");a.Squarespace.FormUtils.template(b,this._fields);(new a.Squarespace.Spinner({color:"light",size:"large",render:b.one(".loading-spinner")})).spin();this._focusInput()},bindUI:function(){q.superclass.bindUI.call(this);this.after("waitingChange",this.syncUI,this);this.after("activeLoginMethodChange",this._switchTab,this);a.Array.each(this._fields,function(a){if("text"===a.getType())a.on("submit", this._onSubmit,this)},this);this.on("waitingChange",function(b){a.Array.each(this._fields,function(a){a.set("readOnly",b.newVal)})},this)},syncUI:function(){q.superclass.syncUI.call(this);var a=this.get("contentBox");this.get("contentBox").one(".wait-overlay").toggleClass("hidden",!this.get("waiting"));a.toggleClass("waiting",this.get("waiting"));if(a=a.one(".tabs")){a.toggleClass("single-tabs",1===this.get("tabsEnabled"));a.all(".tab-item.active").removeClass("active");var b=this.get("activeLoginMethod"); (a=a.one('.tab-item[data-login-method="'+b+'"]'))&&a.addClass("active")}},getEmail:function(){return a.Squarespace.FormUtils.getData(this._fields).email},setEmail:function(a){this._fields.filter(function(a){return"email"===a.get("name")})[0].setAttrs({data:a})},_focusInput:function(){var b="email";this.get("disableEmailChange")&&(b="password");a.Array.find(this._fields,function(a){return a.get("name")===b}).focus()},_activateSquarespaceLogin:function(){this.set("activeLoginMethod","squarespace")}, _activateGoogleLogin:function(){this.set("activeLoginMethod","google")},_onEmailAddressRecoveryClick:function(){a.Squarespace.FormUtils.hideErrors(this._fields);this.emailAddressRecoveryModal||(this.emailAddressRecoveryModal=h.render(g.createElement(k,{defaultWebsiteIdentifier:this.get("websiteUrl")}),this.get("mountNode")));this.emailAddressRecoveryModal=h.render(g.createElement(k,{defaultWebsiteIdentifier:this.get("websiteUrl"),isVisible:!0}),this.get("mountNode"))},_onPasswordRecoveryClick:function(b){a.Squarespace.FormUtils.hideErrors(this._fields); this.hide();b=a.Squarespace.FormUtils.getData(this._fields);var c=new a.Squarespace.Widgets.PasswordRecovery;c.setInitialData({email:b.email});c.show();c.on("destroy",this.show,this)},_onCancel:function(a){this.fire("cancel");this.destroy()},_onCreateAccountClick:function(a){this.fire("create-account")},_getHBTemplateContext:function(){var a=q.superclass._getHBTemplateContext.call(this);a.selectMode="thin";1==a.tabsEnabled.length?a.selectMode="single":3>a.tabsEnabled.length&&(a.selectMode="wide"); 0===a.tabsEnabled.length&&(a.hideTab=!0);return a},_onTabClick:function(a){a=a.target.ancestor(".tab-item",!0).getAttribute("data-login-method");this.set("activeLoginMethod",a)},_switchTab:function(b){var c=this.get("contentBox").all(".body,.footer");c.removeClass(b.prevVal);c.addClass(b.newVal);this.syncUI();a.Squarespace.FormUtils.hideErrors(this._fields)},_onSubmit:function(){this.set("waiting",!0);var b=this.get("activeLoginMethod");a.Squarespace.FormUtils.hideErrors(this._fields);switch(b){case "squarespace":b= this._loginSquarespace();break;case "guest":b=this._loginGuest();break;case "google":b=this._loginOauth(d.GOOGLEAUTH2);break;case "facebook":b=this._loginOauth(d.FACEBOOK);break;case "twitter":b=this._loginOauth(d.TWITTER);break;default:console.error("unknown method: "+b);return}b.then(a.bind(this._handleLoginSuccess,this),a.bind(this._handleLoginFailure,this))},_loginSquarespace:function(){var b=a.Squarespace.FormUtils.getData(this._fields),c=b.email,d=b.password,f=b["stay-logged-in"],e=""+this.get("returnWebsiteList"), g=this.get("targetIdentifier");return new a.Squarespace.Promises.create(function(b,h){a.Data.post({url:"/api/auth/Login",secure:!0,data:{email:c,password:d,includeWebsiteList:e,remember:f,targetIdentifier:g},success:function(a){b({type:"v6",websites:a.websites,account:a.account,website:a.targetWebsite})},failure:h},this)},this)},_loginGuest:function(){var b=a.Squarespace.FormUtils.getData(this._fields),c=b.displayName,d=b.anonEmail,f=b.authorUrl;return new a.Promise(function(b,g){(!a.Lang.isString(c)|| 1>c.length)&&g({errors:{displayName:e("Need to specify display name")}});b({type:"guest",displayName:c,email:d,authorUrl:f})})},_loginOauth:function(c){var d=this.get("returnWebsiteList"),g=this.get("targetIdentifier");return new a.Promise(function(h,k){var l=new a.Squarespace.ExternalAuthentication({includeWebsiteList:d,useLoginFlag:!0,targetIdentifier:g});l.on("completed",function(d){d=l.get("websites");var g=l.get("memberAccount"),p=l.get("website");a.Lang.isObject(g)?h({websites:d,account:g,website:p}): k({type:"oauth",error:f(e("Authentication failed with {sub1}, please try again."),{sub1:b[c]})})},this);l.openPopupWindow(c)})},_handleLoginSuccess:function(a){this.set("waiting",!1);this.fire("loginSuccess",a)},_handleLoginFailure:function(b){this.set("waiting",!1);b.twoFactorAuthException?this._handleTwoFactorAuthRequired():a.Lang.isObject(b.errors)?a.Squarespace.FormUtils.showErrors(this._fields,b.errors):a.Lang.isString(b.error)&&new a.Squarespace.Widgets.Alert({position:a.Squarespace.Widgets.Confirmation.ANCHOR.CENTER, "strings.title":e("Login Failed"),"strings.message":b.error})},_handleTwoFactorAuthRequired:function(){var b=this._getField(this._fields,"email").get("data");this.hide();b=new a.Squarespace.Widgets.TwoFactorAuth({email:b});b.show();b.on("close",function(a){this.show();a=this._getField(this._fields,"password");a.set("data","");a.focus()},this);b.on("success",function(a){this.show();this._onSubmit()},this)},_getField:function(b,c){return a.Array.find(b,function(a){return a.get("name")===c})}},{CSS_PREFIX:"sqs-widgets-login", HANDLEBARS_TEMPLATE:"widgets-login.html",ATTRS:{activeLoginMethod:{value:"squarespace",validator:a.Squarespace.AttrValidators.isValueIn(l)},enableStayLoggedIn:{value:!0,writeOnce:"initOnly"},tabsEnabled:{value:["squarespace"],validator:a.Squarespace.AttrValidators.isArray,writeOnce:"initOnly"},enableGoogleLoginLink:{value:!1,writeOnce:"initOnly"},returnWebsiteList:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},targetIdentifier:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString, writeOnce:"initOnly"},canCancel:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},email:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},firstName:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},lastName:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},disableEmailChange:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},canCreateAccount:{value:!1, validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},useLoginFlag:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},title:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},waiting:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},shouldShowSignupLink:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},strings:{value:{loginButtonTitle:e("Login"),signupButtonTitle:e("Sign up")}},mountNode:{valueFn:function(){return document.createElement("div")}}, websiteUrl:{value:"",writeOnce:"initOnly"}}})},"1.0",{requires:"base squarespace-abtest squarespace-attr-validators squarespace-dialog-check squarespace-dialog-text squarespace-external-authentication squarespace-form-utils squarespace-promises squarespace-spinner squarespace-ss-widget squarespace-widgets-alert squarespace-widgets-create-account squarespace-widgets-login-template squarespace-widgets-password-recovery squarespace-widgets-two-factor-auth".split(" ")})},function(c,b){YUI.add("squarespace-widgets-member-account", function(a){a.namespace("Squarespace.Widgets");var b=a.Squarespace.Widgets.MemberAccount=a.Base.create("MemberAccount",a.Squarespace.Widgets.Model,[],{renderUI:function(){b.superclass.renderUI.call(this)},syncUI:function(){b.superclass.syncUI.apply(this,arguments);var c=this.get("contentBox"),d=this.get("model"),c=c.one(".profile-image");a.Lang.isString(d.get("avatarId"))?c.setStyle("backgroundImage","url("+d.get("avatarAssetUrl")+")"):c.setStyle("backgroundImage",null)},_getHBTemplateContext:function(){return this.get("model").toJSON()}}, {CSS_PREFIX:"sqs-member-account",HANDLEBARS_TEMPLATE:"widgets-member-account.html",ATTRS:{model:{validator:a.Squarespace.AttrValidators.isInstanceOf(a.Squarespace.Models.MemberAccount)}}})},"1.0",{requires:"base squarespace-attr-validators squarespace-models-member-account squarespace-util squarespace-widgets-member-account-template squarespace-widgets-model".split(" ")})},function(c,b,a){var e=a(1),f=a(20);YUI.add("squarespace-widgets-model-list",function(a){a.namespace("Squarespace.Widgets");var b= a.Squarespace.Widgets.ModelList=a.Base.create("ModelList",a.Squarespace.Widgets.SSWidget,[a.WidgetParent,a.Squarespace.Mixins.Loadable],{destructor:function(){this._loadingTimer&&this._loadingTimer.cancel()},bindUI:function(){b.superclass.bindUI.call(this);this._bindModels();this.after("modelsChange",function(){this._bindModels();this.syncUI()},this)},syncUI:function(){b.superclass.syncUI.call(this);this.get("loading")?this._renderLoadingState():this._renderLoadedState()},_bindModels:function(){var a= this.get("models");this._registerEvent([a.after("add",function(b){1===a.size()&&this._empty();this._addWidgetForModel(b.model)},this),a.after("remove",function(b){this._removeWidgetForModel(b.model);a.isEmpty()&&this._renderEmptyState()},this),a.after("reset",this._renderLoadedState,this)])},_renderLoadingState:function(){this._loadingTimer&&this._loadingTimer.cancel();this._loadingTimer=a.later(500,this,function(){this._empty();new a.Squarespace.Spinner({render:this.get("contentBox"),size:44,color:"dark"})})}, _renderLoadedState:function(){this._loadingTimer&&this._loadingTimer.cancel();this._empty();var a=this.get("models");a.isEmpty()?this._renderEmptyState():a.each(this._addWidgetForModel,this)},_renderEmptyState:function(){var b=this.get("emptyStateIconSrc"),c=this.get("strings.modelName")+"s",f=a.Node.create('<div class="no-models"></div>');a.Lang.isValue(b)&&""!==b&&f.append('<img class="icon large" src="'+b+'" />');f.append('<div class="no-models-text">'+this.getEmptyStateMessage(c)+"</div>");this.get("contentBox").append(f)}, getEmptyStateMessage:function(a){return f(e("There are no {modelText}."),{modelText:a})},_empty:function(){this.removeAll().each(function(a){a.destroy()});this._childrenContainer.empty()},_addWidgetForModel:function(a){var b=this.get("models").indexOf(a);this.add({model:a},b)},_removeWidgetForModel:function(a){var b;this.some(function(c){if(c.get("model")===a)return b=c,!0})&&b.destroy()}},{CSS_PREFIX:"sqs-model-list",ATTRS:{models:{valueFn:function(){return new a.Squarespace.Models.ModelList},validator:a.Squarespace.AttrValidators.isInstanceOf(a.Squarespace.Models.ModelList)}, emptyStateIconSrc:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},loadable:{getter:function(){return this.get("models")},readOnly:!0},strings:{value:{modelName:"model"},validator:function(b){return!a.Lang.isObject(b)?(console.error('ModelList: Invalid "strings" attribute. Must be an object.'),!1):!a.Object.hasKey(b,"modelName")?(console.error('ModelList: Invalid "strings" attribute. Must have key "modelName".'),!1):!0},writeOnce:"initOnly"},defaultChildType:{value:a.Squarespace.Widgets.Model, writeOnce:"initOnly"}}})},"1.0",{requires:"base event-custom squarespace-attr-validators squarespace-mixins-loadable squarespace-models-model-list squarespace-spinner squarespace-ss-widget squarespace-widgets-model widget-parent".split(" ")})},function(c,b){YUI.add("squarespace-widgets-model",function(a){a.namespace("Squarespace.Widgets");var b=a.Squarespace.Widgets.Model=a.Base.create("Model",a.Squarespace.Widgets.SSWidget,[a.WidgetChild],{bindUI:function(){b.superclass.bindUI.call(this);this._registerEvent(this.get("model").after("change", this.syncUI,this))},_getHBTemplateContext:function(){var a=b.superclass._getHBTemplateContext.call(this);a.model=a.model.toJSON();return a}},{CSS_PREFIX:"sqs-model",ATTRS:{model:{valueFn:function(){return new a.Model},validator:a.Squarespace.AttrValidators.isInstanceOf(a.Model),writeOnce:"initOnly"}}})},"1.0",{requires:["base","model","squarespace-attr-validators","squarespace-ss-widget","widget-child"]})},function(c,b){YUI.add("squarespace-widgets-website-list",function(a){a.namespace("Squarespace.Widgets"); var b=a.Squarespace.Widgets.WebsiteList=a.Base.create("WebsiteList",a.Squarespace.Widgets.ModelList,[a.WidgetChild],{syncUI:function(){b.superclass.syncUI.call(this);var c=this.get("strings.title");a.Lang.isString(c)&&this.get("contentBox").insert(a.Node.create('<div class="list-title">'+c+"</div>"),0)},bindUI:function(){this.after("selectionChange",function(b){b=b.newVal;a.Lang.isNull(b)?this.set("selectedWebsite",null):this.set("selectedWebsite",b.get("model"))},this)}},{CSS_PREFIX:"sqs-website-list", ATTRS:{selectedWebsite:{value:null},defaultChildType:{value:a.Squarespace.Widgets.Website}}})},"1.0",{requires:["base","squarespace-widgets-model-list","squarespace-widgets-website","widget-child"]})},function(c,b,a){var e=a(1),f=a(125);YUI.add("squarespace-widgets-website-selector",function(a){a.namespace("Squarespace.Widgets");var b=a.Squarespace.Widgets.WebsiteSelector=a.Base.create("WebsiteSelector",a.Squarespace.Widgets.DialogField2,[],{initializer:function(){},renderUI:function(){b.superclass.renderUI.call(this); var c=this.get("title"),f=this.get("websites");f.isEmpty()&&(c=this.get("strings.noWebsitesError"));var e=this.get("contentBox");a.Lang.isString(c)&&e.append(a.Node.create('<div class="select-title">'+c+"</div>"));c=a.Node.create('<div class="member-account"></div><div class="websites-wrapper"><div class="websites"></div></div>');e.append(c);(new a.Squarespace.Widgets.MemberAccount({model:this.get("memberAccount"),boundingBox:e.one(".member-account")})).render();var f=this._segmentWebsites(f),m=e.one(".websites"); a.Array.each(f,function(b){if(0<b.websites.size()){var c=a.Node.create('<div class="website-sublist"></div>');m.append(c);b=new a.Squarespace.Widgets.WebsiteList({models:b.websites,boundingBox:c,"strings.title":b.name});b.render(m);this.add(b)}},this);this._set("errorFlyoutAnchor",m)},bindUI:function(){b.superclass.bindUI.call(this);this.on("WebsiteList:selectedWebsiteChange",function(b){a.Lang.isValue(b.newVal)&&this.set("selectedWebsite",b.newVal)},this)},_segmentWebsites:function(b){var c=new a.Squarespace.Models.ModelList, e=new a.Squarespace.Models.ModelList,g=new a.Squarespace.Models.ModelList,n=new a.Squarespace.Models.ModelList;b.each(function(b){var h=b.get("siteStatus");switch(a.Lang.isNumber(h)?h:a.Object.getValue(h,["value"])){case f.PASTDUE:case f.COMPED:case f.PAID:case f.V5_LINKED:c.add(b);break;case f.EXPIRED:e.add(b);break;case f.TRIAL:g.add(b);break;case f.INTERNAL:n.add(b)}b.get("faviconURL")||b.set("faviconURL",b.get("authenticUrl")+"/favicon.ico")});return[{name:"Internal",websites:n},{name:"Active", websites:c},{name:"Trial",websites:g},{name:"Expired",websites:e}]},isEmpty:function(){return!this.get("selectedWebsite")}},{CSS_PREFIX:"sqs-website-selector",ATTRS:{strings:{value:{noWebsitesError:e("You do not have any existing websites, is this the right account?")}},title:{validator:a.Squarespace.AttrValidators.isString,writeOnce:"initOnly"},memberAccount:{validator:a.Squarespace.AttrValidators.isInstanceOf(a.Squarespace.Models.MemberAccount),writeOnce:"initOnly"},websites:{validator:a.Squarespace.AttrValidators.isInstanceOf(a.Squarespace.Models.ModelList), writeOnce:"initOnly"},selectedWebsite:{value:null,validator:a.Squarespace.AttrValidators.isNullOrInstanceOf(a.Model)},data:{getter:function(){return this.get("selectedWebsite")}},required:{value:!1,validator:a.Lang.isBoolean}}})},"1.0",{requires:"base model squarespace-attr-validators squarespace-dialog-field-2 squarespace-models-member-account squarespace-models-model-list squarespace-widgets-member-account squarespace-widgets-model-list squarespace-widgets-website-list widget-parent".split(" ")})}, function(c,b){YUI.add("squarespace-widgets-website",function(a){a.namespace("Squarespace.Widgets");var b=a.Squarespace.Widgets.Website=a.Base.create("Website",a.Squarespace.Widgets.Model,[],{renderUI:function(){b.superclass.renderUI.call(this)},bindUI:function(){b.superclass.bindUI.call(this);this.get("boundingBox").on("click",function(){this.set("selected",1)},this)},_getHBTemplateContext:function(){var b=this.get("model").toJSON();a.Lang.isValue(b.authenticUrl)&&!a.Lang.isValue(b.url)&&(b.url=b.authenticUrl); return b}},{CSS_PREFIX:"sqs-website",HANDLEBARS_TEMPLATE:"widgets-website.html"})},"1.0",{requires:["base","squarespace-util","squarespace-widgets-model","squarespace-widgets-website-template"]})},,,,,function(c,b){YUI.add("datatype-number-parse",function(a,b){var c=a.Escape.regex;a.mix(a.namespace("Number"),{_buildParser:a.cached(function(a,b,e,k){var l=[],m;a&&l.push("^\\s*"+c(a)+"\\s*");b&&l.push("\\s*"+c(b)+"\\s*$");e&&l.push(c(e)+"(?=\\d)");m=RegExp("(?:"+l.join("|")+")","g");"."===k&&(k=null); return function(a){a=a.replace(m,"");return k?a.replace(k,"."):a}}),parse:function(b,c){var e;c&&"string"===typeof b&&(e=this._buildParser(c.prefix,c.suffix,c.thousandsSeparator,c.decimalSeparator),b=e(b));"string"===typeof b&&""!==a.Lang.trim(b)&&(b=+b);if("number"!==typeof b||!isFinite(b))b=null;return b}});a.namespace("Parsers").number=a.Number.parse;a.namespace("DataType");a.DataType.Number=a.Number},"3.17.2",{requires:["escape"]})},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,function(c,b,a){function e(a){return a.replace(/^\s+|\s+$/g,"")}function f(a,b){return 0==a.indexOf(b)}var d=a(1753);c.exports=function(a,b){function c(){var a="";if(u)for(var b=0;b<u.length-1;b++)a+=" ";return a+=m(u)}function l(a){var b={},c;for(c in a){var d=a[c];b[d.name]=d}return b}function m(a){return a&&0<a.length?a.slice(-1)[0]:""}function n(a){if(!a)return"";for(var b=a.length-1;0<=b;b--)if(""!=a[b])return a[b];return""}function s(a){var b=!1;if(a==n(p)){for(;m(p)!=a;)p.pop(); p.pop();b=!0}return b}function q(a){for(var b=[];0<p.length&&m(p)!=a;){var c=p.pop();b.unshift(c)}return b.join("")}function r(a){var b=p.pop();b&&(a?(p.push(b),"\n"!=b.match("\n$")&&p.push("\n\n")):(/\s*\n\n\s*$/.test(b)?(b=b.replace(/\s*\n\n\s*$/,"\n\n"),a=""):/\s*\n\s*$/.test(b)?(b=b.replace(/\s*\n\s*$/,"\n"),a="\n"):(/\s+$/.test(b),a="\n\n"),p.push(b),p.push(a)))}function t(){0<p.length?"\n"!=m(p).match("\n$")&&p.push("\n"):p.push("\n")}b=b||{};var p=[],u=[],v=[],x=[],w=[],y=[],B=[],A=b.inlineStyle|| !1,z=b.parser,C={hr:"- - -\n\n",br:" \n",title:"# ",h1:"# ",h2:"## ",h3:"### ",h4:"#### ",h5:"##### ",h6:"###### ",b:"**",strong:"**",i:"_",em:"_",dfn:"_","var":"_",cite:"_",span:" ",ul:"* ",ol:"1. ",dl:"- ",blockquote:"> ",code:"`"};!z&&"undefined"!==typeof d&&(z=d);z(a,{preserve:function(a,b){var c="\n"+a.outerHTML.replace(RegExp(" "+b+'="true"',"g"),"")+"\n";p.push(c)},start:function(a,b,d){a=a.toLowerCase();if(!d||!("br"!=a&&"hr"!=a&&"img"!=a))switch(a){case "br":p.push(C[a]);break;case "hr":r(); p.push(C[a]);break;case "title":case "h1":case "h2":case "h3":case "h4":case "h5":case "h6":r();p.push(C[a]);break;case "b":case "strong":case "i":case "em":case "dfn":case "var":case "cite":p.push(C[a]);break;case "code":if(0<w.length||0<y.length)break;p.push(C[a]);y.push(!0);break;case "span":if(0<w.length||0<y.length)break;else/\s+$/.test(m(p))||p.push(C[a]);break;case "p":case "div":case "table":case "tbody":case "tr":case "td":r();break;case "ul":case "ol":case "dl":u.push(C[a]);1<u.length?t(): r();break;case "li":case "dt":var g=c();p.push(g);break;case "a":a=l(b);v.push(a);p.push("[");break;case "img":a=l(b);var h,s;a.src?s=a.src.value:s="";if(!s)break;a.alt?g=e(a.alt.value):g="";a.title?h=e(a.title.value):h="";!A&&!f(n(p),"[")?(a=B.indexOf(s),-1==a&&(B.push(s),a=B.length-1),r(),p.push("!["),""!=g?p.push(g):null!=h&&p.push(h),p.push("]["+a+"]"),r()):(f(n(p),"[")||r(),p.push("!["+g+"]("+s+(h?' "'+h+'"':"")+")"),f(n(p),"[")||r(!0));break;case "blockquote":r();x.push(C[a]);break;case "pre":r(); w.push(!0);p.push(" ");break;case "table":p.push("<table>");break;case "thead":p.push("<thead>");break;case "tbody":p.push("<tbody>");break;case "tr":p.push("<tr>");break;case "td":p.push("<td>")}},chars:function(a){if(0===y.length)if(0<w.length)a=a.replace(/\n/g,"\n ");else if(""!=e(a)){a=a.replace(/\s+/g," ");var b=n(p);/\s+$/.test(b)&&(a=a.replace(/^\s+/g,""))}else{p.push("");return}0<x.length&&p.push(x.join(""));p.push(a)},end:function(a){a=a.toLowerCase();switch(a){case "title":case "h1":case "h2":case "h3":case "h4":case "h5":case "h6":s(C[a])|| r(!0);break;case "p":case "div":case "table":case "tbody":case "tr":case "td":for(;0<p.length&&""==e(m(p));)p.pop();r(!0);break;case "b":case "strong":case "i":case "em":case "dfn":case "var":case "cite":s(C[a])||(p.push(e(q(C[a]))),p.push(C[a]));break;case "a":var b=q("["),b=b.replace(/\s+/g," "),b=e(b);if(""==b){p.pop();break}a=v.pop();var d;a.href&&""!=a.href.value?d=a.href.value:d="";if(""==d){p.pop();p.push(b);break}p.push(b);!A&&!f(m(p),"!")?(b=B.indexOf(d),-1==b&&(B.push(d),b=B.length-1),p.push("]["+ b+"]")):(f(m(p),"!")&&(b=p.pop(),b=p.pop()+b,r(),p.push(b)),b=a.title,p.push("]("+d+(b?' "'+e(b.value).replace(/\s+/g," ")+'"':"")+")"),f(m(p),"!")&&r(!0));break;case "ul":case "ol":case "dl":t();u.pop();break;case "li":case "dt":d=c();s(d)||(b=e(q(d)),f(b,"[![")?(p.pop(),r(),p.push(b),r(!0)):(p.push(b),t()));break;case "blockquote":x.pop();break;case "pre":r(!0);w.pop();break;case "code":y.pop();case "span":if(0<w.length)break;else""==e(m(p))?p.pop():(b=p.pop(),p.push(e(b))),p.push(C[a]);break;case "table":p.push("</table>"); break;case "thead":p.push("</thead>");break;case "tbody":p.push("</tbody>");break;case "tr":p.push("</tr>");break;case "td":p.push("</td>")}}},{nodesToPreserve:"script noscript object iframe frame head style label".split(" ")});if(!A)for(z=0;z<B.length;z++)if(0==z){var I=p.pop();p.push(I.replace(/\s+$/g,""));p.push("\n\n["+z+"]: "+B[z])}else p.push("\n["+z+"]: "+B[z]);return p.join("")}},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,function(c,b,a){(function(a){(function(){function a(b){this.tokens=[];this.tokens.links={};this.options=b||q.defaults;this.rules=r.normal;this.options.gfm&&(this.rules=this.options.tables?r.tables:r.gfm)}function b(a,c){this.options=c||q.defaults;this.links=a;this.rules=t.normal;this.renderer=this.options.renderer||new e;this.renderer.options=this.options;if(!this.links)throw Error("Tokens array requires a `links` property.");this.options.gfm?this.rules=this.options.breaks?t.breaks: t.gfm:this.options.pedantic&&(this.rules=t.pedantic)}function e(a){this.options=a||{}}function h(a){this.tokens=[];this.token=null;this.options=a||q.defaults;this.options.renderer=this.options.renderer||new e;this.renderer=this.options.renderer;this.renderer.options=this.options}function k(a,b){return a.replace(!b?/&(?!#?\w+;)/g:/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function l(a){return a.replace(/&([#\w]+);/g,function(a,b){b=b.toLowerCase(); return"colon"===b?":":"#"===b.charAt(0)?"x"===b.charAt(1)?String.fromCharCode(parseInt(b.substring(2),16)):String.fromCharCode(+b.substring(1)):""})}function m(a,b){a=a.source;b=b||"";return function x(c,d){if(!c)return RegExp(a,b);d=d.source||d;d=d.replace(/(^|[^\[])\^/g,"$1");a=a.replace(c,d);return x}}function n(){}function s(a){for(var b=1,c,d;b<arguments.length;b++)for(d in c=arguments[b],c)Object.prototype.hasOwnProperty.call(c,d)&&(a[d]=c[d]);return a}function q(b,c,d){if(d||"function"===typeof c){d|| (d=c,c=null);c=s({},q.defaults,c||{});var e=c.highlight,g,l,r=0;try{g=a.lex(b,c)}catch(m){return d(m)}l=g.length;var t=function(a){if(a)return c.highlight=e,d(a);var b;try{b=h.parse(g,c)}catch(f){a=f}c.highlight=e;return a?d(a):d(null,b)};if(!e||3>e.length)return t();delete c.highlight;if(!l)return t();for(;r<g.length;r++)(function(a){return"code"!==a.type?--l||t():e(a.text,a.lang,function(b,c){if(b)return t(b);if(null==c||c===a.text)return--l||t();a.text=c;a.escaped=!0;--l||t()})})(g[r])}else try{return c&& (c=s({},q.defaults,c)),h.parse(a.lex(b,c),c)}catch(n){n.message+="\nPlease report this to https://github.com/chjj/marked.";if((c||q.defaults).silent)return"<p>An error occured:</p><pre>"+k(n.message+"",!0)+"</pre>";throw n;}}var r={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:n,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:n,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:n,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/,bullet:/(?:[*+-]|\d+\.)/,item:/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/};r.item=m(r.item,"gm")(/bull/g,r.bullet)();r.list=m(r.list)(/bull/g,r.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+r.def.source+")")();r.blockquote= m(r.blockquote)("def",r.def)();r._tag="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b";r.html=m(r.html)("comment",/\x3c!--[\s\S]*?--\x3e/)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g,r._tag)();r.paragraph=m(r.paragraph)("hr",r.hr)("heading",r.heading)("lheading",r.lheading)("blockquote",r.blockquote)("tag","<"+r._tag)("def",r.def)();r.normal= s({},r);r.gfm=s({},r.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});r.gfm.paragraph=m(r.paragraph)("(?!","(?!"+r.gfm.fences.source.replace("\\1","\\2")+"|"+r.list.source.replace("\\1","\\3")+"|")();r.tables=s({},r.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});a.rules=r;a.lex=function(b,c){return(new a(c)).lex(b)}; a.prototype.lex=function(a){a=a.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");return this.token(a,!0)};a.prototype.token=function(a,b,c){a=a.replace(/^ +$/gm,"");for(var d,e,f,g,h,k,l;a;){if(f=this.rules.newline.exec(a))a=a.substring(f[0].length),1<f[0].length&&this.tokens.push({type:"space"});if(f=this.rules.code.exec(a))a=a.substring(f[0].length),f=f[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:!this.options.pedantic?f.replace(/\n+$/, ""):f});else if(f=this.rules.fences.exec(a))a=a.substring(f[0].length),this.tokens.push({type:"code",lang:f[2],text:f[3]||""});else if(f=this.rules.heading.exec(a))a=a.substring(f[0].length),this.tokens.push({type:"heading",depth:f[1].length,text:f[2]});else if(b&&(f=this.rules.nptable.exec(a))){a=a.substring(f[0].length);h={type:"table",header:f[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:f[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:f[3].replace(/\n$/,"").split("\n")};for(k=0;k<h.align.length;k++)/^ *-+: *$/.test(h.align[k])? h.align[k]="right":/^ *:-+: *$/.test(h.align[k])?h.align[k]="center":/^ *:-+ *$/.test(h.align[k])?h.align[k]="left":h.align[k]=null;for(k=0;k<h.cells.length;k++)h.cells[k]=h.cells[k].split(/ *\| */);this.tokens.push(h)}else if(f=this.rules.lheading.exec(a))a=a.substring(f[0].length),this.tokens.push({type:"heading",depth:"="===f[2]?1:2,text:f[1]});else if(f=this.rules.hr.exec(a))a=a.substring(f[0].length),this.tokens.push({type:"hr"});else if(f=this.rules.blockquote.exec(a))a=a.substring(f[0].length), this.tokens.push({type:"blockquote_start"}),f=f[0].replace(/^ *> ?/gm,""),this.token(f,b,!0),this.tokens.push({type:"blockquote_end"});else if(f=this.rules.list.exec(a)){a=a.substring(f[0].length);g=f[2];this.tokens.push({type:"list_start",ordered:1<g.length});f=f[0].match(this.rules.item);d=!1;l=f.length;for(k=0;k<l;k++)h=f[k],e=h.length,h=h.replace(/^ *([*+-]|\d+\.) +/,""),~h.indexOf("\n ")&&(e-=h.length,h=!this.options.pedantic?h.replace(RegExp("^ {1,"+e+"}","gm"),""):h.replace(/^ {1,4}/gm,"")), this.options.smartLists&&k!==l-1&&(e=r.bullet.exec(f[k+1])[0],g!==e&&!(1<g.length&&1<e.length)&&(a=f.slice(k+1).join("\n")+a,k=l-1)),e=d||/\n\n(?!\s*$)/.test(h),k!==l-1&&(d="\n"===h.charAt(h.length-1),e||(e=d)),this.tokens.push({type:e?"loose_item_start":"list_item_start"}),this.token(h,!1,c),this.tokens.push({type:"list_item_end"});this.tokens.push({type:"list_end"})}else if(f=this.rules.html.exec(a))a=a.substring(f[0].length),this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&& ("pre"===f[1]||"script"===f[1]||"style"===f[1]),text:f[0]});else if(!c&&b&&(f=this.rules.def.exec(a)))a=a.substring(f[0].length),this.tokens.links[f[1].toLowerCase()]={href:f[2],title:f[3]};else if(b&&(f=this.rules.table.exec(a))){a=a.substring(f[0].length);h={type:"table",header:f[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:f[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:f[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(k=0;k<h.align.length;k++)/^ *-+: *$/.test(h.align[k])?h.align[k]= "right":/^ *:-+: *$/.test(h.align[k])?h.align[k]="center":/^ *:-+ *$/.test(h.align[k])?h.align[k]="left":h.align[k]=null;for(k=0;k<h.cells.length;k++)h.cells[k]=h.cells[k].replace(/^ *\| *| *\| *$/g,"").split(/ *\| */);this.tokens.push(h)}else if(b&&(f=this.rules.paragraph.exec(a)))a=a.substring(f[0].length),this.tokens.push({type:"paragraph",text:"\n"===f[1].charAt(f[1].length-1)?f[1].slice(0,-1):f[1]});else if(f=this.rules.text.exec(a))a=a.substring(f[0].length),this.tokens.push({type:"text",text:f[0]}); else if(a)throw Error("Infinite loop on byte: "+a.charCodeAt(0));}return this.tokens};var t={escape:/^\\([\\`*{}\[\]()#+\-.!_>])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:n,tag:/^\x3c!--[\s\S]*?--\x3e|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, br:/^ {2,}\n(?!\s*$)/,del:n,text:/^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/,_inside:/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,_href:/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/};t.link=m(t.link)("inside",t._inside)("href",t._href)();t.reflink=m(t.reflink)("inside",t._inside)();t.normal=s({},t);t.pedantic=s({},t.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});t.gfm=s({},t.normal,{escape:m(t.escape)("])","~|])")(), url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:m(t.text)("]|","~]|")("|","|https?://|")()});t.breaks=s({},t.gfm,{br:m(t.br)("{2,}","*")(),text:m(t.gfm.text)("{2,}","*")()});b.rules=t;b.output=function(a,c,f){return(new b(c,f)).output(a)};b.prototype.output=function(a){for(var b="",c,d;a;)if(d=this.rules.escape.exec(a))a=a.substring(d[0].length),b+=d[1];else if(d=this.rules.autolink.exec(a))a=a.substring(d[0].length),"@"===d[2]?(c=":"===d[1].charAt(6)?this.mangle(d[1].substring(7)): this.mangle(d[1]),d=this.mangle("mailto:")+c):d=c=k(d[1]),b+=this.renderer.link(d,null,c);else if(!this.inLink&&(d=this.rules.url.exec(a)))a=a.substring(d[0].length),d=c=k(d[1]),b+=this.renderer.link(d,null,c);else if(d=this.rules.tag.exec(a))!this.inLink&&/^<a /i.test(d[0])?this.inLink=!0:this.inLink&&/^<\/a>/i.test(d[0])&&(this.inLink=!1),a=a.substring(d[0].length),b+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(d[0]):k(d[0]):d[0];else if(d=this.rules.link.exec(a))a=a.substring(d[0].length), this.inLink=!0,b+=this.outputLink(d,{href:d[2],title:d[3]}),this.inLink=!1;else if((d=this.rules.reflink.exec(a))||(d=this.rules.nolink.exec(a)))a=a.substring(d[0].length),c=(d[2]||d[1]).replace(/\s+/g," "),c=this.links[c.toLowerCase()],!c||!c.href?(b+=d[0].charAt(0),a=d[0].substring(1)+a):(this.inLink=!0,b+=this.outputLink(d,c),this.inLink=!1);else if(d=this.rules.strong.exec(a))a=a.substring(d[0].length),b+=this.renderer.strong(this.output(d[2]||d[1]));else if(d=this.rules.em.exec(a))a=a.substring(d[0].length), b+=this.renderer.em(this.output(d[2]||d[1]));else if(d=this.rules.code.exec(a))a=a.substring(d[0].length),b+=this.renderer.codespan(k(d[2],!0));else if(d=this.rules.br.exec(a))a=a.substring(d[0].length),b+=this.renderer.br();else if(d=this.rules.del.exec(a))a=a.substring(d[0].length),b+=this.renderer.del(this.output(d[1]));else if(d=this.rules.text.exec(a))a=a.substring(d[0].length),b+=this.renderer.text(k(this.smartypants(d[0])));else if(a)throw Error("Infinite loop on byte: "+a.charCodeAt(0));return b}; b.prototype.outputLink=function(a,b){var c=k(b.href),d=b.title?k(b.title):null;return"!"!==a[0].charAt(0)?this.renderer.link(c,d,this.output(a[1])):this.renderer.image(c,d,k(a[1]))};b.prototype.smartypants=function(a){return!this.options.smartypants?a:a.replace(/---/g,"\u2014").replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d").replace(/\.{3}/g,"\u2026")};b.prototype.mangle=function(a){if(!this.options.mangle)return a; for(var b="",c=a.length,d=0,f;d<c;d++)f=a.charCodeAt(d),0.5<Math.random()&&(f="x"+f.toString(16)),b+="&#"+f+";";return b};e.prototype.code=function(a,b,c){if(this.options.highlight){var d=this.options.highlight(a,b);null!=d&&d!==a&&(c=!0,a=d)}return!b?"<pre><code>"+(c?a:k(a,!0))+"\n</code></pre>":'<pre><code class="'+this.options.langPrefix+k(b,!0)+'">'+(c?a:k(a,!0))+"\n</code></pre>\n"};e.prototype.blockquote=function(a){return"<blockquote>\n"+a+"</blockquote>\n"};e.prototype.html=function(a){return a}; e.prototype.heading=function(a,b,c){return"<h"+b+' id="'+this.options.headerPrefix+c.toLowerCase().replace(/[^\w]+/g,"-")+'">'+a+"</h"+b+">\n"};e.prototype.hr=function(){return this.options.xhtml?"<hr/>\n":"<hr>\n"};e.prototype.list=function(a,b){var c=b?"ol":"ul";return"<"+c+">\n"+a+"</"+c+">\n"};e.prototype.listitem=function(a){return"<li>"+a+"</li>\n"};e.prototype.paragraph=function(a){return"<p>"+a+"</p>\n"};e.prototype.table=function(a,b){return"<table>\n<thead>\n"+a+"</thead>\n<tbody>\n"+b+ "</tbody>\n</table>\n"};e.prototype.tablerow=function(a){return"<tr>\n"+a+"</tr>\n"};e.prototype.tablecell=function(a,b){var c=b.header?"th":"td";return(b.align?"<"+c+' style="text-align:'+b.align+'">':"<"+c+">")+a+"</"+c+">\n"};e.prototype.strong=function(a){return"<strong>"+a+"</strong>"};e.prototype.em=function(a){return"<em>"+a+"</em>"};e.prototype.codespan=function(a){return"<code>"+a+"</code>"};e.prototype.br=function(){return this.options.xhtml?"<br/>":"<br>"};e.prototype.del=function(a){return"<del>"+ a+"</del>"};e.prototype.link=function(a,b,c){if(this.options.sanitize){try{var d=decodeURIComponent(l(a)).replace(/[^\w:]/g,"").toLowerCase()}catch(f){return""}if(0===d.indexOf("javascript:")||0===d.indexOf("vbscript:"))return""}a='<a href="'+a+'"';b&&(a+=' title="'+b+'"');return a+(">"+c+"</a>")};e.prototype.image=function(a,b,c){a='<img src="'+a+'" alt="'+c+'"';b&&(a+=' title="'+b+'"');return a+=this.options.xhtml?"/>":">"};e.prototype.text=function(a){return a};h.parse=function(a,b,c){return(new h(b, c)).parse(a)};h.prototype.parse=function(a){this.inline=new b(a.links,this.options,this.renderer);this.tokens=a.reverse();for(a="";this.next();)a+=this.tok();return a};h.prototype.next=function(){return this.token=this.tokens.pop()};h.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};h.prototype.parseText=function(){for(var a=this.token.text;"text"===this.peek().type;)a+="\n"+this.next().text;return this.inline.output(a)};h.prototype.tok=function(){switch(this.token.type){case "space":return""; case "hr":return this.renderer.hr();case "heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case "code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case "table":var a="",b="",c,d,f,e;f="";for(c=0;c<this.token.header.length;c++)f+=this.renderer.tablecell(this.inline.output(this.token.header[c]),{header:!0,align:this.token.align[c]});a+=this.renderer.tablerow(f);for(c=0;c<this.token.cells.length;c++){d=this.token.cells[c]; f="";for(e=0;e<d.length;e++)f+=this.renderer.tablecell(this.inline.output(d[e]),{header:!1,align:this.token.align[e]});b+=this.renderer.tablerow(f)}return this.renderer.table(a,b);case "blockquote_start":for(b="";"blockquote_end"!==this.next().type;)b+=this.tok();return this.renderer.blockquote(b);case "list_start":b="";for(a=this.token.ordered;"list_end"!==this.next().type;)b+=this.tok();return this.renderer.list(b,a);case "list_item_start":for(b="";"list_item_end"!==this.next().type;)b+="text"=== this.token.type?this.parseText():this.tok();return this.renderer.listitem(b);case "loose_item_start":for(b="";"list_item_end"!==this.next().type;)b+=this.tok();return this.renderer.listitem(b);case "html":return b=!this.token.pre&&!this.options.pedantic?this.inline.output(this.token.text):this.token.text,this.renderer.html(b);case "paragraph":return this.renderer.paragraph(this.inline.output(this.token.text));case "text":return this.renderer.paragraph(this.parseText())}};n.exec=n;q.options=q.setOptions= function(a){s(q.defaults,a);return q};q.defaults={gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new e,xhtml:!1};q.Parser=h;q.parser=h.parse;q.Renderer=e;q.Lexer=a;q.lexer=a.lex;q.InlineLexer=b;q.inlineLexer=b.output;q.parse=q;c.exports=q}).call(function(){return this||("undefined"!==typeof window?window:a)}())}).call(b,function(){return this}())},,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b){var a=function(b,c,d){d=d||{};var g=document.createElement("div");g.innerHTML=b;b=d.nodesToIgnore||[];for(var h=d.parseHiddenNodes||"false",k=d.nodesToPreserve||[],l=d.preserveAttribute||"data-preserve-html-node",g=g.childNodes,m=0;m<g.length;m++)try{for(var n=!1,s=0;s<b.length;s++)if(g[m].nodeName.toLowerCase()==b[s]){n=!0;break}for(var s=!1,q=0;q<k.length;q++)if(g[m].nodeName.toLowerCase()==k[q]){s=!0;break}var r; if(!(r=n)){var t;if(t=!h)a:{var p=g[m];if("title"==p.nodeName.toLowerCase())t=!1;else if(window.getComputedStyle){try{var u=window.getComputedStyle(p,null);if(u.getPropertyValue&&"none"==u.getPropertyValue("display")){t=!0;break a}}catch(v){}t=!1}else t=void 0}r=t}if(!r)if("#text"!=g[m].nodeName.toLowerCase()&&"#comment"!=g[m].nodeName.toLowerCase()){n=[];if(g[m].hasAttributes()){for(var x=g[m].attributes,q=0;q<x.length;q++){var w=x.item(q);n.push({name:w.nodeName,value:w.nodeValue})}void 0!==g[m].attributes[l]&& (s=!0)}if(c.preserve&&s)c.preserve(g[m],l);else if(c.start)if(g[m].hasChildNodes()){c.start(g[m].nodeName,n,!1);if("iframe"==g[m].nodeName.toLowerCase()||"frame"==g[m].nodeName.toLowerCase()){if(g[m].contentDocument&&g[m].contentDocument.documentElement)return a(g[m].contentDocument.documentElement,c,d)}else a(g[m].innerHTML,c,d);c.end&&c.end(g[m].nodeName)}else c.start(g[m].nodeName,n,!0)}else"#text"==g[m].nodeName.toLowerCase()?c.chars&&c.chars(g[m].nodeValue):"#comment"==g[m].nodeName.toLowerCase()&& c.comment&&c.comment(g[m].nodeValue)}catch(y){console.error(y),console.log("error while parsing node: "+g[m].nodeName.toLowerCase())}};c.exports=a},function(c,b){function a(a,b){var c=(a&65535)+(b&65535);return(a>>16)+(b>>16)+(c>>16)<<16|c&65535}c.exports=function(b){for(var c=[],d=0;d<8*b.length;d+=8)c[d>>5]|=(b.charCodeAt(d/8)&255)<<24-d%32;b=8*b.length;c[b>>5]|=128<<24-b%32;c[(b+64>>9<<4)+15]=b;b=Array(80);for(var d=1732584193,g=-271733879,h=-1732584194,k=271733878,l=-1009589776,m=0;m<c.length;m+= 16){for(var n=d,s=g,q=h,r=k,t=l,p=0;80>p;p++){b[p]=16>p?c[m+p]:(b[p-3]^b[p-8]^b[p-14]^b[p-16])<<1|(b[p-3]^b[p-8]^b[p-14]^b[p-16])>>>31;var u=d<<5|d>>>27,v;v=20>p?g&h|~g&k:40>p?g^h^k:60>p?g&h|g&k|h&k:g^h^k;u=a(a(u,v),a(a(l,b[p]),20>p?1518500249:40>p?1859775393:60>p?-1894007588:-899497514));l=k;k=h;h=g<<30|g>>>2;g=d;d=u}d=a(d,n);g=a(g,s);h=a(h,q);k=a(k,r);l=a(l,t)}c=[d,g,h,k,l];b="";for(d=0;d<4*c.length;d+=3){g=(c[d>>2]>>8*(3-d%4)&255)<<16|(c[d+1>>2]>>8*(3-(d+1)%4)&255)<<8|c[d+2>>2]>>8*(3-(d+2)%4)& 255;for(h=0;4>h;h++)b=8*d+6*h>32*c.length?b+"=":b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>6*(3-h)&63)}return b}},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b,a){var e=a(74),f=a(1837),d=a(1820);YUI.add("squarespace-login",function(a){if(!a.config.win.SQUARESPACE_LOGIN){var b=e.isFeatureEnabled("singleSignOn")?d:f;a.config.win.SQUARESPACE_LOGIN=Singleton.create(b.init(a));a.augment(a.config.win.SQUARESPACE_LOGIN,a.EventTarget)}},"1.0",{requires:"event-resize squarespace-dialog squarespace-dialog-check squarespace-dialog-description squarespace-dialog-hidden squarespace-dialog-multi-option squarespace-external-authentication squarespace-google-domains-utils squarespace-login-widget-wrapper squarespace-models-member-account squarespace-plugin-v5login squarespace-spinner squarespace-util squarespace-widgets-alert squarespace-widgets-information squarespace-widgets-login squarespace-widgets-password-reset squarespace-widgets-website-selector".split(" ")})}, function(c,b,a){YUI.add("squarespace-markdown",function(b){b.namespace("Squarespace.Lang");b.Squarespace.Lang.markdownFromHTML=function(b){var c=a(1522);return!b?"":c(b)};b.Squarespace.Lang.markdownToHTML=function(b){var c=a(1653);if(!b)return"";c.setOptions({breaks:!0});return c(b)}},"1.0",{requires:[]})},,,,,,,,,,,,,,,,,,,,,,function(c,b,a){var e=a(2),f=a(33),d=a(1337),g=a(706),h=a(541),k=a(304),l=a(249);c.exports={init:function(a){return{ready:function(){Static.SQUARESPACE_CONTEXT&&(this.account= Static.SQUARESPACE_CONTEXT.authenticatedAccount)},configure:function(){},isLoggedIn:function(){return!!this.account},getAccount:function(){return this.account},showWwwLogin:function(){if(!this.wwwAuthenticationFrame){var a="https://"+l.getDomainForIdentifier(k.OAUTH);this.wwwAuthenticationFrame=f.render(e.createElement(d,{onMessageReceived:function(a){a.type===h.REDIRECT&&(g.showLoading(),window.location=a.location)},url:a+"/config/website-disambiguation/general?redirect="+encodeURIComponent("/config")}), document.body.appendChild(document.createElement("div")))}g.show()},showCommentLogin:function(){this.commentAuthenticationFrame||(this.commentAuthenticationFrame=f.render(e.createElement(d,{onMessageReceived:this._onCommentFrameMessage,url:"/config/authentication-frame/comments"}),document.body.appendChild(document.createElement("div"))));g.show()},_onCommentFrameMessage:function(b){b.type===h.AUTHENTICATED?(g.closeFrame(),Static.SQUARESPACE_CONTEXT.authenticatedAccount=b.account,a.config.win.SQUARESPACE_LOGIN.account= b.account,a.config.win.SQUARESPACE_LOGIN.fire("login")):h.CLOSE&&(g.closeFrame(),a.config.win.SQUARESPACE_LOGIN.fire("cancel"))}}}}},,,,,,,function(c,b,a){var e=a(1);YUI.add("squarespace-plugin-v5login",function(b){var c=a(1754);b.namespace("Squarespace.Plugin");b.Squarespace.Plugin.V5Login=b.Base.create("V5Login",b.Plugin.Base,[],{initializer:function(a){this._eventHandler=b.Do.before(this._proxyLogin,this.get("host"),"_loginSquarespace",this)},destroy:function(){this._eventHandler.detach();this._eventHandler= null},_proxyLogin:function(){var a=this.get("host"),c=b.Squarespace.FormUtils.getData(a._fields),a=c.email,c=c.password;if(-1===a.indexOf("@"))return new b.Do.Halt(e("V5 account"),this._v5Login(a,c))},_v5Login:function(a,e){var k=c(e);return SQUARESPACE_LOGIN.loginRPCProvider?new b.Promise(function(b,c){SQUARESPACE_LOGIN.loginRPCProvider.v5LoginRequest(a,k,b,function(a){c(a.message)})}):b.Squarespace.Auth.loginV5(a,k)}},{NS:"v5login"})},"1.0",{requires:["base","squarespace-form-utils","squarespace-v5login-utils"]})}, ,,,,,,,,function(c,b,a){var e=a(1);YUI.add("squarespace-v5login-utils",function(a){a.namespace("Squarespace.Auth");a.Squarespace.Auth.loginV5=function(b,c){return new a.Promise(function(h,k){a.Data.post({xdr:{credentials:!0},url:"https://squarespace5.squarespace.com/process/service/CredentialCheck",data:{A:b,B:c,from6:!0},success:function(a){h({type:"v5",url:"http://"+b+".squarespace.com/process/service/TokenLogin?loginToken="+a.loginToken})},failure:function(b){b.type="v5";b.errors?(a.Object.each(b.errors, function(a,c){b.errors[c]=a.replace(/support@squarespace.com/g,"customercare@squarespace.com")}),k(b)):k({error:e("There was an unexpected error. Please try again later.")})}},this)})}},"1.0",{requires:["promise","squarespace-util"]})},function(c,b,a){var e=a(1),f=a(2),d=a(33);b=a(71);var g=a(966),h=a(923),k=a(339),l=a(454),m=a(304),n=a(249),s=a(233),q=b(m),r,t,p,u;switch(!1){case "loginWithSocialAccounts":r=!0;u=p=t=void 0;break;case "commentsLogin":u=p=t=r=!0;break;case "acceptInvitation":p=!0, u=t=r=void 0}c.exports={init:function(a){return{ready:function(){Static.SQUARESPACE_CONTEXT&&(this.account=Static.SQUARESPACE_CONTEXT.authenticatedAccount);this.params=this.defaultParams={redirectAfterCancel:!0,redirectAfterLogin:!0,minimal:!1,cancelable:!0,overlayOpacity:0.8,disableOverlayCancel:!1,forgotPassword:!0,disableCreateAccount:!0,globalLogin:!0,allowSocialLogins:!0,canSignup:!1};this.dialogParameters=null},configure:function(b){this.params=this.defaultParams;this.params=a.merge(this.params, b)},reset:function(){this.params=this.defaultParams},isLoggedIn:function(){return!!this.account},getAccount:function(){return this.account},_getNoLoginDialogParams:function(){return{style:"flyout",discardChangesConfirmation:!1,overlay:this.params.overlayOpacity,width:400,closeOthers:!1,closeable:!this.params.disableOverlayCancel,disableOverlayCancel:this.params.disableOverlayCancel,tabs:[{title:e("Squarespace Login"),icon:"/universal/images-v6/dialog/login-icon.png?4",fields:[{ctor:a.Squarespace.DialogFields.Description, config:{text:e("This browser does not accept cookies, which is a requirement for login. You can allow cookies by changing your browser's settings.")}}]}]}},showCommentLogin:function(a,b,c,d){d||(d=["squarespace","google","twitter","facebook"]);this.iFrameCommentLoginShow(a,b,c,d)},showWwwLogin:function(){SQUARESPACE_LOGIN.params.disableOverlayCancel=!0;SQUARESPACE_LOGIN.params.overlayOpacity=!1;SQUARESPACE_LOGIN.params.disableCreateAccount=!1;SQUARESPACE_LOGIN.params.canSignup=!0;this._showLoginInIframe()}, _getWebsiteUrl:function(){var a=Static.SQUARESPACE_CONTEXT.website;return!a?"":q.contains(a.identifier)?"":a.authenticUrl},_showCommentLoginIniFrame:function(b,c,d,f,e){try{var g="squarespace";d&&(e.splice(0,0,"guest"),g="guest");var h=a.Node.create('<div class="login-wrapper-node"></div>'),k=a.one("body");if(k){k.append(h);var p=new a.Squarespace.Widgets.LoginWidgetWrapper({srcNode:h,render:!0,tabsEnabled:e,activeLoginMethod:g,returnWebsiteList:!1,canCreateAccount:!0,canCancel:!0,title:b,targetIdentifier:f, className:"comments",websiteUrl:this._getWebsiteUrl(),"strings.loginButtonTitle":c});p.on("loginSuccess",function(a){SQUARESPACE_LOGIN.loginRPCProvider.commentLoginSuccess({type:a.type,displayName:a.displayName,email:a.email,authorUrl:a.authorUrl,account:a.account,website:a.website});SQUARESPACE_LOGIN.loginRPCProvider.remove(!1);p.destroy()},this);p.on("destroy",function(){SQUARESPACE_LOGIN.loginRPCProvider.remove(!1)},this);p.on("cancel",function(){SQUARESPACE_LOGIN.loginRPCProvider.remove(!0)}, this)}else console.log("no body element")}catch(l){console.log("ERROR: found error: "+l,l)}},showGoogleWebhostingLogin:function(){this._showSimpleLogin({enableGoogleLoginLink:!0,returnWebsiteList:!0}).then(a.bind(function(b){a.Squarespace.GoogleDomains.initiateWebsiteLink(b.websites)},this))},showReferralDisambigLogin:function(b){var c={returnWebsiteList:!0};a.Lang.isString(b)&&(c.email=b,c.disableEmailChange=!0);this._showSimpleLogin(c).then(a.bind(function(a){this._displayWebsiteSelector(a.websites, "/auth/referral/"+Static.SQUARESPACE_CONTEXT.referralSecretToken+"/disambiguate")},this))},_showSimpleLogin:function(b){var c=this._getWebsiteUrl();return new a.Promise(function(d,f){if(a.Squarespace.Utils.areCookiesEnabled()){b=a.merge({render:!0,websiteUrl:c},b);var e=new a.Squarespace.Widgets.LoginWidgetWrapper(b);e.on("loginSuccess",function(a){e.destroy({remove:!0});d(a)},this);a.Squarespace.Analytics.trackInternal("engagement_login_overview_view")}else{var g=this._getNoLoginDialogParams();(new a.Squarespace.EditingDialog(g)).show(); f()}})},_displayWebsiteSelector:function(b,c){l.loadSuccess(b);k.bootstrap({disambiguationType:s.DEFAULT,redirectPath:c,currentWebsiteIdentifier:m.WWW,appDomain:n.getAppDomain()});var e=f.createElement(h,{shouldShowListWhenOnlyOneWebsite:!1}),g=a.one(".login-overlay,.website-selector");g||(g=a.one(a.config.doc.body).appendChild('<div class="website-selector"></div>'));d.render(e,g.getDOMNode())},acceptInvitationSignin:function(b,c){if(a.Squarespace.Utils.areCookiesEnabled()){var d=new a.Squarespace.Widgets.LoginWidgetWrapper({email:b.email, enableGoogleLoginLink:!1,render:!0,tabsEnabled:[],canCreateAccount:!0,targetIdentifier:window.Static.SQUARESPACE_CONTEXT.website.identifier,websiteUrl:this._getWebsiteUrl()});d.on("loginSuccess",function(a){d.destroy();a=a.website.loginUrl+"&redirectUrl="+encodeURIComponent(c);window.location.replace(a)})}else{var f=this._getNoLoginDialogParams();(new a.Squarespace.EditingDialog(f)).show()}},show:function(){if(a.Squarespace.Utils.areCookiesEnabled()){var b=a.Cookie.get("email"),c=!0,d=["squarespace"], f=!0,g=!1;if(Static.SQUARESPACE_CONTEXT.hasSocialAccounts||r)d=["squarespace","google","twitter","facebook"],f=!1;t&&d.push("guest");var h={};p&&(h.canCreateAccount=!0);u&&(h.canCancel=!0);this.params&&"undefined"!==typeof this.params.canSignup&&(g=this.params.canSignup);var k=new a.Squarespace.Widgets.LoginWidgetWrapper(a.merge({websiteUrl:this._getWebsiteUrl(),render:!0,enableGoogleLoginLink:f,tabsEnabled:d,returnWebsiteList:!0,email:b,canSignup:g},h));k.enableV5();if(this.loginRPCProvider)k.on("destroy", function(a){this.loginRPCProvider.remove()},this);k.on("loginSuccess",function(b){k.destroy();a.one(a.config.doc.body).removeClass("login-visible");a.Lang.isObject(b.account)&&a.Lang.isString(b.account.email)&&(("v6"===b.type||"v5"===b.type)&&a.Cookie.set("email",b.account.email),0<=location.pathname.indexOf("squarespace-admin")&&(c=!1));if("v5"===b.type)top.window.location.replace(b.url);else if(a.Lang.isString(b.redirectUrl))top.window.location.replace(b.redirectUrl);else if(c){var d=Static.SQUARESPACE_CONTEXT.website.identifier, f=b.websites.filter(function(a){return d===a.identifier});1===f.length&&(b.websites=f);a.Lang.isArray(b.websites)&&(f=d===m.WWW?"/config":location.pathname+location.search+location.hash,this._displayWebsiteSelector(b.websites,f))}else if(a.Lang.isObject(b.website)){b=b.website;var f="/config",g=location.host,g=g.substr(0,g.indexOf("."));b.identifier===g&&(f=location.pathname+location.search+location.hash);f=b.loginUrl+"&redirectUrl="+encodeURIComponent(f);top.window.location.replace(f)}else a.Squarespace.Widgets.Alert({position:a.Squarespace.Widgets.Confirmation.ANCHOR.CENTER, "strings.title":e("Login Failed"),"strings.message":e("We could not find a website you have access to for the account you signed in with.")}),a.soon(function(){a.one(a.config.doc.body).addClass("login-visible")})},this);a.soon(function(){var b=k.get("boundingBox").one(".body.squarespace .mode.squarespace input[name=email]");if(b)a.one(a.config.win).on("click",function(a){a.target.ancestor(".sqs-widgets-login")||b.focus()})})}else b=this._getNoLoginDialogParams(),(new a.Squarespace.EditingDialog(b)).show()}, onEscape:function(){a.one("body").removeClass("login-visible");a.later(300,this,function(){a.config.win.location.href="http://"+a.config.win.location.host+"/"})},onLoginComplete:function(b,c){a.config.win.SQUARESPACE_LOGIN.account=b;SQUARESPACE_LOGIN.loginRPCProvider&&c?a.config.win.SQUARESPACE_LOGIN.fire("iframeLogin",c):this.params.redirectAfterLogin||this.params.reloadAfterLogin?c?c===a.config.win.location.href?a.config.win.location.reload():a.config.win.location.replace(c):new a.Squarespace.Widgets.Alert({"strings.title":e("No Administrative Privileges"), "strings.message":e("Your Squarespace account is not listed as an administrator on any sites.")}):(a.config.win.SQUARESPACE_LOGIN.fire("login"),this.params.globalLogin&&a.Global.fire("squarespace:login"),this.reset())},onCommentLoginSuccess:function(b){if("guest"===b.type){var c=new Date;c.setSeconds(c.getSeconds()+30);a.Cookie.set("email",b.email,{path:"/",expires:c});a.Cookie.set("displayName",b.displayName,{path:"/",expires:c});a.Cookie.set("websiteUrl",b.authorUrl,{path:"/",expires:c});a.config.win.SQUARESPACE_LOGIN.fire("guestLogin"); this.params.globalLogin&&a.Global.fire("squarespace:login")}else{var d=b.account;a.Data.get({url:b.website.loginUrl,secure:!0,success:function(){Static.SQUARESPACE_CONTEXT.authenticatedAccount=d;a.config.win.SQUARESPACE_LOGIN.account=d;a.config.win.SQUARESPACE_LOGIN.fire("login");this.params.globalLogin&&a.Global.fire("squarespace:login")},failure:function(b){new a.Squarespace.Widgets.Alert({position:a.Squarespace.Widgets.Confirmation.ANCHOR.CENTER,"strings.title":e("Login Failed"),"strings.message":e("An unexpected error happened, please try again.")}); console.error("failed to sign in with token",b)}},this)}},_buildIFrameLoginDialog:function(){this.buildDialog()},_showLoginInIframe:function(){this.show();if(a.Lang.isValue(this.loginRPCProvider)){var b=a.Node.create('<div class="login-overlay"><div class="close-x"></div></div>');a.one("body").append(b);b.on("click",function(a){SQUARESPACE_LOGIN.loginRPCProvider.remove()},this)}else a.one("html").addClass("squarespace-damask"),a.one("html").removeClass("squarespace-cameron"),a.one("body").addClass("squarespace-login")}, loadRPCProvider:function(){try{this.loginRPCProvider=new g.Rpc({},{local:{show:function(){SQUARESPACE_LOGIN._showLoginInIframe()},showCommentLogin:SQUARESPACE_LOGIN._showCommentLoginIniFrame.bind(SQUARESPACE_LOGIN)},remote:{remove:{},v5LoginRequest:{},commentLoginSuccess:{}}})}catch(a){console.log("failed to load RPC",a)}},_loadRPCConsumer:function(b,c){this.loginRPCConsumer=new g.Rpc({remote:"https://oauth."+Static.SQUARESPACE_CONTEXT.appDomain+"/config/iframeLogin",container:b,onReady:c,props:{style:{width:"100%", height:"100%",top:0,left:0,position:"fixed",zIndex:30040}}},{local:{remove:function(a){SQUARESPACE_LOGIN.iFrameLoginRemove(a)},v5LoginRequest:function(b,c,d,f){a.Squarespace.Auth.loginV5(b,c).then(d,f)},commentLoginSuccess:a.bind(this.onCommentLoginSuccess,this)},remote:{show:{},showCommentLogin:{}}})},iFrameLoginLoad:function(b){var c=a.Node.create('<div class="login-wrapper hidden" ></div>');a.one("body").append(c);this._loadRPCConsumer(c.getDOMNode(),b)},_getLoginOverlayNode:function(){var b=a.Node.create('<div class="login-overlay" style="position: fixed; top: 0; right:0; height: 100%; width: 100%; z-index: 30000; background: rgba(204, 204, 204, 0.65);"></div>'); this._loginOverlaySpinner=new a.Squarespace.Spinner({render:b,size:"large",color:"dark"});this._loginOverlaySpinner.get("boundingBox").setStyles({position:"fixed",top:"50%",left:"50%",marginLeft:"-11px",marginTop:"-11px"});return b},iFrameLoginShow:function(b){b&&b.preventDefault();b=this._getLoginOverlayNode();a.one("body").append(b);this.loginRPCConsumer?this._iFrameLoginShow():SQUARESPACE_LOGIN.iFrameLoginLoad(a.bind(this._iFrameLoginShow,this))},_iFrameLoginShow:function(){this.loginRPCConsumer.show(); a.one(".login-wrapper").removeClass("hidden");this._loginOverlaySpinner&&this._loginOverlaySpinner.destroy();a.one("body").addClass("no-scroll")},iFrameCommentLoginShow:function(b,c,d,f){var e=this._getLoginOverlayNode();a.one("body").append(e);this.loginRPCConsumer?this._iFrameCommentLoginShow(b,c,d,f):SQUARESPACE_LOGIN.iFrameLoginLoad(a.bind(this._iFrameCommentLoginShow,this,b,c,d,f))},_iFrameCommentLoginShow:function(b,c,d,f){var e=Static.SQUARESPACE_CONTEXT.website.identifier,g=this.loginRPCConsumer.showCommentLogin; a.soon(function(){g(b,c,d,e,f)});a.one(".login-wrapper").removeClass("hidden");this._loginOverlaySpinner&&this._loginOverlaySpinner.destroy()},iFrameLoginHide:function(){this.overlay.hideScreenOverlay();a.one(".login-wrapper").addClass("hidden")},iFrameLoginRemove:function(b){this.loginRPCConsumer.destroy();delete this.loginRPCConsumer;a.one(".login-overlay").remove();a.one("body").removeClass("no-scroll");a.one(".login-wrapper").remove();b&&this.fire("cancel")}}}}},,,,,function(c,b,a){var e=a(1), f=a(1057);YUI.add("squarespace-login-widget-wrapper",function(a){a.namespace("Squarespace.Widgets");a.Squarespace.Widgets.LoginWidgetWrapper=a.Base.create("login-widget-wrapper",a.Squarespace.SSWidget,[],{renderUI:function(){var b=this.get("contentBox"),c=this.get("createAccountWidget");this.get("loginWidget").render(b);c.render(b);c.get("contentBox").addClass("hidden");a.soon(function(){a.one(a.config.doc.body).addClass("login-visible")})},bindUI:function(){var a=this.get("createAccountWidget"), b=this.get("loginWidget");this._registerEvent(a.on("cancel",this._onCancelCreateAccount,this),a.after("memberAccountChange",this._onMemberAccountChange,this),b.on("cancel",this._onLoginCancel,this),b.on("create-account",this._onCreateAccountClick,this),b.on("loginSuccess",this._onLoginSuccess,this))},enableV5:function(){this.get("loginWidget").plug(a.Squarespace.Plugin.V5Login)},_onLoginSuccess:function(a){this.fire("loginSuccess",a)},_onLoginCancel:function(a){this.fire("cancel",a)},_onCancelCreateAccount:function(){var a= this.get("createAccountWidget"),b=this.get("loginWidget"),c=a.getEmail();b.setEmail(c);a.get("contentBox").addClass("hidden");b.get("contentBox").removeClass("hidden")},_onCreateAccountClick:function(){var a=this.get("createAccountWidget"),b=this.get("loginWidget"),c=b.getEmail();a.setEmail(c);b.get("contentBox").addClass("hidden");a.get("contentBox").removeClass("hidden")},_onMemberAccountChange:function(){var b=this.get("createAccountWidget"),c=this.get("loginWidget"),f=b.get("memberAccount"),e= b.get("password");a.Lang.isValue(f)&&(a.Squarespace.FormUtils.setData(c._fields,{email:f.get("email"),password:e}),b.get("contentBox").addClass("hidden"),c.get("contentBox").removeClass("hidden"),c._loginSquarespace().then(a.bind(c._handleLoginSuccess,this),a.bind(c._handleLoginFailure,this)))}},{ATTRS:{loginWidget:{valueFn:function(){return new a.Squarespace.Widgets.Login({websiteUrl:this.get("websiteUrl"),enableGoogleLoginLink:this.get("enableGoogleLoginLink"),tabsEnabled:this.get("tabsEnabled"), activeLoginMethod:this.get("activeLoginMethod"),disableEmailChange:this.get("disableEmailChange"),useLoginFlag:this.get("useLoginFlag"),returnWebsiteList:!0,email:this.get("email"),title:this.get("title"),targetIdentifier:this.get("targetIdentifier"),canCancel:this.get("canCancel"),canCreateAccount:this.get("canCreateAccount"),canSignup:this.get("canSignup"),waiting:this.get("waiting"),"strings.loginButtonTitle":this.get("strings.loginButtonTitle")})}},createAccountWidget:{valueFn:function(){var b= this.get("name").split(" ");return new a.Squarespace.Widgets.CreateAccount({render:!0,email:this.get("email"),firstName:this.get("name")?b[0]:"",lastName:this.get("name")?b[1]:""})}},activeLoginMethod:{value:"squarespace",validator:a.Squarespace.AttrValidators.isValueIn(f)},enableStayLoggedIn:{value:!0,writeOnce:"initOnly"},tabsEnabled:{value:["squarespace"],validator:a.Squarespace.AttrValidators.isArray,writeOnce:"initOnly"},currentState:{value:"login",validator:a.Squarespace.AttrValidators.isString}, canCancel:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},enableGoogleLoginLink:{value:!1,writeOnce:"initOnly"},returnWebsiteList:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},targetIdentifier:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},email:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},name:{value:"",validator:a.Squarespace.AttrValidators.isNullOrString, writeOnce:"initOnly"},disableEmailChange:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},canCreateAccount:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},canSignup:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},useLoginFlag:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean,writeOnce:"initOnly"},waiting:{value:!1,validator:a.Squarespace.AttrValidators.isBoolean},render:{value:!0,validator:a.Squarespace.AttrValidators.isBoolean}, strings:{value:{loginButtonTitle:e("Login")}},title:{value:null,validator:a.Squarespace.AttrValidators.isNullOrString,writeOnce:"initOnly"},websiteUrl:{value:"",writeOnce:"initOnly"}}})},"1.0",{requires:"base squarespace-ss-widget squarespace-attr-validators squarespace-widgets-create-account squarespace-form-utils squarespace-plugin-v5login squarespace-widgets-login".split(" ")})},function(c,b,a){var e=a(1);YUI.add("squarespace-widgets-password-reset",function(a){var b={name:"password-reset",loadingText:"Loading...", savingText:"",closingText:"",style:"minimal",width:400,closeOthers:!1,closeable:!1,disableOverlayCancel:!0,buttons:[{type:"saveAndClose",title:e("Save")}],title:{$value:"title"},initialData:{email:{$value:"email"},recoveryId:{$value:"recoveryId"}},fields:[{ctor:a.Squarespace.DialogFields.Description,config:{text:{$value:"message"}}},{ctor:a.Squarespace.DialogFields.Password,config:{name:"password","strings.placeholder":e("New Password"),submitOnEnter:!0,strengthMeterVisible:!0}}]};a.namespace("Squarespace.Widgets"); var c=a.Squarespace.Widgets.PasswordReset=a.Base.create("PasswordReset",a.Squarespace.EditingDialog,[],{initialize:function(e){c.superclass.initialize.call(this);e=a.merge({},e);e=a.Squarespace.ObjectBuilder.make(b,{},e);this.setParams(e);this.on("send-requested",this._submit,this);this.publish("success",{emitFacade:!0})},_submit:function(b){a.Lang.isObject(b)&&b.halt();var c=this.getData();a.Squarespace.Promises.create(function(b,d){a.Data.post({url:"/api/auth/password-reset",secure:!0,json:!0,data:c, success:b,failure:d})}).then(a.bind(this._handleSuccess,this),a.bind(this._handleFailure,this))},_handleSuccess:function(){this.fire("success")},_handleFailure:function(b){b.twoFactorAuthException?this._handleTwoFactorAuthRequired():a.Lang.isValue(b.errors)&&this.showErrors(b.errors)},_handleTwoFactorAuthRequired:function(){this.temporaryHide();var b=this.getData(),b=new a.Squarespace.Widgets.TwoFactorAuth({email:b.email});b.show();b.on("close",function(a){this.temporaryShow();this.hideSaveOverlay(); this.focusTab()},this);b.on("success",function(a){this._submit()},this)}})},"1.0",{requires:["base","squarespace-dialog","squarespace-object-builder","squarespace-promises","squarespace-widgets-two-factor-auth"]})},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b,a){a={atype:{NONE:0,URI:1,URI_FRAGMENT:11,SCRIPT:2,STYLE:3,ID:4,IDREF:5,IDREFS:6,GLOBAL_NAME:7,LOCAL_NAME:8,CLASSES:9,FRAME_TARGET:10},ATTRIBS:{"*::class":9,"*::dir":0,"*::id":4,"*::lang":0,"*::onclick":2,"*::ondblclick":2,"*::onkeydown":2,"*::onkeypress":2,"*::onkeyup":2,"*::onload":2,"*::onmousedown":2,"*::onmousemove":2,"*::onmouseout":2,"*::onmouseover":2, "*::onmouseup":2,"*::style":3,"*::title":0,"a::accesskey":0,"a::coords":0,"a::href":1,"a::hreflang":0,"a::name":7,"a::onblur":2,"a::onfocus":2,"a::rel":0,"a::rev":0,"a::shape":0,"a::tabindex":0,"a::target":10,"a::type":0,"area::accesskey":0,"area::alt":0,"area::coords":0,"area::href":1,"area::nohref":0,"area::onblur":2,"area::onfocus":2,"area::shape":0,"area::tabindex":0,"area::target":10,"bdo::dir":0,"blockquote::cite":1,"br::clear":0,"button::accesskey":0,"button::disabled":0,"button::name":8,"button::onblur":2, "button::onfocus":2,"button::tabindex":0,"button::type":0,"button::value":0,"caption::align":0,"col::align":0,"col::char":0,"col::charoff":0,"col::span":0,"col::valign":0,"col::width":0,"colgroup::align":0,"colgroup::char":0,"colgroup::charoff":0,"colgroup::span":0,"colgroup::valign":0,"colgroup::width":0,"del::cite":1,"del::datetime":0,"dir::compact":0,"div::align":0,"dl::compact":0,"font::color":0,"font::face":0,"font::size":0,"form::accept":0,"form::action":1,"form::autocomplete":0,"form::enctype":0, "form::method":0,"form::name":7,"form::onreset":2,"form::onsubmit":2,"form::target":10,"h1::align":0,"h2::align":0,"h3::align":0,"h4::align":0,"h5::align":0,"h6::align":0,"hr::align":0,"hr::noshade":0,"hr::size":0,"hr::width":0,"iframe::align":0,"iframe::frameborder":0,"iframe::height":0,"iframe::marginheight":0,"iframe::marginwidth":0,"iframe::width":0,"img::align":0,"img::alt":0,"img::border":0,"img::height":0,"img::hspace":0,"img::ismap":0,"img::name":7,"img::src":1,"img::usemap":11,"img::vspace":0, "img::width":0,"input::accept":0,"input::accesskey":0,"input::align":0,"input::alt":0,"input::autocomplete":0,"input::checked":0,"input::disabled":0,"input::ismap":0,"input::maxlength":0,"input::name":8,"input::onblur":2,"input::onchange":2,"input::onfocus":2,"input::onselect":2,"input::readonly":0,"input::size":0,"input::src":1,"input::tabindex":0,"input::type":0,"input::usemap":11,"input::value":0,"ins::cite":1,"ins::datetime":0,"label::accesskey":0,"label::for":5,"label::onblur":2,"label::onfocus":2, "legend::accesskey":0,"legend::align":0,"li::type":0,"li::value":0,"map::name":7,"menu::compact":0,"ol::compact":0,"ol::start":0,"ol::type":0,"optgroup::disabled":0,"optgroup::label":0,"option::disabled":0,"option::label":0,"option::selected":0,"option::value":0,"p::align":0,"pre::width":0,"q::cite":1,"select::disabled":0,"select::multiple":0,"select::name":8,"select::onblur":2,"select::onchange":2,"select::onfocus":2,"select::size":0,"select::tabindex":0,"table::align":0,"table::bgcolor":0,"table::border":0, "table::cellpadding":0,"table::cellspacing":0,"table::frame":0,"table::rules":0,"table::summary":0,"table::width":0,"tbody::align":0,"tbody::char":0,"tbody::charoff":0,"tbody::valign":0,"td::abbr":0,"td::align":0,"td::axis":0,"td::bgcolor":0,"td::char":0,"td::charoff":0,"td::colspan":0,"td::headers":6,"td::height":0,"td::nowrap":0,"td::rowspan":0,"td::scope":0,"td::valign":0,"td::width":0,"textarea::accesskey":0,"textarea::cols":0,"textarea::disabled":0,"textarea::name":8,"textarea::onblur":2,"textarea::onchange":2, "textarea::onfocus":2,"textarea::onselect":2,"textarea::readonly":0,"textarea::rows":0,"textarea::tabindex":0,"tfoot::align":0,"tfoot::char":0,"tfoot::charoff":0,"tfoot::valign":0,"th::abbr":0,"th::align":0,"th::axis":0,"th::bgcolor":0,"th::char":0,"th::charoff":0,"th::colspan":0,"th::headers":6,"th::height":0,"th::nowrap":0,"th::rowspan":0,"th::scope":0,"th::valign":0,"th::width":0,"thead::align":0,"thead::char":0,"thead::charoff":0,"thead::valign":0,"tr::align":0,"tr::bgcolor":0,"tr::char":0,"tr::charoff":0, "tr::valign":0,"ul::compact":0,"ul::type":0},eflags:{OPTIONAL_ENDTAG:1,EMPTY:2,CDATA:4,RCDATA:8,UNSAFE:16,FOLDABLE:32,SCRIPT:64,STYLE:128},ELEMENTS:{a:0,abbr:0,acronym:0,address:0,applet:16,area:2,b:0,base:18,basefont:18,bdo:0,big:0,blockquote:0,body:49,br:2,button:0,caption:0,center:0,cite:0,code:0,col:2,colgroup:1,dd:1,del:0,dfn:0,dir:0,div:0,dl:0,dt:1,em:0,fieldset:0,font:0,form:0,frame:18,frameset:16,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,head:49,hr:2,html:49,i:0,iframe:4,img:2,input:2,ins:0,isindex:18, kbd:0,label:0,legend:0,li:1,link:18,map:0,menu:0,meta:18,noframes:20,noscript:20,object:16,ol:0,optgroup:0,option:1,p:1,param:18,pre:0,q:0,s:0,samp:0,script:84,select:0,small:0,span:0,strike:0,strong:0,style:148,sub:0,sup:0,table:0,tbody:1,td:1,textarea:8,tfoot:1,th:1,thead:1,title:24,tr:1,tt:0,u:0,ul:0,"var":0},URIEFFECTS:{},LOADERTYPES:{}};"undefined"!==typeof c&&c.exports&&(b=c.exports=a);b.URI=a},function(c,b,a){a(2258);a=a(2259);a=function(){function a(b){b=(""+b).match(q);return!b?null:new l(m(b[1]), m(b[2]),m(b[3]),m(b[4]),m(b[5]),m(b[6]),m(b[7]))}function b(a){return"string"==typeof a?encodeURIComponent(a):null}function c(a,b){return"string"==typeof a?encodeURI(a).replace(b,g):null}function g(a){a=a.charCodeAt(0);return"%"+"0123456789ABCDEF".charAt(a>>4&15)+"0123456789ABCDEF".charAt(a&15)}function h(a){if(null===a)return null;a=a.replace(/(^|\/)\.(?:\/|$)/g,"$1").replace(/\/{2,}/g,"/");for(var b=n,c;(c=a.replace(b,"$1"))!=a;a=c);return a}function k(a,b){var c=a.clone(),d=b.hasScheme();d?c.setRawScheme(b.getRawScheme()): d=b.hasCredentials();d?c.setRawCredentials(b.getRawCredentials()):d=b.hasDomain();d?c.setRawDomain(b.getRawDomain()):d=b.hasPort();var e=b.getRawPath(),f=h(e);if(d)c.setPort(b.getPort()),f=f&&f.replace(s,"");else if(d=!!e){if(47!==f.charCodeAt(0))var f=h(c.getRawPath()||"").replace(s,""),g=f.lastIndexOf("/")+1,f=h((g?f.substring(0,g):"")+h(e)).replace(s,"")}else f=f&&f.replace(s,""),f!==e&&c.setRawPath(f);d?c.setRawPath(f):d=b.hasQuery();d?c.setRawQuery(b.getRawQuery()):d=b.hasFragment();d&&c.setRawFragment(b.getRawFragment()); return c}function l(a,b,c,d,f,e,g){this.scheme_=a;this.credentials_=b;this.domain_=c;this.port_=d;this.path_=f;this.query_=e;this.fragment_=g;this.paramCache_=null}function m(a){return"string"==typeof a&&0<a.length?a:null}var n=RegExp(/(\/|^)(?:[^./][^/]*|\.{2,}(?:[^./][^/]*)|\.{3,}[^/]*)\/\.\.(?:\/|$)/),s=/^(?:\.\.\/)*(?:\.\.$)?/;l.prototype.toString=function(){var a=[];null!==this.scheme_&&a.push(this.scheme_,":");null!==this.domain_&&(a.push("//"),null!==this.credentials_&&a.push(this.credentials_, "@"),a.push(this.domain_),null!==this.port_&&a.push(":",this.port_.toString()));null!==this.path_&&a.push(this.path_);null!==this.query_&&a.push("?",this.query_);null!==this.fragment_&&a.push("#",this.fragment_);return a.join("")};l.prototype.clone=function(){return new l(this.scheme_,this.credentials_,this.domain_,this.port_,this.path_,this.query_,this.fragment_)};l.prototype.getScheme=function(){return this.scheme_&&decodeURIComponent(this.scheme_).toLowerCase()};l.prototype.getRawScheme=function(){return this.scheme_}; l.prototype.setScheme=function(a){this.scheme_=c(a,r);return this};l.prototype.setRawScheme=function(a){this.scheme_=a?a:null;return this};l.prototype.hasScheme=function(){return null!==this.scheme_};l.prototype.getCredentials=function(){return this.credentials_&&decodeURIComponent(this.credentials_)};l.prototype.getRawCredentials=function(){return this.credentials_};l.prototype.setCredentials=function(a){this.credentials_=c(a,r);return this};l.prototype.setRawCredentials=function(a){this.credentials_= a?a:null;return this};l.prototype.hasCredentials=function(){return null!==this.credentials_};l.prototype.getDomain=function(){return this.domain_&&decodeURIComponent(this.domain_)};l.prototype.getRawDomain=function(){return this.domain_};l.prototype.setDomain=function(a){return this.setRawDomain(a&&encodeURIComponent(a))};l.prototype.setRawDomain=function(a){this.domain_=a?a:null;return this.setRawPath(this.path_)};l.prototype.hasDomain=function(){return null!==this.domain_};l.prototype.getPort=function(){return this.port_&& decodeURIComponent(this.port_)};l.prototype.setPort=function(a){if(a){a=Number(a);if(a!==(a&65535))throw Error("Bad port number "+a);this.port_=""+a}else this.port_=null;return this};l.prototype.hasPort=function(){return null!==this.port_};l.prototype.getPath=function(){return this.path_&&decodeURIComponent(this.path_)};l.prototype.getRawPath=function(){return this.path_};l.prototype.setPath=function(a){return this.setRawPath(c(a,t))};l.prototype.setRawPath=function(a){a?(a=String(a),this.path_=!this.domain_|| /^\//.test(a)?a:"/"+a):this.path_=null;return this};l.prototype.hasPath=function(){return null!==this.path_};l.prototype.getQuery=function(){return this.query_&&decodeURIComponent(this.query_).replace(/\+/g," ")};l.prototype.getRawQuery=function(){return this.query_};l.prototype.setQuery=function(a){this.paramCache_=null;this.query_=b(a);return this};l.prototype.setRawQuery=function(a){this.paramCache_=null;this.query_=a?a:null;return this};l.prototype.hasQuery=function(){return null!==this.query_}; l.prototype.setAllParameters=function(a){if("object"===typeof a&&!(a instanceof Array)&&(a instanceof Object||"[object Array]"!==Object.prototype.toString.call(a))){var b=[],c=-1,d;for(d in a){var f=a[d];"string"===typeof f&&(b[++c]=d,b[++c]=f)}a=b}this.paramCache_=null;for(var b=[],c="",e=0;e<a.length;)d=a[e++],f=a[e++],b.push(c,encodeURIComponent(d.toString())),c="&",f&&b.push("=",encodeURIComponent(f.toString()));this.query_=b.join("");return this};l.prototype.checkParameterCache_=function(){if(!this.paramCache_){var a= this.query_;if(a){for(var a=a.split(/[&\?]/),b=[],c=-1,d=0;d<a.length;++d){var f=a[d].match(/^([^=]*)(?:=(.*))?$/);b[++c]=decodeURIComponent(f[1]).replace(/\+/g," ");b[++c]=decodeURIComponent(f[2]||"").replace(/\+/g," ")}this.paramCache_=b}else this.paramCache_=[]}};l.prototype.setParameterValues=function(a,b){"string"===typeof b&&(b=[b]);this.checkParameterCache_();for(var c=0,d=this.paramCache_,f=[],e=0;e<d.length;e+=2)a===d[e]?c<b.length&&f.push(a,b[c++]):f.push(d[e],d[e+1]);for(;c<b.length;)f.push(a, b[c++]);this.setAllParameters(f);return this};l.prototype.removeParameter=function(a){return this.setParameterValues(a,[])};l.prototype.getAllParameters=function(){this.checkParameterCache_();return this.paramCache_.slice(0,this.paramCache_.length)};l.prototype.getParameterValues=function(a){this.checkParameterCache_();for(var b=[],c=0;c<this.paramCache_.length;c+=2)a===this.paramCache_[c]&&b.push(this.paramCache_[c+1]);return b};l.prototype.getParameterMap=function(a){this.checkParameterCache_(); a={};for(var b=0;b<this.paramCache_.length;b+=2){var c=this.paramCache_[b++],d=this.paramCache_[b++];c in a?a[c].push(d):a[c]=[d]}return a};l.prototype.getParameterValue=function(a){this.checkParameterCache_();for(var b=0;b<this.paramCache_.length;b+=2)if(a===this.paramCache_[b])return this.paramCache_[b+1];return null};l.prototype.getFragment=function(){return this.fragment_&&decodeURIComponent(this.fragment_)};l.prototype.getRawFragment=function(){return this.fragment_};l.prototype.setFragment= function(a){this.fragment_=a?encodeURIComponent(a):null;return this};l.prototype.setRawFragment=function(a){this.fragment_=a?a:null;return this};l.prototype.hasFragment=function(){return null!==this.fragment_};var q=/^(?:([^:/?#]+):)?(?:\/\/(?:([^/?#]*)@)?([^/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/,r=/[#\/\?@]/g,t=/[\#\?]/g;l.parse=a;l.create=function(a,e,h,k,m,s,n){a=new l(c(a,r),c(e,r),b(h),0<k?k.toString():null,c(m,t),null,b(n));s&&("string"===typeof s?a.setRawQuery(s.replace(/[^?&=0-9A-Za-z_\-~.%]/g, g)):a.setAllParameters(s));return a};l.resolve=k;l.collapse_dots=h;l.utils={mimeTypeOf:function(b){b=a(b);return/\.html$/.test(b.getPath())?"text/html":"application/javascript"},resolve:function(b,c){return b?k(a(b),a(c)).toString():""+c}};return l}();"undefined"!==typeof c&&c.exports&&(b=c.exports=a);b.URI=a},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c,b,a){var e=a(2258),f=a(2259),d=function(a){function b(a){if(I.hasOwnProperty(a))return I[a];var c=a.match(O);return c?String.fromCharCode(parseInt(c[1],10)):(c=a.match(N))?String.fromCharCode(parseInt(c[1], 16)):L&&D.test(a)?(L.innerHTML="&"+a+";",c=L.textContent,I[a]=c):"&"+a+";"}function c(a,d){return b(d)}function d(a){return a.replace(K,c)}function e(a){return(""+a).replace(H,"&amp;").replace(Q,"&lt;").replace(J,"&gt;").replace(E,"&#34;")}function n(a){return a.replace(S,"&amp;$1").replace(Q,"&lt;").replace(J,"&gt;")}function s(a){var b={cdata:a.cdata||a.cdata,comment:a.comment||a.comment,endDoc:a.endDoc||a.endDoc,endTag:a.endTag||a.endTag,pcdata:a.pcdata||a.pcdata,rcdata:a.rcdata||a.rcdata,startDoc:a.startDoc|| a.startDoc,startTag:a.startTag||a.startTag};return function(a,c){var d;var f=/(<\/|<\!--|<[!?]|[&<>])/g;d=a+"";if(M)d=d.split(f);else{for(var e=[],g=0,h;null!==(h=f.exec(d));)e.push(d.substring(g,h.index)),e.push(h[0]),g=h.index+h[0].length;e.push(d.substring(g));d=e}r(b,d,0,{noMoreGT:!1,noMoreEndComments:!1},c)}}function q(a,b,c,d,f){return function(){r(a,b,c,d,f)}}function r(b,c,d,f,e){try{b.startDoc&&0==d&&b.startDoc(e);for(var h,k,l,r=c.length;d<r;){var m=c[d++],s=c[d];switch(m){case "&":T.test(s)? (b.pcdata&&b.pcdata("&"+s,e,G,q(b,c,d,f,e)),d++):b.pcdata&&b.pcdata("&amp;",e,G,q(b,c,d,f,e));break;case "</":if(h=/^([-\w:]+)[^\'\"]*/.exec(s))if(h[0].length===s.length&&">"===c[d+1])d+=2,l=h[1].toLowerCase(),b.endTag&&b.endTag(l,e,G,q(b,c,d,f,e));else{var n=c,u=d,v=b,x=e,w=G,y=f,z=p(n,u);z?(v.endTag&&v.endTag(z.name,x,w,q(v,n,u,y,x)),d=z.next):d=n.length}else b.pcdata&&b.pcdata("&lt;/",e,G,q(b,c,d,f,e));break;case "<":if(h=/^([-\w:]+)\s*\/?/.exec(s))if(h[0].length===s.length&&">"===c[d+1]){d+=2; l=h[1].toLowerCase();b.startTag&&b.startTag(l,[],e,G,q(b,c,d,f,e));var A=a.ELEMENTS[l];A&R&&(d=t(c,{name:l,next:d,eflags:A},b,e,G,f))}else{var n=c,u=b,v=e,x=G,w=f,C=p(n,d);C?(u.startTag&&u.startTag(C.name,C.attrs,v,x,q(u,n,C.next,w,v)),d=C.eflags&R?t(n,C,u,v,x,w):C.next):d=n.length}else b.pcdata&&b.pcdata("&lt;",e,G,q(b,c,d,f,e));break;case "\x3c!--":if(!f.noMoreEndComments){for(k=d+1;k<r&&!(">"===c[k]&&/--$/.test(c[k-1]));k++);if(k<r){if(b.comment){var B=c.slice(d,k).join("");b.comment(B.substr(0, B.length-2),e,G,q(b,c,k+1,f,e))}d=k+1}else f.noMoreEndComments=!0}f.noMoreEndComments&&b.pcdata&&b.pcdata("&lt;!--",e,G,q(b,c,d,f,e));break;case "<!":if(/^\w/.test(s)){if(!f.noMoreGT){for(k=d+1;k<r&&">"!==c[k];k++);k<r?d=k+1:f.noMoreGT=!0}f.noMoreGT&&b.pcdata&&b.pcdata("&lt;!",e,G,q(b,c,d,f,e))}else b.pcdata&&b.pcdata("&lt;!",e,G,q(b,c,d,f,e));break;case "<?":if(!f.noMoreGT){for(k=d+1;k<r&&">"!==c[k];k++);k<r?d=k+1:f.noMoreGT=!0}f.noMoreGT&&b.pcdata&&b.pcdata("&lt;?",e,G,q(b,c,d,f,e));break;case ">":b.pcdata&& b.pcdata("&gt;",e,G,q(b,c,d,f,e));break;case "":break;default:b.pcdata&&b.pcdata(m,e,G,q(b,c,d,f,e))}}b.endDoc&&b.endDoc(e)}catch(D){if(D!==G)throw D;}}function t(b,c,d,f,e,h){var k=b.length;V.hasOwnProperty(c.name)||(V[c.name]=RegExp("^"+c.name+"(?:[\\s\\/]|$)","i"));for(var l=V[c.name],r=c.next,p=c.next+1;p<k&&!("</"===b[p-1]&&l.test(b[p]));p++);p<k&&(p-=1);k=b.slice(r,p).join("");if(c.eflags&a.eflags.CDATA)d.cdata&&d.cdata(k,f,e,q(d,b,p,h,f));else if(c.eflags&a.eflags.RCDATA)d.rcdata&&d.rcdata(n(k), f,e,q(d,b,p,h,f));else throw Error("bug");return p}function p(b,c){var f=/^([-\w:]+)/.exec(b[c]),e={};e.name=f[1].toLowerCase();e.eflags=a.ELEMENTS[e.name];for(var h=b[c].substr(f[0].length),k=c+1,r=b.length;k<r&&">"!==b[k];k++)h+=b[k];if(!(r<=k)){for(var p=[];""!==h;)if(f=U.exec(h))if(f[4]&&!f[5]||f[6]&&!f[7]){for(var f=f[4]||f[6],m=!1,h=[h,b[k++]];k<r;k++){if(m){if(">"===b[k])break}else 0<=b[k].indexOf(f)&&(m=!0);h.push(b[k])}if(r<=k)break;h=h.join("")}else{var m=f[1].toLowerCase(),t;if(f[2]){t= f[3];var s=t.charCodeAt(0);if(34===s||39===s)t=t.substr(1,t.length-2);t=d(t.replace(F,""))}else t="";p.push(m,t);h=h.substr(f[0].length)}else h=h.replace(/^[\s\S][^a-z\s]*/,"");e.attrs=p;e.next=k+1;return e}}function u(b){var c,d,f=function(a,b){d||b.push(a)};return s({startDoc:function(a){c=[];d=!1},startTag:function(f,h,k){if(!d&&a.ELEMENTS.hasOwnProperty(f)){var l=a.ELEMENTS[f];if(!(l&a.eflags.FOLDABLE)){var r=b(f,h);if(r){if("object"!==typeof r)throw Error("tagPolicy did not return object (old API?)"); if("attribs"in r)h=r.attribs;else throw Error("tagPolicy gave no attribs");var p;"tagName"in r?(p=r.tagName,r=a.ELEMENTS[p]):(p=f,r=l);if(l&a.eflags.OPTIONAL_ENDTAG){var t=c[c.length-1];t&&(t.orig===f&&(t.rep!==p||f!==p))&&k.push("</",t.rep,">")}l&a.eflags.EMPTY||c.push({orig:f,rep:p});k.push("<",p);f=0;for(t=h.length;f<t;f+=2){var s=h[f],n=h[f+1];null!==n&&void 0!==n&&k.push(" ",s,'="',e(n),'"')}k.push(">");l&a.eflags.EMPTY&&!(r&a.eflags.EMPTY)&&k.push("</",p,">")}else d=!(l&a.eflags.EMPTY)}}},endTag:function(b, f){if(d)d=!1;else if(a.ELEMENTS.hasOwnProperty(b)){var e=a.ELEMENTS[b];if(!(e&(a.eflags.EMPTY|a.eflags.FOLDABLE))){if(e&a.eflags.OPTIONAL_ENDTAG)for(e=c.length;0<=--e;){var h=c[e].orig;if(h===b)break;if(!(a.ELEMENTS[h]&a.eflags.OPTIONAL_ENDTAG))return}else for(e=c.length;0<=--e&&c[e].orig!==b;);if(!(0>e)){for(h=c.length;--h>e;){var k=c[h].rep;a.ELEMENTS[k]&a.eflags.OPTIONAL_ENDTAG||f.push("</",k,">")}e<c.length&&(b=c[e].rep);c.length=e;f.push("</",b,">")}}}},pcdata:f,rcdata:f,cdata:f,endDoc:function(a){for(;c.length;c.length--)a.push("</", c[c.length-1].rep,">")}})}function v(a,b,c,d,e){if(!e)return null;try{var g=f.parse(""+a);if(g&&(!g.hasScheme()||W.test(g.getScheme()))){var h=e(g,b,c,d);return h?h.toString():null}}catch(k){}return null}function x(a,b,c,d,f){c||a(b+" removed",{change:"removed",tagName:b});if(d!==f){var e="changed";d&&!f?e="removed":!d&&f&&(e="added");a(b+"."+c+" "+e,{change:e,tagName:b,attribName:c,oldValue:d,newValue:f})}}function w(a,b,c){b=b+"::"+c;if(a.hasOwnProperty(b))return a[b];b="*::"+c;if(a.hasOwnProperty(b))return a[b]} function y(b,c,d,f,e){for(var h=0;h<c.length;h+=2){var k=c[h],l=c[h+1],r=l,p=null,m;if((m=b+"::"+k,a.ATTRIBS.hasOwnProperty(m))||(m="*::"+k,a.ATTRIBS.hasOwnProperty(m)))p=a.ATTRIBS[m];if(null!==p)switch(p){case a.atype.NONE:break;case a.atype.SCRIPT:l=null;e&&x(e,b,k,r,l);break;case a.atype.STYLE:if("undefined"===typeof z){l=null;e&&x(e,b,k,r,l);break}var t=[];z(l,{declaration:function(b,c){var f=b.toLowerCase();C(f,c,d?function(b){return v(b,a.ueffects.SAME_DOCUMENT,a.ltypes.SANDBOXED,{TYPE:"CSS", CSS_PROP:f},d)}:null);c.length&&t.push(f+": "+c.join(" "))}});l=0<t.length?t.join(" ; "):null;e&&x(e,b,k,r,l);break;case a.atype.ID:case a.atype.IDREF:case a.atype.IDREFS:case a.atype.GLOBAL_NAME:case a.atype.LOCAL_NAME:case a.atype.CLASSES:l=f?f(l):l;e&&x(e,b,k,r,l);break;case a.atype.URI:l=v(l,w(a.URIEFFECTS,b,k),w(a.LOADERTYPES,b,k),{TYPE:"MARKUP",XML_ATTR:k,XML_TAG:b},d);e&&x(e,b,k,r,l);break;case a.atype.URI_FRAGMENT:l&&"#"===l.charAt(0)?(l=l.substring(1),l=f?f(l):l,null!==l&&void 0!==l&&(l= "#"+l)):l=null;e&&x(e,b,k,r,l);break;default:l=null,e&&x(e,b,k,r,l)}else l=null,e&&x(e,b,k,r,l);c[h+1]=l}return c}function B(b,c,d){return function(f,e){if(a.ELEMENTS[f]&a.eflags.UNSAFE)d&&x(d,f,void 0,void 0,void 0);else return{attribs:y(f,e,b,c,d)}}}function A(a,b){var c=[];u(b)(a,c);return c.join("")}var z,C;"undefined"!==typeof window&&(z=window.parseCssDeclarations,C=window.sanitizeCssProperty);var I={lt:"<",LT:"<",gt:">",GT:">",amp:"&",AMP:"&",quot:'"',apos:"'",nbsp:"\u00a0"},O=/^#(\d+)$/,N= /^#x([0-9A-Fa-f]+)$/,D=/^[A-Za-z][A-za-z0-9]+$/,L="undefined"!==typeof window&&window.document?window.document.createElement("textarea"):null,F=/\0/g,K=/&(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/g,T=/^(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/,H=/&/g,S=/&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi,Q=/[<]/g,J=/>/g,E=/\"/g,U=/^\s*([-.:\w]+)(?:\s*(=)\s*((")[^"]*("|$)|(')[^']*('|$)|(?=[a-z][-\w]*\s*=)|[^"'\s]*))?/i,M=3==="a,b".split(/(,)/).length,R=a.eflags.CDATA|a.eflags.RCDATA,G={},V={},W=/^(?:https?|mailto)$/i, P={};P.escapeAttrib=P.escapeAttrib=e;P.makeHtmlSanitizer=P.makeHtmlSanitizer=u;P.makeSaxParser=P.makeSaxParser=s;P.makeTagPolicy=P.makeTagPolicy=B;P.normalizeRCData=P.normalizeRCData=n;P.sanitize=P.sanitize=function(a,b,c,d){b=B(b,c,d);return A(a,b)};P.sanitizeAttribs=P.sanitizeAttribs=y;P.sanitizeWithPolicy=P.sanitizeWithPolicy=A;P.unescapeEntities=P.unescapeEntities=d;return P}(e);a={};a.escapeAttrib=d.escapeAttrib;a.makeHtmlSanitizer=d.makeHtmlSanitizer;a.makeSaxParser=d.makeSaxParser;a.makeTagPolicy= d.makeTagPolicy;a.normalizeRCData=d.normalizeRCData;a.sanitizeAttribs=d.sanitizeAttribs;a.sanitizeWithPolicy=d.sanitizeWithPolicy;a.unescapeEntities=d.unescapeEntities;a.escape=d.escapeAttrib;a.sanitize=function(a,b,c,f){"string"===typeof a&&(a=a.replace(/<([a-zA-Z]+)([^>]*)\/>/g,"<$1$2></$1>"));return a?d.sanitize(a,b,c,f):a};"undefined"!==typeof c&&c.exports&&(b=c.exports=a);b.Sanitizer=a},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(c, b,a){var e=a(761);YUI.add("squarespace-comment-data",function(a){a.namespace("Squarespace");a.Squarespace.CommentData=Class.create({initialize:function(a){if(void 0===a)throw Error("You must provide a configuration object.");if(void 0===a.target)throw Error("You must provide a target id.");if(void 0===a.targetType)throw Error("You must provide a target type.");this.settings=a.settings||{approvalRequired:!1,allowAnon:!0,threaded:!0};this.formatter=a.formatter||function(a){return a};this.page=1;this.data= {comments:[]};this.visibleComments=this.topLevelComments=0;this.totalComments=a.publicCommentCount||0;this.commentsPerPage=50;this.target=a.target;this.targetType=a.targetType;this.idToIndex={};this.comments=[];this.likeMap={};this.flagMap={};this.formatted={};this.currentThreadRoot="";this.formattedThread={};this.pageIntervals=[]},useSecure:function(){return window.SQUARESPACE_LOGIN&&window.SQUARESPACE_LOGIN.isLoggedIn()},getCommentById:function(a){return this.comments[this.idToIndex[a]]},removeCommentById:function(b){b= this.idToIndex[b];a.Lang.isUndefined(b)||(this.comments.splice(b,1),this.calculatePagination())},removeCommentsByIds:function(b){b.forEach(function(b){b=this.idToIndex[b];a.Lang.isUndefined(b)||(this.comments.splice(b,1),this.visibleComments-=1,this.totalComments-=1)},this);this.calculatePagination()},getFormattedPage:function(a){return(a=this.pageIntervals[a-1])?Array.prototype.slice.apply(this.comments,a):null},fullBookkeeping:function(a){var b=0,c={};this.comments=[];this.pageIntervals=[];this.idToIndex= {};for(b=0;b<a.comments.length;b++)c=a.comments[b],this.idToIndex[c.id]=b,this.comments[b]=c;this.pageIntervals.push([0,void 0]);this.flagMap=a.flagMap;this.likeMap=a.likeMap;this.commentSettings=a.commentSettings;this.visibleComments=a.visibleComments;this.topLevelComments=this.formatted.topLevelComments||this.topLevelComments;this.totalComments=a.totalComments?a.totalComments:this.totalComments;this.reformat();this.topLevelComments=a.topLevelComments;this.numLikes=a.numLikes;this.numPages=Math.ceil(this.topLevelComments/ this.commentsPerPage)},addCommentData:function(a){this.comments.splice((this.idToIndex[a.parentId]||-1)+1,0,a);this.calculatePagination()},calculatePagination:function(){var a=0,b,c;this.idToIndex={};this.pageIntervals=[[0,void 0]];for(c=0;c<this.comments.length;c++)b=this.comments[c],this.idToIndex[b.id]=c,b.parentId||(a+=1,50<a&&(b=this.pageIntervals[this.pageIntervals.length-1],b[1]=a-1,this.pageIntervals.push([b[1],void 0]),a=0))},appendBookkeeping:function(b){var c=0,e={};this.pageIntervals[this.pageIntervals.length- 1][1]=this.comments.length;for(c=0;c<b.comments.length;c++)e=b.comments[c],this.idToIndex[e.id]=this.comments.length+1,this.comments.push(e);this.pageIntervals.push([this.pageIntervals[this.pageIntervals.length-1][1],void 0]);this.likeMap=a.merge(this.likeMap,b.likeMap);this.flagMap=a.merge(this.flagMap,b.flagMap);this.visibleComments+=b.visibleComments;this.reformat()},reformat:function(){this.formatted=this.formatter(this.comments,this.likeMap,this.flagMap)},like:function(b,c){a.Data.post({url:"/api/comment/LikeComment", secure:!0,data:{commentId:b.id},success:function(a){var e=this.getCommentById(b.id);e&&(e.likeCount+=1,this.reformat());(b.success||noop).call(c||this,a)},failure:function(a){(b.failure||noop).call(c||this,a)}},this)},unlike:function(b,c){a.Data.post({url:"/api/comment/UnlikeComment",secure:!0,data:{commentId:b.id},success:function(a){var e=this.getCommentById(b.id);e&&(e.likeCount=Math.max(e.likeCount-1,0),this.reformat());(b.success||noop).call(c||this,a)},failure:b.failure},this)},flag:function(b, c){a.Data.post({url:"/api/comment/FlagComment",secure:!0,data:{commentId:b.id},success:function(a){var e=this.getCommentById(b.id);e&&(e.flagCount+=1,this.reformat());(b.success||noop).call(c||this,a)},failure:function(a){(b.failure||noop).call(c||this,a)}},this)},_delete:function(b,c){a.Data.post({url:"/api/comment/admin/DeleteComments",secure:!0,data:{markAsSpam:b.spam,comments:a.Lang.isArray(b.comments)?b.comments:[b.comments]},success:function(a){b.comments.forEach(function(a){this.removeCommentById(a.id)}, this);this.visibleComments-=b.comments.length;this.totalComments-=b.comments.length;(b.success||noop).call(c||this,a)},failure:b.failure?a.bind(b.failure,c||this):void 0},this)},approve:function(b,c){a.Data.post({url:"/api/comment/admin/ApproveComments",secure:!0,data:{comments:a.Lang.isArray(b.comments)?b.comments:[b.comments]},success:function(a){b.comments.forEach(function(a){if(a=this.getCommentById(a.id))a.status=e.APPROVED},this);this.totalComments+=1;(b.success||noop).call(c||this,a)},failure:b.failure? a.bind(b.failure,c||this):void 0},this)},unflag:function(b,c){a.Data.post({url:"/api/comment/UnflagComment",secure:!0,data:{commentId:b.id},success:function(a){var e=this.getCommentById(b.id);e&&(e.flagCount=Math.max(e.flagCount-1,0),this.reformat());(b.success||noop).call(c||this,a)},failure:function(a){(b.failure||noop).call(c||this,a)}},this)},post:function(b,c){a.Data.post({url:"/api/comment/CreateComment",secure:!!Static.SQUARESPACE_CONTEXT.authenticatedAccount,data:{targetId:this.target,targetType:this.targetType, body:b.body,replyToId:b.replyTo,authorName:b.name||"",authorEmail:b.email||"",authorUrl:b.authorUrl||""},success:function(a){a.comment.status===e.APPROVED&&(this.addCommentData(a.comment),this.visibleComments+=1,this.totalComments+=1,b.replyTo||(this.topLevelComments+=1),this.reformat());(b.success||noop).call(c||this,a)},failure:b.failure?a.bind(b.failure,c||this):void 0},this)},getPage:function(a,b,c){b<=this.numPages&&this.get({sortBy:a.order,page:b,success:a.success,failure:a.failure},c)},getSince:function(a, b,c){this.get({since:b,success:a.success,failure:a.failure},c)},getThread:function(b,c){a.Data.get({url:"/api/comment/GetThread",secure:this.useSecure(),data:{sortBy:b.order,commentId:b.commentId},success:function(e){this.currentThreadRoot=b.commentId;var k=e.comments[0].comment.depth;e.comments=a.Array.map(e.comments,function(a){return a.comment});e.comments.forEach(function(a){a.depth-=k});this.formattedThread=this.formatter(e.comments,{},{});a.Lang.isFunction(b.success)&&b.success.call(c||this, e)},failure:function(e){a.Lang.isFunction(b.failure)&&b.failure.call(c||this,e)}},this)},get:function(b,c){a.Data.get({url:"/api/comment/GetComments",secure:this.useSecure(),data:{targetId:this.target,targetType:this.targetType,since:b.since||"",page:b.page,sortBy:b.order},success:function(a){this.page=b.page;1>=b.page?this.fullBookkeeping(a):1<b.page&&this.appendBookkeeping(a);b.success&&b.success.call(c||this,a)},failure:b.failure},this)},getLikesAndFlags:function(b,c){var e=a.Array.map(this.comments, function(a){return a.id});a.Data.get({url:"/api/comment/GetLikesFlags",secure:this.useSecure(),data:{ids:e},success:function(e){b.success&&a.Lang.isFunction(b.success)&&b.success.call(c||this,e)},failure:function(e){b.failure&&a.Lang.isFunction(b.failure)&&b.failure.call(c||this,e)}})}})},"1.0",{requires:["squarespace-util"]})},function(c,b,a){var e=a(1),f=a(20),d=a(162),g=a(283),h=a(925),k=a(527),l=a(761),m=a(926),n=a(2760);YUI.add("squarespace-comments",function(a){a.namespace("Squarespace");a.Squarespace.Comments= Class.create({initialize:function(b){this.events=[];this.settings={likesAllowed:b.likesAllowed,flagsAllowed:b.flagsAllowed,threaded:b.threaded,approvalRequired:b.approvalRequired,allowAnon:b.allowAnon,avatarsHidden:!b.avatarsOn,readOnly:b.readOnly};this.commentData=new a.Squarespace.CommentData({target:b.identifier,targetType:b.type,publicCommentCount:b.publicCommentCount,settings:this.settings,formatter:a.bind(this.formatData,this)});this.targetId=b.identifier;this.params=b||{design:{}};this.replyCompleteEvents= {};this.threadState=!1;this.lastSortTime=new Date;this.lastHashChangeTime=new Date;this.PaginationModes={EXTEND:1,PAGE:2};this.containerEl=a.one(this.params.containerEl);this.params.paginationMode=this.PaginationModes.EXTEND;this.type=g.COMMENT;this.currentPage=1;this.maxComments=50;this.sortOrderLookup=[null];this.sortOrderLookup.push(e("Oldest First"),e("Newest First"),e("Most Liked"),e("Least Liked"));this.sortOrder=this.params.sortType;this.commentsEl=a.Node.create('<div class="comments-content"><div class="comment-list"></div></div>'); this.settings.readOnly&&this.commentsEl.addClass("read-only");this.commentsEl.appendTo(this.containerEl);this.loadMoreNode=a.Node.create(e('<div class="load-more"><div class="view-more-btn">Load More Comments</div></div>'));this.fullViewNode=a.Node.create('<div class="full-view-btn">View full comment thread</div>');this.history=new a.HistoryHash;this.events.push(this.commentsEl.delegate("click",this.onReplyToggleClick,".reply",this),this.commentsEl.delegate("click",this.onLikeClick,".comment:not(.liked):not(.read-only) .like", this),this.commentsEl.delegate("click",this.onUnlikeClick,".comment.liked:not(.read-only) .like",this),this.commentsEl.delegate("click",this.onFlagClick,".comment:not(.flagged):not(.read-only) .flag",this),this.commentsEl.delegate("click",this.onUnflagClick,".comment.flagged:not(.read-only) .flag",this),this.commentsEl.delegate("click",this.onApproveClick,".comment.unmoderated:not(.read-only) .approve",this),this.commentsEl.delegate("click",this.onDeleteClick,".comment:not(.read-only) .delete",this), this.commentsEl.delegate("click",this.replyBtnOnClick,".reply-area-wrapper .comment-btn:not(.read-only)",this),this.commentsEl.delegate("click",this.togglePreview,".reply-area-wrapper .preview-comment",this),this.commentsEl.delegate("click",this.showSubscribe,".subscribe",this),this.commentsEl.delegate("click",this.unsubscribe,".unsubscribe",this),this.history.on("commentIdChange",this.commentIdHashOnChange,this),this.history.on("commentIdRemove",this.commentIdHashOnRemove,this),this.containerEl.delegate("click", function(){var a,b,c;return function(d){SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,allowAnonymous:this.settings.allowAnon,overlayOpacity:0.5});d=function(){this.onLoading();this.commentData.visibleComments=0;this.retrieveComments({onSuccess:function(a){this.fullDataRender(a)},page:1,order:this.sortOrder},this);a.detach();c.detach()};a=SQUARESPACE_LOGIN.once("cancel",function(){b.detach();c.detach()},this);b=SQUARESPACE_LOGIN.once("login",d,this);c=SQUARESPACE_LOGIN.once("guestLogin", d,this);SQUARESPACE_LOGIN.show()}}(),".squarespace-comment-login",this),SQUARESPACE_LOGIN.on("login",function(){this.updateLikedFlaggedState();this.refreshCommentPostButtons();this.moderationMode=this.userHasAccessPermission(d.CONFIG_ACTIVITY_COMMENTS)},this),SQUARESPACE_LOGIN.on("logout",function(){this.updateLikedFlaggedState();this.refreshCommentPostButtons();this.refreshSubscribeControl();this.moderationMode=!1},this),this.containerEl.delegate("click",function(a){SQUARESPACE_LOGIN.onLogoutClick()}, ".squarespace-comment-logout",this),this.containerEl.delegate("focus",function(){this.set("text","");this.setAttribute("data-edited",!0)},".comment-input"),this.containerEl.delegate("blur",function(){""===this.get("value")&&this.setAttribute("data-edited",!1)},".comment-input"),this.containerEl.delegate("focus",function(a){a.target.setAttribute("data-edited",!0)},".new-comment-area textArea",this),this.containerEl.delegate("click",this.extendComments,".view-more-btn",this),this.containerEl.delegate("click", this.fullViewOnClick,".full-view-btn",this),this.containerEl.delegate("click",this.commentBtnOnClick,".top-level-comment-area .comment-btn:not(.read-only)",this),this.containerEl.delegate("click",this.togglePreview,".top-level-comment-area .preview-comment",this),this.containerEl.delegate("change",function(a){this.sort(a.target.get("value"))},".hidden-ordering",this));a.Cookie.remove("displayName",{path:"/"});this.subscribeDialogParams={name:"subscribe",style:"flyout",flyoutPointerDirection:"top", width:320,position:"center",closeable:!0,overlay:0.5,top:200,discardChangesConfirmation:!1,title:e("Subscribe by Email"),primaryTabs:[{title:e("Subscribe by Email"),icon:"/universal/images-v6/standard/icon_invites_24_light.png",fields:[{type:"text",required:!0,name:"email",title:e("Email"),fieldStyle:"normal",titleStyle:"inline",submitOnEnter:!0,style:"major"},{ctor:a.Squarespace.DialogFields.Description,config:{text:e("Subscribe to this comment thread by email."),padding:[0,0]}}]}],buttons:[{type:"cancel", title:e("Cancel")},{type:"saveAndClose",title:e("Submit")}]}},destroy:function(){this.events.forEach(function(a){a.detach()})},userHasAccessPermission:function(b){return!a.Object.getValue(Static,["SQUARESPACE_CONTEXT","accessPermissions"])?!1:0<=a.Array.indexOf(Static.SQUARESPACE_CONTEXT.accessPermissions,b)},doAfterLogin:function(a,b,c){var d,e,f;e=a.once("login",function(){b.call(this);f.detach();d.detach()},c);f=a.once("guestLogin",function(){e.detach();d.detach()});d=a.once("cancel",function(){e.detach(); f.detach()})},doAfterGuestLogin:function(a,b,c){var d,e,f;e=a.once("guestLogin",function(){b.call(this);f.detach();d.detach()},c);f=a.once("login",function(){e.detach();d.detach()});d=a.once("cancel",function(){e.detach();f.detach()})},fullViewOnClick:function(){this.history.addValue("commentId",null)},updateTopLevelButton:function(){var b=a.one(".top-level-comment-area .comment-btn"),c=this.renderToFragment({newCommentAreaTop:{authenticatedAccount:null===SQUARESPACE_LOGIN.account?void 0:SQUARESPACE_LOGIN.account}, comments:[{}]}).one(".top-level-comment-area .comment-btn");b&&(b.ancestor(".comment-btn-wrapper").append(c),b.remove(!0))},updateReplyAreaButtons:function(){var a=this.renderToFragment({comments:[{authenticatedAccount:SQUARESPACE_LOGIN.account}]}).one(".reply-area-wrapper .comment-btn");a&&this.commentsEl.all(".reply-area-wrapper .comment-btn").each(function(b){b.insert(a.cloneNode(!0),"after");b.remove(!0)})},refreshCommentPostButtons:function(){this.updateTopLevelButton();this.updateReplyAreaButtons()}, refreshSubscribeControl:function(){SQUARESPACE_LOGIN.account||(Static.SQUARESPACE_CONTEXT.subscribed=!1);var b,c=this.renderToFragment(this.scatterData({subscribed:Static.SQUARESPACE_CONTEXT.subscribed,comments:[{}]})).one(".subscribe-control");c&&(b=a.one(".subscribe-control"),b.insert(c,"after"),b.remove(!0))},generatePreview:function(b){var c=a.Squarespace.Escaping.escapeForHtml(b.get("value")),d={comments:[{}]},f=null,g=null,f=d.comments[0];b.ancestor(".reply-area-wrapper");var h=!b.ancestor(".reply-area-wrapper"), k;h?b=0:(k=a.one('.comment[data-commentId="'+b.ancestor(".reply-area-wrapper").getAttribute("data-commentId")+'"]'),b=k.hasAttribute("data-depth")?parseInt(k.getAttribute("data-depth"),10)+1:1);f.body=n.sanitize(a.Squarespace.Lang.markdownToHTML(c));f.memberAccount=a.clone(SQUARESPACE_LOGIN.account);f.authorName=(SQUARESPACE_LOGIN.account?SQUARESPACE_LOGIN.account.displayName:a.Cookie.get("displayName"))||e("Not Logged In");f.addedOn=(new Date).getTime();f.depth=b;g=this.renderToFragment(this.scatterData(d)); f=g.one(".comment");f.addClass("comment-preview");h?f.addClass("top-level"):(f.setAttribute("data-previewId",k.getAttribute("data-commentId")),f.setAttribute("data-replyTo",k.getAttribute("data-commentId")));return g},replyBtnOnClick:function(b){var c=b.target.ancestor(".reply-area-wrapper"),d=c.getAttribute("data-commentId"),e=a.one('.comment[data-commentId="'+d+'"]'),d=c.one("textArea"),f=d.get("value");""===f.trim()?this.showEmptyText():(e=this.injectReply(f,e),this.replyTo(c.getAttribute("data-commentId"), f,e,d));b.stopImmediatePropagation()},subscribe:function(b){a.Data.post({url:"/api/comment/Subscribe",secure:!0,data:{targetId:this.targetId},success:function(){Static.SQUARESPACE_CONTEXT.subscribed=!0;this.refreshSubscribeControl();new a.Squarespace.Widgets.Information({"strings.title":e("Subscribed"),"strings.message":e("Successfully subscribed")})},failure:function(){SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5});this.doAfterLogin(SQUARESPACE_LOGIN, function(){this.subscribe(b)},this);SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Subscribe"),"Subscribe",!1,["squarespace"])}},this)},unsubscribe:function(b){a.Data.post({url:"/api/comment/Unsubscribe",secure:!0,data:{targetId:this.targetId},success:function(){Static.SQUARESPACE_CONTEXT.subscribed=!1;this.refreshSubscribeControl();new a.Squarespace.Widgets.Information({"strings.title":e("Unsubscribed"),"strings.message":e("Successfully unsubscribed")})},failure:function(a){a.loginRequired&&(SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1, reloadAfterLogin:!1,overlayOpacity:0.5}),this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.unsubscribe(b)},this),SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Unsubscribe"),"Unsubscribe",!1))}},this)},showSubscribe:function(b){(new a.Squarespace.Widgets.Confirmation({"strings.confirm":e("Subscribe"),"strings.title":e("Subscribe to Thread"),"strings.message":e("Are you sure you wish to subscribe to this comment thread?You will receive updates via the email on file in your profile.")})).on("confirm", this.subscribe,this)},togglePreview:function(a){var b=a.target.ancestor(".reply-area-wrapper"),b=b?b.one("textArea"):a.target.ancestor(".top-level-comment-area").one("textArea");""!==b.get("value")&&("open"===a.target.getAttribute("data-state")?(a.target.setAttribute("data-state","closed"),this.hidePreview(b)):(a.target.setAttribute("data-state","open"),this.showPreview(b)))},showPreview:function(b){if(b){var c=this.generatePreview(b).one(".comment"),d=b.ancestor(".reply-area-wrapper"),e=b.ancestor(".input"), f=!d,g;c.wrap('<div class="new comment-preview-wrapper closed"></div>');g=c.ancestor(".comment-preview-wrapper");f?(g.addClass("top-level"),a.one(".comment-list").prepend(g)):(d.insert(g,"after"),g.setAttribute("data-commentId",d.getAttribute("data-commentId")));b.ancestor(".new-comment-area").one(".preview-comment").set("innerHTML","Edit");e.setStyle("height",e.get("offsetHeight"));b=new a.Anim({node:e,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:0}});b.on("start",function(){this._node.setStyle("overflow", "hidden")});b.run();c=new a.Anim({node:g,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:c.get("offsetHeight")+parseInt(c.getComputedStyle("paddingBottom"),10)+parseInt(c.getComputedStyle("marginBottom"),10)}});c.on("end",function(){this._node.addClass("open")});c.run()}},hideAllPreviews:function(){a.all(".comment-preview-wrapper:not(.top-level)").each(function(b){b=new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:0}});b.on("end",function(){this._node.remove(!0)});b.run()}, this);a.all('.preview-comment[data-state="open"]:not(.top-level-preview-btn)').each(function(a){a.setAttribute("data-state","closed");a.set("innerHTML","Preview")},this)},hidePreview:function(b){if(b){var c=b.ancestor(".reply-area-wrapper"),c=c?a.one('.comment-preview[data-previewId="'+c.getAttribute("data-commentId")+'"]'):a.one(".comment-preview.top-level");b.ancestor(".new-comment-area").one(".preview-comment").set("innerHTML","Preview");b=new a.Anim({node:b.ancestor(".input"),duration:0.3,easing:a.Easing.easeOutStrong, to:{height:b.get("offsetHeight")}});b.on("end",function(){this._node.setStyle("overflow","visible")});b.run();c&&(b=c.ancestor(".comment-preview-wrapper"),b=new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:0}}),b.on("start",function(){this._node.removeClass("open");this._node.addClass("closed")}),b.on("end",function(){this._node.remove(!0)}),b.run())}},getTemplateData:function(b,c){a.Data.get({url:"/api/template/GetTemplateSchema",data:{type:g.COMMENTS,componentType:"widget"}, success:function(c){this._template=new a.JSONTemplate.Template(c.html);b.call(this)},failure:c},this)},updateLikedFlaggedState:function(){(this.settings.flagsAllowed||this.settings.likesAllowed)&&this.commentData.getLikesAndFlags({success:function(b){a.one(".comment-list").all(".comment").each(function(a){var c=a.getAttribute("data-commentId");this.settings.flagsAllowed&&(b.flagMap[c]?a.addClass("flagged"):a.removeClass("flagged"));this.settings.likesAllowed&&(b.likeMap[c]?a.addClass("liked"):a.removeClass("liked"))}, this)}},this)},create:function(){this.userHasAccessPermission(d.CONFIG_ACTIVITY_COMMENTS)&&(this.moderationMode=!0);this.getTemplateData(function(){var b=this.history.get("commentId");a.Lang.isUndefined(b)?(this.onLoading(),this.retrieveComments({onSuccess:function(a){this.fullDataRender(a)},page:1,order:this.sortOrder})):(this.onLoading(),this.retrieveThread({onSuccess:this.threadRender,onFailure:function(a){this.onLoading();this.retrieveComments({onSuccess:function(a){this.fullDataRender(a)},page:1, order:this.sortOrder})},order:this.sortOrder,commentId:b}))},function(){})},updateCommentCounts:function(){var b=this.renderToFragment({visibleComments:this.commentData.visibleComments,totalComments:this.commentData.totalComments,comments:[]});0===this.commentData.visibleComments?this.containerEl.addClass("empty"):this.containerEl.removeClass("empty");a.one(".comment-count").set("innerHTML",b.one(".comment-count").get("innerHTML"))},truncateAt:function(a,b){if(!a)return"";if(void 0===b)return a;var c= a.split(" ").slice(0,b).join(" ");return c+(c.length>b?"."===c.substr(c.length-1)?"..":"...":"")},formatAccountData:function(b){return{userAvatarUrl:(b.avatarAssetUrl?b.avatarAssetUrl:"/universal/images-v6/default-avatar.png")+"?format=50w",userHref:b.websiteUrl?"http://"+a.Squarespace.Escaping.escapeForHtml(b.websiteUrl):"",userHtml:b.websiteUrl||"",userName:a.Escape.html(b.displayName||""),userBio:this.truncateAt(a.Squarespace.Escaping.escapeForHtml(b.bio,60))||""}},buildInfoPane:function(b){var c= this.formatAccountData(b),d=a.Node.create('<div class="squarespace-user-info"></div>'),e=a.Node.create('<div class="user-info-header"></div>'),f=a.Node.create('<div class="avatar"><img src="'+c.userAvatarUrl+'" /></div>'),g=a.Lang.sub('<div class="info"><div class="name">{userName}</div><a class="website" href="{userHref}">{userHtml}</a></div>',c),g=a.Node.create(g),c=a.Node.create('<div class="user-info-body"><p>'+c.userBio+"</p></div>"),h=a.Node.create('<div class="user-social-opts"><div class="social-leftcol"></div><div class="social-rightcol"></div><div class="clearfix"></div></div>'); e.append(f).append(g);d.append(e).append(c).append(h);var k=d.one(".social-leftcol"),l=d.one(".social-rightcol"),m=function(){var a=function(a,b){return function(b){return"http://"+a+".com/"+b}};return{facebook:a("facebook"),twitter:a("twitter"),foursquare:function(a){return null===/[a-zA-Z]/.exec(a)?"http://www.foursquare.com/user/"+a:"http://www.foursquare.com/"+a}}}();b.socialOptions&&a.Array.each(b.socialOptions,function(b,c){var d=b.type,e=m[d](b.username),d=a.Node.create('<div class="social-widget"><a href="'+ e+'"><img class="social-icon" src="/universal/images-v6/'+("foursquare"===d?"member/icon-foursquare-small.png":"social/"+d+"_16.png")+'" /></a><a href="'+e+'" class="social-name">'+d+"</a></div>");(0===c%2?k:l).append(d)});return d},showClickOverlay:function(){var b=a.one(document),c=b.get("winHeight"),b=b.get("winWidth");this.overlayEl=a.Node.create('<div class="user-profile-overlay"></div>');this.overlayEl.setStyles({position:"fixed",background:"#000",height:c+"px",width:b+"px",opacity:"0",top:"0px", left:"0px",zIndex:999});a.one(a.config.doc.body).append(this.overlayEl);a.on("click",this.hideUserProfileFlyout,this.overlayEl,this)},showUserProfileFlyout:function(b){if(!b.target.hasClass("squarespace-comment-user-flyout")&&!b.target.ancestor(".squarespace-comment-user-flyout")&&!this.flyoutOpen){var c=b.target.ancestor(".comment").getAttribute("data-commentid"),c=this.commentData.getCommentById(c).memberAccount;if(!c)return;var d=a.Node.create('<div class="squarespace-comment-user-flyout"></div>'); d.append(this.buildInfoPane(c));d.append(e('<div class="squarespace-user-activity"><div class="squarespace-activity-header"><div class="title">Activity"</div><div class="description">Comments and likes across the Squarespace platform</div></div><div class="feed"></div></div>'));d.append('<div class="squarespace-comment-user-clearfix"></div>');a.one(document.body).append(d);d.setStyles({position:"fixed",left:"50%",top:"50%",opacity:0,zIndex:1E3,transform:"scale(.95)"});d.setStyles({marginTop:-(parseInt(d.get("offsetHeight"), 10)/2),marginLeft:-(parseInt(d.get("offsetWidth"),10)/2)});d.transition({WebkitTransform:{duration:0.3,easing:"ease-out",value:"scale(1)"},opacity:{duration:0.3,easing:"ease-out",value:1}})}this.flyoutOpen=!0;this.showClickOverlay();b.stopImmediatePropagation()},hideUserProfileFlyout:function(b){if(this.flyoutOpen){var c=a.one(".squarespace-comment-user-flyout");c&&c.transition({WebkitTransform:{duration:0.3,easing:"ease-out",value:"scale(1.08)"},opacity:{duration:0.4,easing:"ease-out",value:0},on:{end:a.bind(function(){c.remove(!0); b.target.remove(!0);this.flyoutOpen=!1},this)}})}},getThreadNodes:function(b,c){var d=b.getAttribute("data-commentId");c.push(b);a.all('.comment[data-replyTo="'+d+'"]').each(function(a){this.getThreadNodes(a,c)},this)},actualDelete:function(b,c,d){var f=b.target.ancestor(".comment"),g=f.getAttribute("data-commentId"),h,k,l=this.lastSortTime,m=this.lastHashChangeTime;this.commentData._delete({comments:[g],spam:c,success:function(b){l===this.lastSortTime&&m===this.lastHashChangeTime&&(h=a.Node.create('<div class="delete-anim-wrapper"></div>'), f.insert(h,"after"),d.forEach(function(b){h.append(b);(b=a.one('.reply-area-wrapper[data-commentId="'+b.getAttribute("data-commentId")+'"]'))&&b.remove(!0)}),k=new a.Anim({node:h,duration:0.5,easing:a.Easing.easeOutStrong,to:{height:0}}),k.on("end",function(){h.remove(!0);1<d.length&&this.commentData.removeCommentsByIds(d.map(function(a){return a.getAttribute("data-commentId")}).filter(function(a){return a!==g}));this.updateCommentCounts()},this),k.run())},failure:function(f){f.loginRequired?(SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1, reloadAfterLogin:!1,overlayOpacity:0.5}),this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.actaulDelete(b,c,d)},this),SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Delete Comments"),e("Delete Comments"),!1)):f.authorizationFail&&new a.Squarespace.Widgets.Alert({"strings.title":e("Authorization Failure"),"strings.message":e("You are not allowed to perform that action.")})}},this)},onDeleteClick:function(b){var c,d=b.target.ancestor(".comment"),g=function(){var a=[];this.getThreadNodes(d,a);return a}.call(this), h=function(){g.forEach(function(b){b.hasClass("unmoderated")?b.removeClass("pending-delete"):(b=new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{opacity:1}}),b.on("end",function(){this._node.removeClass("pending-delete")}),b.run())})};g.forEach(function(b){b.hasClass("unmoderated")?b.addClass("pending-delete"):(b=new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{opacity:0.5}}),b.on("end",function(){this._node.addClass("pending-delete")}),b.run())});c=new a.Squarespace.Widgets.Confirmation({style:a.Squarespace.Widgets.Confirmation.TYPE.CONFIRM_OR_REJECT, "strings.reject":e("Delete"),"strings.confirm":e("Delete & Report Spam"),"strings.title":1===g.length?e("Delete Comment"):f(e("Delete {sub1} Comments"),{sub1:g.length}),"strings.message":1<g.length?e("Are you sure you wish to delete these comments?"):e("Are you sure you wish to delete this comment?")});c.on("cancel",function(){h()},this);c.on("reject",function(){h();this.actualDelete(b,!1,g)},this);c.on("confirm",function(){h();this.actualDelete(b,!0,g)},this)},onApproveClick:function(a){var b=a.target.ancestor(".comment"); this.approve(b.getAttribute("data-commentId"),b);a.stopImmediatePropagation()},approve:function(a,b){b.removeClass("unmoderated");this.commentData.approve({comments:[a],success:function(a){this.updateCommentCounts()},failure:function(c){c.loginRequired&&(b.addClass("unmoderated"),SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5}),this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.approve(a,b)},this),SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Approve Comments"), e("Approve Comments"),!1))}},this)},onUnlikeClick:function(a){var b=a.target.ancestor(".comment");this.unlike(b.getAttribute("data-commentId"),b);a.stopImmediatePropagation()},unlike:function(a,b){var c=b.one(".likes");b.removeClass("liked");this.commentData.unlike({id:a,success:function(){if(c){var b={comments:[{likesAllowed:{likeCount:this.commentData.getCommentById(a).likeCount}}]},b=this.renderToFragment(this.scatterData(b)).one(".likes");c.replace(b)}},failure:function(c){b.addClass("liked"); c.loginRequired&&(SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5}),this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.unlike(a,b)},this),SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Dislike Comment"),e("Dislike Comment"),!1))}},this)},onFlagClick:function(b){(new a.Squarespace.Widgets.Confirmation({"strings.title":e("Flag Comment"),"strings.message":e("Are you sure you wish to flag this comment as inappropriate?")})).on("confirm",function(){var a=b.target.ancestor(".comment"); this.flag(a.getAttribute("data-commentId"),a)},this);b.stopImmediatePropagation()},flag:function(b,c){c.addClass("flagged");this.commentData.flag({id:b,success:function(){},failure:function(d){c.removeClass("flagged");if(d.loginRequired){SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5});var f;this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.flag(b,c);f.detach()},this);f=SQUARESPACE_LOGIN.once("cancel",function(){c.removeClass("flagged")},this);SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Flag Comment"), e("Flag Comment"),!1)}else d.error&&new a.Squarespace.Widgets.Alert({"strings.title":e("Failed to Flag Comment"),"strings.message":d.error})}},this)},onUnflagClick:function(a){var b=a.target.ancestor(".comment");this.unflag(b.getAttribute("data-commentId"),b);a.stopImmediatePropagation()},unflag:function(a,b){b.removeClass("flagged");this.commentData.unflag({id:a,success:function(){},failure:function(c){b.addClass("flagged");c.loginRequired&&(SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1, opacity:0.5}),this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.unflag(a,b)},this),SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Unflag Comment"),e("Unflag Comment"),!1))}},this)},onLikeClick:function(a){var b=a.target.ancestor(".comment");this.like(b.getAttribute("data-commentId"),b);a.stopImmediatePropagation()},like:function(b,c){var d=c.one(".likes"),f=c.getAttribute("data-commentid");c.addClass("liked");this.commentData.like({id:b,success:function(){if(d&&!a.Lang.isNull(c._node)){var b={comments:[{likesAllowed:{likeCount:this.commentData.getCommentById(f).likeCount}}]}, b=this.renderToFragment(this.scatterData(b)).one(".likes");d.replace(b)}},failure:function(d){c.removeClass("liked");d.loginRequired?(SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5}),this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.like(b,c)},this),SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Like Comment"),e("Like Comment"),!1)):d.error&&new a.Squarespace.Widgets.Alert({"strings.title":e("Failed to Like Comment"),"strings.message":d.error})}},this)}, addLoadMoreControls:function(b){(b=a.one(".load-more"))&&b.remove(!0);!this.threadState&&this.commentData.page<this.commentData.numPages&&this.containerEl.append(this.loadMoreNode.cloneNode(!0))},addFullViewControls:function(b){(b=a.one(".full-view-btn"))&&b.remove(!0);this.threadState&&this.containerEl.one(".comment-list").insert(this.fullViewNode.cloneNode(!0),"before")},onReplyToggleClick:function(b){var c=b.target.ancestor(".comment"),d=c.getAttribute("data-commentid"),e=a.one('.reply-area-wrapper[data-commentid="'+ d+'"]'),f=a.one(a.config.doc.body),g,h,k=a.bind(function(b,c){b&&(b.setStyles({overflow:"hidden",height:b.get("offsetHeight")}),b.one(".input").setStyle("height","auto"),a.one('.comment[data-commentid="'+b.getAttribute("data-commentId")+'"]').fire("reply-close"),g=new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:0}}),g.on("end",function(){},this),g.run())},this),l=a.bind(function(b){if(b){var d,e;e=b.one(".new-comment-area").cloneNode(!0);e.setStyles({visibility:"hidden",display:"block", position:"absolute"});c.append(e);d=e.get("offsetHeight");e.remove(!0);a.one('.comment[data-commentid="'+b.getAttribute("data-commentId")+'"]').fire("reply-open");this.hideAllPreviews();h=new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:Math.max(d,190)+15}});h.on("end",function(){this._node.setStyle("height","auto");var b=this._node.getY()+this._node.get("offsetHeight")-(f.get("docScrollY")+f.get("winHeight")),c=f.get("scrollTop");0<=b&&(b=new a.Anim({node:f,duration:0.3,easing:a.Easing.easeOutStrong, to:{scrollTop:c+b}}),b.run())});h.run()}},this);c.hasClass("reply-open")?(c.removeClass("reply-open"),this.hideAllPreviews(),k(e)):(e.one(".reply-area").setAttribute("replyid",d),a.all(".comment.reply-open").each(function(b){b.removeClass("reply-open");b=a.one('.reply-area-wrapper[data-commentid="'+b.getAttribute("data-commentid")+'"]');k(b)}),d=e.one("textArea"),this.replyCompleteEvents[c.getAttribute("data-commentId")]||(this.replyCompleteEvents[c.getAttribute("data-commentId")]=this.once("reply-complete", function(a){k(e,function(){this.one(".input").setStyle("height","auto")});this.replyCompleteEvents[c.getAttribute("data-commentId")]=null},this)),d.on("focus",function(){this.setAttribute("data-edited",!0)}),d.on("blur",function(){""===this.get("value")&&this.setAttribute("data-edited",!1)}),c.addClass("reply-open"),l(e));b.stopImmediatePropagation()},escapeComment:function(b){b.authorName=a.Squarespace.Escaping.escapeForHtml(b.authorName);b.authorUrl=a.Squarespace.Escaping.escapeForHtml(b.authorUrl); b.authorEmail=a.Squarespace.Escaping.escapeForHtml(b.authorEmail);b.memberAccount&&(b.memberAccount.displayName=a.Squarespace.Escaping.escapeForHtml(b.memberAccount.displayName),b.memberAccount.bio=a.Squarespace.Escaping.escapeForHtml(b.memberAccount.bio))},addReplyArea:function(b){var c=a.one(".reply-area-wrapper");c?(c.one(".preview-comment").setAttribute("data-state","closed").set("innerHTML","Preview"),c=c.cloneNode(!0),c.setAttribute("data-commentId",b.getAttribute("data-commentId")),c.setAttribute("data-depth", b.getAttribute("data-depth"))):(c={comments:[{id:b.getAttribute("data-commentId"),depth:b.getAttribute("data-depth")}]},c=this.renderToFragment(c),c=c.one(".reply-area-wrapper").cloneNode(!0));c.setStyle("height",null);b.insert(c,"after")},prependComment:function(b){var c=(SQUARESPACE_LOGIN.account?SQUARESPACE_LOGIN.account.displayName:a.Cookie.get("displayName"))||e("Not Logged In");b=a.one(".top-level-comment-area .comment-input");var d=a.one(".top-level.comment-preview"),f=!1;d?(d.one(".author").set("innerHTML", a.Escape.html(c)),c=d.ancestor(".comment-preview-wrapper")):(d=this.generatePreview(b).one(".comment-preview"),f=!0,d.wrap('<div class="comment-preview-wrapper"></div>'),c=d.ancestor(".comment-preview-wrapper"),a.one(".comment-list").prepend(c));d.removeClass("comment-preview");d.addClass("pending");a.one(".top-level-comment-area .preview-comment").setAttribute("data-state","closed");this.hidePreview(b);f?(b=new a.Anim({node:c,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:d.get("offsetHeight")+ parseInt(d.getComputedStyle("marginBottom"),10)}}),b.on("end",function(){d.unwrap()}),b.run()):d.unwrap();this.containerEl.removeClass("empty");this.makeMostRecent(d);return d},injectReply:function(b,c){var d=c.getAttribute("data-commentId"),f=a.one('.comment-preview-wrapper[data-commentId="'+d+'"]'),d=a.one('.reply-area-wrapper[data-commentId="'+d+'"]').one("textArea"),g=(SQUARESPACE_LOGIN.account?SQUARESPACE_LOGIN.account.displayName:a.Cookie.get("displayName"))||e("Not Logged In"),h=!1;f?(f=f.one(".comment-preview"), f.one(".author").set("innerHTML",a.Escape.html(g))):(f=this.generatePreview(d).one(".comment-preview"),h=!0,f.wrap('<div class="comment-preview-wrapper"></div>'),f.ancestor(".comment-preivew-wrapper"));c.hasAttribute("data-depth")&&f.setAttribute("data-depth",parseInt(c.getAttribute("data-depth"),10)+1);f.unwrap();f.removeClass("comment-preview");f.addClass("pending");c.removeClass("reply-open");c.fire("reply-complete");h&&(d.ancestor(".reply-area-wrapper").cloneNode(!0),d.ancestor(".reply-area-wrapper").insert(f, "after"));this.makeMostRecent(f);this.fire("reply-complete",{node:f});return f},makeMostRecent:function(b){b.hasClass("comment")&&(a.all(".comment.pending.most-recent").each(function(a){a.ancestor(".most-recent-anim-wrapper")||a.removeClass("most-recent")}),b.addClass("most-recent"))},fullDataRender:function(){this.render(this.commentData.formatted);this.commentList=a.one(".comment-list")},threadRender:function(){this.render(this.commentData.formattedThread);this.commentList=a.one(".comment-list"); this.commentList.one('.comment[data-commentId="'+this.commentData.currentThreadRoot+'"]').addClass("target")},showEmptyText:function(){new a.Squarespace.Widgets.Alert({"strings.title":e("Enter Comment Text"),"strings.message":e("Enter text in the field above to post a comment.")})},showModerationNotification:function(){new a.Squarespace.Widgets.Alert({className:"okay","strings.title":e("Comment Awaiting Moderation"),"strings.message":e("Your comment has been successfully posted and is awaiting moderation.")})}, showCommentSuccessNotification:function(){new a.Squarespace.Widgets.Alert({className:"okay","strings.title":e("Comment Posted"),"strings.message":e("Your comment has been successfully posted.")})},showPostCommentNotification:function(a){a.status===l.AWAITING_MODERATION&&this.showModerationNotification()},squarespaceAdminOnly:function(){return Static.SQUARESPACE_CONTEXT.website.cloneable&&!this.userHasAccessPermission(d.ADMIN)},commentBtnOnClick:function(b){var c=a.one(".top-level-comment-area .comment-input"), d=c.get("value");if(""===d.trim())this.showEmptyText();else{var e=this.prependComment(d);this.submitTopLevel(d,e,c)}b.stopImmediatePropagation()},updateWithMemberAccount:function(b,c){if(c&&!SQUARESPACE_LOGIN.account){var d=b.one(".author");d&&d.setContent(a.Escape.html(c.displayName));(d=b.one(".avatar img"))&&c.avatarAssetUrl&&d.setAttribute("src",c.avatarAssetUrl)}},submitTopLevel:function(b,c,d){if(a.Squarespace.Utils.areCookiesEnabled()){this.setPosting(c,!this.approvalRequired||!this.moderationMode); var f=d.get("value");d.set("value","");this.addComment({onSuccess:function(b){this.updateCommentCounts();a.Lang.isNull(c._node)||(this.setPosted(c),c.setAttribute("data-commentId",b.comment.id),b.comment.status===l.APPROVED&&c.removeClass("pending"),this.addReplyArea(c),this.updateWithMemberAccount(c,b.comment.memberAccount),this.showPostCommentNotification(b.comment))},onFailure:function(g){d.set("value",f);if(g.errors)if(g.errors.anonEmail||g.errors.authorEmail||g.errors.authorName){var h=c.one(".author"); g.errors.anonEmail&&new a.Squarespace.Widgets.Alert({className:"okay","strings.title":e("Comment Failed"),"strings.message":g.errors.anonEmail});SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5});this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.submitTopLevel(b,c,d);(!a.Lang.isNull(h)||a.Lang.isNull(h._node))&&h.set("innerHTML",a.Escape.html(SQUARESPACE_LOGIN.account.displayName));SQUARESPACE_LOGIN.account.avatarAssetUrl&&c.one(".avatar").one("img").setAttribute("src", SQUARESPACE_LOGIN.account.avatarAssetUrl);k.detach()},this);this.doAfterGuestLogin(SQUARESPACE_LOGIN,function(){this.submitTopLevel(b,c,d);var e=a.Cookie.get("displayName");!a.Lang.isNull(h)&&(!a.Lang.isNull(h._node)&&!a.Lang.isNull(e))&&h.set("innerHTML",a.Escape.html(e));k.detach()},this);var k=SQUARESPACE_LOGIN.once("cancel",function(){this.removeMostRecentPending()},this);SQUARESPACE_LOGIN.showCommentLogin(e("Post Comment"),e("Post Comment"),this.settings.allowAnon)}else this.showPostCommentNotification(g.comment)}, body:b},this)}else new a.Squarespace.Widgets.Alert({"strings.title":e("Comments disallowed"),"strings.message":e("This browser does not accept cookies, which is a requirement for commenting. You can allow cookies by changing your browser's settings.")})},removeMostRecentPending:function(){var b=a.one(".comment.most-recent"),c;b.ancestor(".comment-preview-wrapper")&&b.unwrap();b.wrap('<div class="most-recent-anim-wrapper"></div>');c=b.ancestor(".most-recent-anim-wrapper");c.setStyles({overflow:"hidden", height:b.get("offsetHeight")});b=new a.Anim({node:c,duration:0.3,easing:a.Easing.easeOutStrong,to:{height:0}});b.on("end",function(){this._node.remove(!0)});b.run()},onLoading:function(){var b=a.one(".comments-content"),c=a.Node.create('<div class="comment-event-capture"></div>');c.setStyles({position:"absolute",top:b.getY(),left:b.getX(),width:b.get("offsetWidth"),height:b.get("offsetHeight"),zIndex:1E3});c.on("hover",function(a){a.stopImmediatePropagation()});c.on("click",function(a){a.stopImmediatePropagation()}); a.one(a.config.doc.body).append(c);(new a.Anim({node:b,duration:0.3,easing:a.Easing.easeOutStrong,to:{opacity:0.3}})).run()},commentIdHashOnChange:function(b){!a.Lang.isNull(b.newVal)&&!a.Lang.isUndefined(b.newVal)&&(this.threadState=!0,this.lastHashChangeTime=new Date,this.onLoading(),this.retrieveThread({commentId:b.newVal,order:this.sortOrder,onSuccess:function(){this.threadRender()}}))},commentIdHashOnRemove:function(){this.threadState=!1;this.lastHashChangeTime=new Date;this.onLoading();this.retrieveComments({onSuccess:function(a){this.fullDataRender(a)}, page:1,order:this.sortOrder},this)},retrieveThread:function(a,b){this.threadState=!0;this.commentData.getThread({order:a.order,commentId:a.commentId,success:a.onSuccess,failure:function(c){this.threadState=!1;a.onFailure.call(b||this,c)}},b||this)},retrieveComments:function(b,c){var d=a.bind(function(a){this.lastPollTime=new Date;b.onSuccess.call(c||this,a);this.updateLikedFlaggedState()},this);this.commentData.get({order:b.order,page:b.page,since:b.since||"",success:d,failure:b.onFailure},this)}, addComment:function(b,c){var d=a.bind(function(d){a.Lang.isFunction(b.onSuccess)&&(b||noop).onSuccess.call(c||this,d);a.Cookie.remove("displayName",{path:"/"})},this);this.commentData.post({body:b.body,replyTo:b.replyTo,name:SQUARESPACE_LOGIN.account?SQUARESPACE_LOGIN.account.displayName:a.Cookie.get("displayName"),email:SQUARESPACE_LOGIN.account?SQUARESPACE_LOGIN.account.email:a.Cookie.get("email"),authorUrl:SQUARESPACE_LOGIN.account?SQUARESPACE_LOGIN.account.websiteUrl:a.Cookie.get("websiteUrl"), success:d,failure:b.onFailure},c||this)},setPosting:function(a,b){a.all(".posting-text").each(function(a){a.removeClass("visible")});var c=a.one(".posting-text"+(b?".moderated":""));c&&c.addClass("visible")},setPosted:function(a){(a=a.all(".posting-text"))&&a.each(function(a){a.removeClass("visible")})},replyTo:function(b,c,d,f){this.setPosting(d,!this.approvalRequired||!this.moderationMode);var g=f.get("value");f.set("value","");this.addComment({body:c,replyTo:b,onSuccess:function(b){this.updateCommentCounts(); a.Lang.isNull(f._node)||(this.setPosted(d),d.setAttribute("data-commentId",b.comment.id),b.comment.status===l.APPROVED&&d.removeClass("pending"),this.addReplyArea(d),this.updateWithMemberAccount(d,b.comment.memberAccount),this.showPostCommentNotification(b.comment))},onFailure:function(h){f.set("value",g);if(h.errors&&(h.errors.anonEmail||h.errors.authorEmail||h.errors.authorName)){h.errors.anonEmail&&new a.Squarespace.Widgets.Alert({className:"okay","strings.title":e("Comment Failed"),"strings.message":h.errors.anonEmail}); SQUARESPACE_LOGIN.configure({redirectAfterLogin:!1,reloadAfterLogin:!1,overlayOpacity:0.5});this.doAfterLogin(SQUARESPACE_LOGIN,function(){this.replyTo(b,c,d,f);a.one('.comment[data-replyTo="'+b+'"] .author').set("innerHTML",a.Escape.html(SQUARESPACE_LOGIN.account.displayName));d.one(".author").set("innerHTML",a.Escape.html(SQUARESPACE_LOGIN.account.displayName));SQUARESPACE_LOGIN.account.avatarAssetUrl&&d.one(".avatar").one("img").setAttribute("src",SQUARESPACE_LOGIN.account.avatarAssetUrl);k.detach()}, this);this.doAfterGuestLogin(SQUARESPACE_LOGIN,function(){this.replyTo(b,c,d,f);var e=a.Cookie.get("displayName");a.Lang.isNull(e)||a.one('.comment[data-replyTo="'+b+'"] .author').set("innerHTML",a.Escape.html(e));k.detach()},this);var k=SQUARESPACE_LOGIN.once("cancel",function(){this.removeMostRecentPending()},this);SQUARESPACE_LOGIN.showCommentLogin(e("Log In to Post Reply"),e("Post Reply"),this.settings.allowAnon)}}},this)},extendComments:function(){this.currentPage+=1;var a=this.lastSortTime, b=this.lastHashChangeTime;this.retrieveComments({order:this.sortOrder,onSuccess:function(){a===this.lastSortTime&&b===this.lastHashChangeTime&&this.attachComments.call(this)},page:this.currentPage},this)},attachComments:function(){var b=this.commentData.formatted;b.comments=this.commentData.getFormattedPage(this.currentPage);b=this.renderToFragment(b);this.updateCommentCounts();var c=a.one(".comment-list");b.all(".comment, .reply-area-wrapper").each(function(a){c.append(a)});this.containerEl.one(".load-more").remove(!0); this.addLoadMoreControls()},sort:function(b){var c=this.sortOrderLookup[b];a.Cookie.set("commentSortOrder",b);this.sortOrder=b;this.currentPage=1;this.onLoading();this.retrieveComments({order:this.sortOrder,onSuccess:function(b){this.lastSortTime=new Date;this.fullDataRender(b);b=a.one(".comment-sort");b.one("span").set("innerHTML",c);b.one("select").set("value",this.sortOrder)},page:this.currentPage})},formatData:function(a,b,c){var d,e={comments:[]},f;b=b||{};c=c||{};var g=this.squarespaceAdminOnly()|| this.settings.readOnly;e.noAvatars=this.settings.avatarsHidden;e.likesAllowed=this.settings.likesAllowed;e.newCommentAreaTop={authenticatedAccount:SQUARESPACE_LOGIN.account,readOnly:g};e.commentSortTitle=this.sortOrderLookup[this.sortOrder];e.sortOldestFirst=this.sortOrder===h.OLDEST_FIRST;e.sortNewestFirst=this.sortOrder===h.NEWEST_FIRST;e.sortMostLiked=this.sortOrder===h.MOST_LIKED;e.sortLeastLiked=this.sortOrder===h.LEAST_LIKED;e.totalComments=this.commentData.totalComments;e.visibleComments=this.commentData.visibleComments; e.subscribed=Static.SQUARESPACE_CONTEXT.subscribed;for(var k=0;k<a.length;k++)f=a[k],f.unmoderated=f.status===l.AWAITING_MODERATION,f.moderationMode=this.moderationMode,f.readOnly=g,f.flagsAllowed=this.settings.flagsAllowed,f.memberAccount&&(f.authorName=f.memberAccount.displayName,f.authorUrl=f.memberAccount.websiteUrl),f.authorUrl&&(!f.authorUrl.startsWith("http://")&&!f.authorUrl.startsWith("https://"))&&(f.authorUrl="http://"+f.authorUrl),d=f.id,this.settings.likesAllowed&&(f.likesAllowed={likeCount:f.likeCount}, b[d]&&(f.likesAllowed.liked=!0)),c[d]&&(f.flagged=!0),f.threaded=this.settings.threaded,e.comments.push(f);return e},scatterData:function(a){var b=this.squarespaceAdminOnly()||this.settings.readOnly;a.noAvatars=this.settings.avatarsHidden;a.likesAllowed=this.settings.likesAllowed;a.newCommentAreaTop={};a.newCommentAreaTop.readOnly=b;a.newCommentAreaTop.authenticatedAccount=SQUARESPACE_LOGIN.account;a.commentSortTitle=this.sortOrderLookup[this.sortOrder];a.subscribed=Static.SQUARESPACE_CONTEXT.subscribed; 0===this.commentData.totalComments&&(a.noComments=!0);for(var c={},d=0;d<a.comments.length;d++)c=a.comments[d],c.flagsAllowed=this.settings.flagsAllowed,c.moderationMode=this.moderationMode,c.memberAccount&&(c.authorName=c.memberAccount.displayName,c.authorUrl=c.memberAccount.websiteUrl),c.authorUrl&&(!c.authorUrl.startsWith("http://")&&!c.authorUrl.startsWith("https://"))&&(c.authorUrl="http://"+c.authorUrl),c.readOnly=b,this.settings.likesAllowed&&(c.likesAllowed||(c.likesAllowed={likeCount:0}), c.likesAllowed.likeCount=0===c.likesAllowed.likeCount?void 0:c.likesAllowed.likeCount),c.threaded=this.settings.threaded,a.likeMap&&(a.likeMap[c.id]&&void 0!==c.likesAllowed)&&(c.likesAllowed.liked=!0),a.flagMap&&a.flagMap[c.id]&&(c.flagged=!0),a.comments[d]=c;return a},render:function(b){var c=this.renderToFragment(b),d=this.commentsEl,e=a.one(".comment-event-capture");b.comments.length?this.containerEl.removeClass("empty"):this.containerEl.addClass("empty");d.empty();d.append(c);b=new a.Anim({node:d, duration:0.3,easing:a.Easing.easeOutStrong,to:{opacity:1}});b.on("end",function(){e.remove(!0)});b.run();this.addFullViewControls();switch(this.params.paginationMode){case this.PaginationModes.EXTEND:this.addLoadMoreControls()}this.fire("render")},renderToFragment:function(b){for(var c=0;c<b.comments.length;c++)this.escapeComment(b.comments[c]),b.comments[c].body=n.sanitize(b.comments[c].body);c=a.Node.create(this._template.expand(b));c.all(".comment").each(function(a,c){a.setAttribute("data-commentId", b.comments[c].id)});return c}});a.augment(a.Squarespace.Comments,a.EventTarget);var b=null;a.config.win.Squarespace.onInitialize(a,function(){var c=a.config.win.Static,d=c.SQUARESPACE_CONTEXT.websiteSettings.disqusShortname;if(d){var e=a.one(".squarespace-comments");e&&(d&&""!==d)&&(window.disqus_shortname=d,"disqus_thread"!==e.getAttribute("id")&&e.setAttribute("id","disqus_thread"),a.Get.script("//"+d+".disqus.com/embed.js",{win:a.config.win}))}else{var e=a.one(".squarespace-comments"),f,g,h=c.SQUARESPACE_CONTEXT.websiteSettings; if(e&&!h.disqusShortname){var l=e.getAttribute("data-item-id"),n=e.getAttribute("data-collection-id"),d=parseInt(e.getAttribute("data-comment-state"),10),B=parseInt(e.getAttribute("data-public-comment-count"),10);if(f=l||n){g=l?m.ITEM:m.COLLECTION;var A=l=!1;g===m.ITEM&&d===k.DISABLED&&(0===B?l=!0:A=!0);if(!l){var z=function(){a.use("squarespace-comments","cookie",function(a){b=new a.Squarespace.Comments({containerEl:e,identifier:f,type:g,publicCommentCount:B,likesAllowed:h.commentLikesAllowed,flagsAllowed:h.commentFlagsAllowed, threaded:h.commentThreaded,approvalRequired:h.commentApprovalRequired,allowAnon:h.commentAnonAllowed,avatarsOn:h.commentAvatarsOn,readOnly:A,sortType:a.Cookie.get("commentSortOrder")||h.commentSortType});b.create()})},d=function(){a.use("squarespace-comments","cookie",function(a){var b=function(){a.Data.get({url:"/api/auth/CheckAuthentication",secure:!0,success:function(b){null!==b.member&&a.use("squarespace-management",function(a){c.SQUARESPACE_CONTEXT.authenticatedAccount=b.member;SQUARESPACE_LOGIN.params= a.merge(SQUARESPACE_LOGIN.params,{redirectAfterCancel:!1,redirectAfterLogin:!1});SQUARESPACE_LOGIN.onLoginComplete(b.member)});z()},failure:z})};a.Data.TRANSPORT_READY?b():(console.warn("Flash cross-domain transport not initialized yet. Delaying comment initialization until flash is ready."),a.once("io:xdrReady",b))})};c.SQUARESPACE_CONTEXT.authenticatedAccount||c.SQUARESPACE_CONTEXT.website.cloneable?z():d()}}}}});a.config.win.Squarespace.onDestroy(a,function(){b&&(b.destroy(),b=null)})},"1.0",{requires:"anim event history node selector-css3 squarespace-comment-data squarespace-dialog squarespace-escaping-utils squarespace-json-template squarespace-login squarespace-markdown squarespace-ui-base squarespace-util squarespace-widgets-alert squarespace-widgets-confirmation squarespace-widgets-information transition".split(" ")})}]);
app/components/Loading/index.js
vollmerr/app-hub
import React from 'react'; import PropTypes from 'prop-types'; import ErrorMessage from './ErrorMessage'; import LoadingMessage from './LoadingMessage'; // https://www.npmjs.com/package/react-loadable class Loading extends React.PureComponent { render() { const { text, loading, isLoading, timedOut, pastDelay, error } = this.props; if (loading) { return <LoadingMessage text={text} />; } else if (isLoading) { // isLoading and timeOut, etc is used by react-loadable if (timedOut) { return <ErrorMessage {...this.props} />; } else if (pastDelay) { return <LoadingMessage text={text} />; } } else if (error) { return <ErrorMessage {...this.props} />; } return null; } } const { bool, string, shape, number, oneOfType } = PropTypes; Loading.propTypes = { text: string, loading: oneOfType([bool, number]), isLoading: bool, timedOut: bool, pastDelay: bool, error: shape({ message: string }), }; export default Loading;
src/components/series/SeriesList.js
IvoPaunov/stremio-demo-app
import React, {PropTypes} from 'react'; import SerieListBox from './SerieListBox'; const SeriesList = ({series, onChange}) => { return ( <div className="metas-list-container"> <div className="row"> {series.map(serie => <SerieListBox key={serie.imdb_id} serie={serie} onChange={onChange}/> )} </div> </div> ); }; SeriesList.propTypes = { series: PropTypes.array.isRequired, onChange: React.PropTypes.func.isRequired }; export default SeriesList;
src/__tests__/components/MessageSection.js
isuruAb/chat.susi.ai
import React from 'react'; import MessageSection from '../../components/ChatApp/MessageSection/MessageSection.react'; import { shallow } from 'enzyme'; it('render MessageListItem without crashing', () => { shallow(<MessageSection />); })
client/src/components/Session/withAuthorization.js
googleinterns/Pictophone
import React from 'react'; import { withRouter } from 'react-router-dom'; import { compose } from 'recompose'; import AuthUserContext from './context'; import { withFirebase } from '../Firebase'; import * as ROUTES from '../../constants/routes'; const withAuthorization = condition => Component => { class WithAuthorization extends React.Component { componentDidMount() { this.listener = this.props.firebase.onAuthUserListener( authUser => { if (!condition(authUser)) { this.props.history.push(ROUTES.LANDING); } }, () => this.props.history.push(ROUTES.LANDING), ); } componentWillUnmount() { this.listener(); } render() { return ( <AuthUserContext.Consumer> {authUser => condition(authUser) ? <Component {...this.props} /> : null } </AuthUserContext.Consumer> ); } } return compose( withRouter, withFirebase, )(WithAuthorization); }; export default withAuthorization;
ajax/libs/react/0.9.0/react-with-addons.js
ppoffice/cdnjs
/** * React (with addons) v0.9.0 */ !function(e){if("object"==typeof exports)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.React=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(require,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. * * @providesModule AutoFocusMixin * @typechecks static-only */ "use strict"; var AutoFocusMixin = { componentDidMount: function() { if (this.props.autoFocus) { this.getDOMNode().focus(); } } }; module.exports = AutoFocusMixin; },{}],2:[function(require,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. * * @providesModule CSSCore * @typechecks */ var invariant = require("./invariant"); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function(element, className) { ("production" !== "development" ? invariant( !/\s/.test(className), 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ) : invariant(!/\s/.test(className))); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function(element, className) { ("production" !== "development" ? invariant( !/\s/.test(className), 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ) : invariant(!/\s/.test(className))); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1') .replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to set the class on * @param {string} className the CSS className * @returns {boolean} true if the element has the class, false if not */ hasClass: function(element, className) { ("production" !== "development" ? invariant( !/\s/.test(className), 'CSS.hasClass takes only a single class name.' ) : invariant(!/\s/.test(className))); if (element.classList) { return !!className && element.classList.contains(className); } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; } }; module.exports = CSSCore; },{"./invariant":121}],3:[function(require,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. * * @providesModule CSSProperty */ "use strict"; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { columnCount: true, fillOpacity: true, flex: true, flexGrow: true, flexShrink: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function(prop) { prefixes.forEach(function(prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundImage: true, backgroundPosition: true, backgroundRepeat: true, backgroundColor: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],4:[function(require,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. * * @providesModule CSSPropertyOperations * @typechecks static-only */ "use strict"; var CSSProperty = require("./CSSProperty"); var dangerousStyleValue = require("./dangerousStyleValue"); var escapeTextForBrowser = require("./escapeTextForBrowser"); var hyphenate = require("./hyphenate"); var memoizeStringOnly = require("./memoizeStringOnly"); var processStyleName = memoizeStringOnly(function(styleName) { return escapeTextForBrowser(hyphenate(styleName)); }); /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function(styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleValue) { style[styleName] = styleValue; } else { var expansion = CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; },{"./CSSProperty":3,"./dangerousStyleValue":107,"./escapeTextForBrowser":109,"./hyphenate":120,"./memoizeStringOnly":129}],5:[function(require,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. * * @providesModule ChangeEventPlugin */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var ReactUpdates = require("./ReactUpdates"); var SyntheticEvent = require("./SyntheticEvent"); var isEventSupported = require("./isEventSupported"); var isTextInputElement = require("./isTextInputElement"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { return ( elem.nodeName === 'SELECT' || (elem.nodeName === 'INPUT' && elem.type === 'file') ); } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && ( !('documentMode' in document) || document.documentMode > 8 ); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled( eventTypes.change, activeElementID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactEventTopLevelCallback. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && ( !('documentMode' in document) || document.documentMode > 9 ); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function() { return activeElementValueProp.get.call(this); }, set: function(val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor( target.constructor.prototype, 'value' ); Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return ( elem.nodeName === 'INPUT' && (elem.type === 'checkbox' || elem.type === 'radio') ); } function getTargetIDForClickEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc( topLevelType, topLevelTarget, topLevelTargetID ); if (targetID) { var event = SyntheticEvent.getPooled( eventTypes.change, targetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc( topLevelType, topLevelTarget, topLevelTargetID ); } } }; module.exports = ChangeEventPlugin; },{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":80,"./SyntheticEvent":88,"./isEventSupported":122,"./isTextInputElement":124,"./keyOf":128}],6:[function(require,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. * * @providesModule ClientReactRootIndex * @typechecks */ "use strict"; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function() { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],7:[function(require,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. * * @providesModule CompositionEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var ReactInputSelection = require("./ReactInputSelection"); var SyntheticCompositionEvent = require("./SyntheticCompositionEvent"); var getTextContentAccessor = require("./getTextContentAccessor"); var keyOf = require("./keyOf"); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var useCompositionEvent = ( ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window ); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. In Korean, for example, // the compositionend event contains only one character regardless of // how many characters have been composed since compositionstart. // We therefore use the fallback data while still using the native // events as triggers. var useFallbackData = ( !useCompositionEvent || 'documentMode' in document && document.documentMode > 8 ); var topLevelTypes = EventConstants.topLevelTypes; var currentComposition = null; // Events and their corresponding property names. var eventTypes = { compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({onCompositionEnd: null}), captured: keyOf({onCompositionEndCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({onCompositionStart: null}), captured: keyOf({onCompositionStartCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({onCompositionUpdate: null}), captured: keyOf({onCompositionUpdateCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] } }; /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackStart(topLevelType, nativeEvent) { return ( topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE ); } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1); case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return (nativeEvent.keyCode !== START_KEYCODE); case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Helper class stores information about selection and document state * so we can figure out what changed at a later date. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this.root = root; this.startSelection = ReactInputSelection.getSelection(root); this.startValue = this.getText(); } /** * Get current text of input. * * @return {string} */ FallbackCompositionState.prototype.getText = function() { return this.root.value || this.root[getTextContentAccessor()]; }; /** * Text that has changed since the start of composition. * * @return {string} */ FallbackCompositionState.prototype.getData = function() { var endValue = this.getText(); var prefixLength = this.startSelection.start; var suffixLength = this.startValue.length - this.startSelection.end; return endValue.substr( prefixLength, endValue.length - suffixLength - prefixLength ); }; /** * This plugin creates `onCompositionStart`, `onCompositionUpdate` and * `onCompositionEnd` events on inputs, textareas and contentEditable * nodes. */ var CompositionEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var eventType; var data; if (useCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (useFallbackData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = new FallbackCompositionState(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { data = currentComposition.getData(); currentComposition = null; } } } if (eventType) { var event = SyntheticCompositionEvent.getPooled( eventType, topLevelTargetID, nativeEvent ); if (data) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = data; } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } }; module.exports = CompositionEventPlugin; },{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactInputSelection":56,"./SyntheticCompositionEvent":86,"./getTextContentAccessor":118,"./keyOf":128}],8:[function(require,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. * * @providesModule DOMChildrenOperations * @typechecks static-only */ "use strict"; var Danger = require("./Danger"); var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes"); var getTextContentAccessor = require("./getTextContentAccessor"); /** * The DOM property to use when setting text content. * * @type {string} * @private */ var textContentAccessor = getTextContentAccessor(); /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ function insertChildAt(parentNode, childNode, index) { var childNodes = parentNode.childNodes; if (childNodes[index] === childNode) { return; } // If `childNode` is already a child of `parentNode`, remove it so that // computing `childNodes[index]` takes into account the removal. if (childNode.parentNode === parentNode) { parentNode.removeChild(childNode); } if (index >= childNodes.length) { parentNode.appendChild(childNode); } else { parentNode.insertBefore(childNode, childNodes[index]); } } /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ var updateTextContent; if (textContentAccessor === 'textContent') { updateTextContent = function(node, text) { node.textContent = text; }; } else { updateTextContent = function(node, text) { // In order to preserve newlines correctly, we can't use .innerText to set // the contents (see #1080), so we empty the element then append a text node while (node.firstChild) { node.removeChild(node.firstChild); } if (text) { var doc = node.ownerDocument || document; node.appendChild(doc.createTextNode(text)); } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: updateTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function(updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; update = updates[i]; i++) { if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; update = updates[k]; k++) { switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt( update.parentNode, renderedMarkup[update.markupIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt( update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: updateTextContent( update.parentNode, update.textContent ); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; module.exports = DOMChildrenOperations; },{"./Danger":11,"./ReactMultiChildUpdateTypes":63,"./getTextContentAccessor":118}],9:[function(require,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. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ "use strict"; var invariant = require("./invariant"); var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function(domPropertyConfig) { var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push( domPropertyConfig.isCustomAttribute ); } for (var propName in Properties) { ("production" !== "development" ? invariant( !DOMProperty.isStandardName[propName], 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName ) : invariant(!DOMProperty.isStandardName[propName])); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; var attributeName = DOMAttributeNames[propName]; if (attributeName) { DOMProperty.getPossibleStandardName[attributeName] = propName; } DOMProperty.getAttributeName[propName] = attributeName || lowerCased; DOMProperty.getPropertyName[propName] = DOMPropertyNames[propName] || propName; var mutationMethod = DOMMutationMethods[propName]; if (mutationMethod) { DOMProperty.getMutationMethod[propName] = mutationMethod; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE; DOMProperty.mustUseProperty[propName] = propConfig & DOMPropertyInjection.MUST_USE_PROPERTY; DOMProperty.hasSideEffects[propName] = propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS; DOMProperty.hasBooleanValue[propName] = propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE; DOMProperty.hasPositiveNumericValue[propName] = propConfig & DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE; ("production" !== "development" ? invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ) : invariant(!DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName])); ("production" !== "development" ? invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ) : invariant(DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName])); ("production" !== "development" ? invariant( !DOMProperty.hasBooleanValue[propName] || !DOMProperty.hasPositiveNumericValue[propName], 'DOMProperty: Cannot have both boolean and positive numeric value: %s', propName ) : invariant(!DOMProperty.hasBooleanValue[propName] || !DOMProperty.hasPositiveNumericValue[propName])); } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { return DOMProperty._isCustomAttributeFunctions.some( function(isCustomAttributeFn) { return isCustomAttributeFn.call(null, attributeName); } ); }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"./invariant":121}],10:[function(require,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. * * @providesModule DOMPropertyOperations * @typechecks static-only */ "use strict"; var DOMProperty = require("./DOMProperty"); var escapeTextForBrowser = require("./escapeTextForBrowser"); var memoizeStringOnly = require("./memoizeStringOnly"); function shouldIgnoreValue(name, value) { return value == null || DOMProperty.hasBooleanValue[name] && !value || DOMProperty.hasPositiveNumericValue[name] && (isNaN(value) || value < 1); } var processAttributeNameAndPrefix = memoizeStringOnly(function(name) { return escapeTextForBrowser(name) + '="'; }); if ("production" !== "development") { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function(name) { if (reactProps[name] || warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName[lowerCasedName]; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. if (standardName != null) { console.warn( 'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?' ); } }; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function(id) { return processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) + escapeTextForBrowser(id) + '"'; }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function(name, value) { if (DOMProperty.isStandardName[name]) { if (shouldIgnoreValue(name, value)) { return ''; } var attributeName = DOMProperty.getAttributeName[name]; if (DOMProperty.hasBooleanValue[name]) { return escapeTextForBrowser(attributeName); } return processAttributeNameAndPrefix(attributeName) + escapeTextForBrowser(value) + '"'; } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return processAttributeNameAndPrefix(name) + escapeTextForBrowser(value) + '"'; } else if ("production" !== "development") { warnUnknownProperty(name); } return null; }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function(node, name, value) { if (DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(name, value)) { this.deleteValueForProperty(node, name); } else if (DOMProperty.mustUseAttribute[name]) { node.setAttribute(DOMProperty.getAttributeName[name], '' + value); } else { var propName = DOMProperty.getPropertyName[name]; if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) { node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { node.setAttribute(name, '' + value); } } else if ("production" !== "development") { warnUnknownProperty(name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function(node, name) { if (DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, undefined); } else if (DOMProperty.mustUseAttribute[name]) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { var propName = DOMProperty.getPropertyName[name]; var defaultValue = DOMProperty.getDefaultValueForProperty( node.nodeName, name ); if (!DOMProperty.hasSideEffects[name] || node[propName] !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if ("production" !== "development") { warnUnknownProperty(name); } } }; module.exports = DOMPropertyOperations; },{"./DOMProperty":9,"./escapeTextForBrowser":109,"./memoizeStringOnly":129}],11:[function(require,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. * * @providesModule Danger * @typechecks static-only */ /*jslint evil: true, sub: true */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var createNodesFromMarkup = require("./createNodesFromMarkup"); var emptyFunction = require("./emptyFunction"); var getMarkupWrap = require("./getMarkupWrap"); var invariant = require("./invariant"); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function(markupList) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a Worker ' + 'thread. This is likely a bug in the framework. Please report ' + 'immediately.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== "development" ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. for (var resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (i = 0; i < renderNodes.length; ++i) { var renderNode = renderNodes[i]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== "development" ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== "development") { console.error( "Danger: Discarding unexpected node:", renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== "development" ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== "development" ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. This is likely a bug in the framework. Please report ' + 'immediately.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup)); ("production" !== "development" ? invariant( oldChild.tagName.toLowerCase() !== 'html', 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See renderComponentToString().' ) : invariant(oldChild.tagName.toLowerCase() !== 'html')); var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; },{"./ExecutionEnvironment":21,"./createNodesFromMarkup":104,"./emptyFunction":108,"./getMarkupWrap":115,"./invariant":121}],12:[function(require,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. * * @providesModule DefaultDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = require("./DOMProperty"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var DefaultDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusMixin // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, className: MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: null, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, frameBorder: MUST_USE_ATTRIBUTE, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, label: null, lang: null, list: null, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, max: null, maxLength: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, noValidate: HAS_BOOLEAN_VALUE, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scrollLeft: MUST_USE_PROPERTY, scrollTop: MUST_USE_PROPERTY, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, step: null, style: null, tabIndex: null, target: null, title: null, type: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ autoCapitalize: null, // Supported in Mobile Safari for keyboard hints autoCorrect: null, // Supported in Mobile Safari for keyboard hints property: null, // Supports OG in meta tags /** * SVG Properties */ cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { className: 'class', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', htmlFor: 'for', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeLinecap: 'stroke-linecap', strokeWidth: 'stroke-width', viewBox: 'viewBox' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', encType: 'enctype', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc' }, DOMMutationMethods: { /** * Setting `className` to null may cause it to be set to the string "null". * * @param {DOMElement} node * @param {*} value */ className: function(node, value) { node.className = value || ''; } } }; module.exports = DefaultDOMPropertyConfig; },{"./DOMProperty":9}],13:[function(require,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. * * @providesModule DefaultEventPluginOrder */ "use strict"; var keyOf = require("./keyOf"); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [ keyOf({ResponderEventPlugin: null}), keyOf({SimpleEventPlugin: null}), keyOf({TapEventPlugin: null}), keyOf({EnterLeaveEventPlugin: null}), keyOf({ChangeEventPlugin: null}), keyOf({SelectEventPlugin: null}), keyOf({CompositionEventPlugin: null}), keyOf({AnalyticsEventPlugin: null}), keyOf({MobileSafariClickEventPlugin: null}) ]; module.exports = DefaultEventPluginOrder; },{"./keyOf":128}],14:[function(require,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. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var SyntheticMouseEvent = require("./SyntheticMouseEvent"); var ReactMount = require("./ReactMount"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({onMouseEnter: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] }, mouseLeave: { registrationName: keyOf({onMouseLeave: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] } }; var extractedEvents = [null, null]; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from, to; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) || win; } else { from = win; to = topLevelTarget; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromID = from ? ReactMount.getID(from) : ''; var toID = to ? ReactMount.getID(to) : ''; var leave = SyntheticMouseEvent.getPooled( eventTypes.mouseLeave, fromID, nativeEvent ); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled( eventTypes.mouseEnter, toID, nativeEvent ); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; },{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":60,"./SyntheticMouseEvent":91,"./keyOf":128}],15:[function(require,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. * * @providesModule EventConstants */ "use strict"; var keyMirror = require("./keyMirror"); var PropagationPhases = keyMirror({bubbled: null, captured: null}); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topBlur: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topReset: null, topScroll: null, topSelectionChange: null, topSubmit: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"./keyMirror":127}],16:[function(require,module,exports){ /** * @providesModule EventListener */ var emptyFunction = require("./emptyFunction"); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function() { target.detachEvent(eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function(target, eventType, callback) { if (!target.addEventListener) { if ("production" !== "development") { console.error( 'Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.' ); } return { remove: emptyFunction }; } else { target.addEventListener(eventType, callback, true); return { remove: function() { target.removeEventListener(eventType, callback, true); } }; } } }; module.exports = EventListener; },{"./emptyFunction":108}],17:[function(require,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. * * @providesModule EventPluginHub */ "use strict"; var EventPluginRegistry = require("./EventPluginRegistry"); var EventPluginUtils = require("./EventPluginUtils"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var accumulate = require("./accumulate"); var forEachAccumulated = require("./forEachAccumulated"); var invariant = require("./invariant"); var isEventSupported = require("./isEventSupported"); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ var executeDispatchesAndRelease = function(event) { if (event) { var executeDispatch = EventPluginUtils.executeDispatch; // Plugins can provide custom behavior when dispatching events. var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event); if (PluginModule && PluginModule.executeDispatch) { executeDispatch = PluginModule.executeDispatch; } EventPluginUtils.executeDispatchesInOrder(event, executeDispatch); if (!event.isPersistent()) { event.constructor.release(event); } } }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var invalid = !InstanceHandle|| !InstanceHandle.traverseTwoPhase || !InstanceHandle.traverseEnterLeave; if (invalid) { throw new Error('InstanceHandle not injected before use!'); } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function(InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if ("production" !== "development") { validateInstanceHandle(); } }, getInstanceHandle: function() { if ("production" !== "development") { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function(id, registrationName, listener) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'Cannot call putListener() in a non-DOM environment.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== "development" ? invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); if ("production" !== "development") { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. if (registrationName === 'onScroll' && !isEventSupported('scroll', true)) { console.warn('This browser doesn\'t support the `onScroll` event'); } } var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function(id) { for (var registrationName in listenerBank) { delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0, l = plugins.length; i < l; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); if (extractedEvents) { events = accumulate(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function(events) { if (events) { eventQueue = accumulate(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function() { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; forEachAccumulated(processingEventQueue, executeDispatchesAndRelease); ("production" !== "development" ? invariant( !eventQueue, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.' ) : invariant(!eventQueue)); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; },{"./EventPluginRegistry":18,"./EventPluginUtils":19,"./ExecutionEnvironment":21,"./accumulate":97,"./forEachAccumulated":111,"./invariant":121,"./isEventSupported":122}],18:[function(require,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. * * @providesModule EventPluginRegistry * @typechecks static-only */ "use strict"; var invariant = require("./invariant"); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); ("production" !== "development" ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== "development" ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== "development" ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.eventNameDispatchConfigs[eventName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs[eventName])); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName ); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName ) : invariant(!EventPluginRegistry.registrationNameModules[registrationName])); EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function(InjectedEventPluginOrder) { ("production" !== "development" ? invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than once.' ) : invariant(!EventPluginOrder)); // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function(injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (namesToPlugins[pluginName] !== PluginModule) { ("production" !== "development" ? invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName ) : invariant(!namesToPlugins[pluginName])); namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function(event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[ dispatchConfig.phasedRegistrationNames[phase] ]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function() { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; },{"./invariant":121}],19:[function(require,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. * * @providesModule EventPluginUtils */ "use strict"; var EventConstants = require("./EventConstants"); var invariant = require("./invariant"); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function(InjectedMount) { injection.Mount = InjectedMount; if ("production" !== "development") { ("production" !== "development" ? invariant( InjectedMount && InjectedMount.getNode, 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' + 'is missing getNode.' ) : invariant(InjectedMount && InjectedMount.getNode)); } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("production" !== "development") { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; ("production" !== "development" ? invariant( idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.' ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen)); }; } /** * Invokes `cb(event, listener, id)`. Avoids using call if no scope is * provided. The `(listener,id)` pair effectively forms the "dispatch" but are * kept separate to conserve memory. */ function forEachEventDispatch(event, cb) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "development") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. cb(event, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { cb(event, dispatchListeners, dispatchIDs); } } /** * Default implementation of PluginModule.executeDispatch(). * @param {SyntheticEvent} SyntheticEvent to handle * @param {function} Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, listener, domID) { event.currentTarget = injection.Mount.getNode(domID); var returnValue = listener(event, domID); event.currentTarget = null; return returnValue; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, executeDispatch) { forEachEventDispatch(event, executeDispatch); event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return id of the first dispatch execution who's listener returns true, or * null if no listener returned true. */ function executeDispatchesInOrderStopAtTrue(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "development") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("production" !== "development") { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; ("production" !== "development" ? invariant( !Array.isArray(dispatchListener), 'executeDirectDispatch(...): Invalid `event`.' ) : invariant(!Array.isArray(dispatchListener))); var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {bool} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatch: executeDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, injection: injection, useTouchEvents: false }; module.exports = EventPluginUtils; },{"./EventConstants":15,"./invariant":121}],20:[function(require,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. * * @providesModule EventPropagators */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var accumulate = require("./accumulate"); var forEachAccumulated = require("./forEachAccumulated"); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(domID, upwards, event) { if ("production" !== "development") { if (!domID) { throw new Error('Dispatching id must not be null'); } } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulate(event._dispatchListeners, listener); event._dispatchIDs = accumulate(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We can not perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase( event.dispatchMarker, accumulateDirectionalDispatches, event ); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulate(event._dispatchListeners, listener); event._dispatchIDs = accumulate(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave( fromID, toID, accumulateDispatches, leave, enter ); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"./EventConstants":15,"./EventPluginHub":17,"./accumulate":97,"./forEachAccumulated":111}],21:[function(require,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. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = typeof window !== 'undefined'; /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && (window.addEventListener || window.attachEvent), isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],22:[function(require,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. * * @providesModule LinkedStateMixin * @typechecks static-only */ "use strict"; var ReactLink = require("./ReactLink"); var ReactStateSetters = require("./ReactStateSetters"); /** * A simple mixin around ReactLink.forState(). */ var LinkedStateMixin = { /** * Create a ReactLink that's linked to part of this component's state. The * ReactLink will have the current value of this.state[key] and will call * setState() when a change is requested. * * @param {string} key state key to update. Note: you may want to use keyOf() * if you're using Google Closure Compiler advanced mode. * @return {ReactLink} ReactLink instance linking to the state. */ linkState: function(key) { return new ReactLink( this.state[key], ReactStateSetters.createStateKeySetter(this, key) ); } }; module.exports = LinkedStateMixin; },{"./ReactLink":58,"./ReactStateSetters":74}],23:[function(require,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. * * @providesModule LinkedValueUtils * @typechecks static-only */ "use strict"; var ReactPropTypes = require("./ReactPropTypes"); var invariant = require("./invariant"); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(input) { ("production" !== "development" ? invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.' ) : invariant(input.props.checkedLink == null || input.props.valueLink == null)); } function _assertValueLink(input) { _assertSingleLink(input); ("production" !== "development" ? invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.' ) : invariant(input.props.value == null && input.props.onChange == null)); } function _assertCheckedLink(input) { _assertSingleLink(input); ("production" !== "development" ? invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink' ) : invariant(input.props.checked == null && input.props.onChange == null)); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedValueChange(e) { /*jshint validthis:true */ this.props.valueLink.requestChange(e.target.value); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { Mixin: { propTypes: { value: function(props, propName, componentName) { if ("production" !== "development") { if (props[propName] && !hasReadOnlyValue[props.type] && !props.onChange && !props.readOnly && !props.disabled) { console.warn( '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(props, propName, componentName) { if ("production" !== "development") { if (props[propName] && !props.onChange && !props.readOnly && !props.disabled) { console.warn( '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: ReactPropTypes.func } }, /** * @param {ReactComponent} input Form component * @return {*} current value of the input either from value prop or link. */ getValue: function(input) { if (input.props.valueLink) { _assertValueLink(input); return input.props.valueLink.value; } return input.props.value; }, /** * @param {ReactComponent} input Form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { _assertValueLink(input); return _handleLinkedValueChange; } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; } return input.props.onChange; } }; module.exports = LinkedValueUtils; },{"./ReactPropTypes":69,"./invariant":121}],24:[function(require,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. * * @providesModule MobileSafariClickEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var emptyFunction = require("./emptyFunction"); var topLevelTypes = EventConstants.topLevelTypes; /** * Mobile Safari does not fire properly bubble click events on non-interactive * elements, which means delegated click listeners do not fire. The workaround * for this bug involves attaching an empty click listener on the target node. * * This particular plugin works around the bug by attaching an empty click * listener on `touchstart` (which does fire on every element). */ var MobileSafariClickEventPlugin = { eventTypes: null, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topTouchStart) { var target = nativeEvent.target; if (target && !target.onclick) { target.onclick = emptyFunction; } } } }; module.exports = MobileSafariClickEventPlugin; },{"./EventConstants":15,"./emptyFunction":108}],25:[function(require,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. * * @providesModule PooledClass */ "use strict"; var invariant = require("./invariant"); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function(a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function(a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fiveArgumentPooler = function(a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function(instance) { var Klass = this; ("production" !== "development" ? invariant( instance instanceof Klass, 'Trying to release an instance into a pool of a different type.' ) : invariant(instance instanceof Klass)); if (instance.destructor) { instance.destructor(); } if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function(CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"./invariant":121}],26:[function(require,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. * * @providesModule React */ "use strict"; var DOMPropertyOperations = require("./DOMPropertyOperations"); var EventPluginUtils = require("./EventPluginUtils"); var ReactChildren = require("./ReactChildren"); var ReactComponent = require("./ReactComponent"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactDOM = require("./ReactDOM"); var ReactDOMComponent = require("./ReactDOMComponent"); var ReactDefaultInjection = require("./ReactDefaultInjection"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var ReactMultiChild = require("./ReactMultiChild"); var ReactPerf = require("./ReactPerf"); var ReactPropTypes = require("./ReactPropTypes"); var ReactServerRendering = require("./ReactServerRendering"); var ReactTextComponent = require("./ReactTextComponent"); var onlyChild = require("./onlyChild"); ReactDefaultInjection.inject(); var React = { Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, only: onlyChild }, DOM: ReactDOM, PropTypes: ReactPropTypes, initializeTouchEvents: function(shouldUseTouch) { EventPluginUtils.useTouchEvents = shouldUseTouch; }, createClass: ReactCompositeComponent.createClass, constructAndRenderComponent: ReactMount.constructAndRenderComponent, constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID, renderComponent: ReactPerf.measure( 'React', 'renderComponent', ReactMount.renderComponent ), renderComponentToString: ReactServerRendering.renderComponentToString, unmountComponentAtNode: ReactMount.unmountComponentAtNode, isValidClass: ReactCompositeComponent.isValidClass, isValidComponent: ReactComponent.isValidComponent, withContext: ReactContext.withContext, __internals: { Component: ReactComponent, CurrentOwner: ReactCurrentOwner, DOMComponent: ReactDOMComponent, DOMPropertyOperations: DOMPropertyOperations, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, MultiChild: ReactMultiChild, TextComponent: ReactTextComponent } }; if ("production" !== "development") { var ExecutionEnvironment = require("./ExecutionEnvironment"); if (ExecutionEnvironment.canUseDOM && window.top === window.self && navigator.userAgent.indexOf('Chrome') > -1) { console.debug( 'Download the React DevTools for a better development experience: ' + 'http://fb.me/react-devtools' ); } } // Version exists only in the open-source version of React, not in Facebook's // internal version. React.version = '0.9.0'; module.exports = React; },{"./DOMPropertyOperations":10,"./EventPluginUtils":19,"./ExecutionEnvironment":21,"./ReactChildren":29,"./ReactComponent":30,"./ReactCompositeComponent":33,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDOM":36,"./ReactDOMComponent":38,"./ReactDefaultInjection":48,"./ReactInstanceHandles":57,"./ReactMount":60,"./ReactMultiChild":62,"./ReactPerf":65,"./ReactPropTypes":69,"./ReactServerRendering":73,"./ReactTextComponent":76,"./onlyChild":136}],27:[function(require,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. * * @typechecks * @providesModule ReactCSSTransitionGroup * @jsx React.DOM */ "use strict"; var React = require("./React"); var ReactTransitionGroup = require("./ReactTransitionGroup"); var ReactCSSTransitionGroupChild = require("./ReactCSSTransitionGroupChild"); var ReactCSSTransitionGroup = React.createClass({displayName: 'ReactCSSTransitionGroup', propTypes: { transitionName: React.PropTypes.string.isRequired, transitionEnter: React.PropTypes.bool, transitionLeave: React.PropTypes.bool }, getDefaultProps: function() { return { transitionEnter: true, transitionLeave: true }; }, _wrapChild: function(child) { // We need to provide this childFactory so that // ReactCSSTransitionGroupChild can receive updates to name, enter, and // leave while it is leaving. return ( ReactCSSTransitionGroupChild( {name:this.props.transitionName, enter:this.props.transitionEnter, leave:this.props.transitionLeave}, child ) ); }, render: function() { return this.transferPropsTo( ReactTransitionGroup( {childFactory:this._wrapChild}, this.props.children ) ); } }); module.exports = ReactCSSTransitionGroup; },{"./React":26,"./ReactCSSTransitionGroupChild":28,"./ReactTransitionGroup":79}],28:[function(require,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. * * @typechecks * @providesModule ReactCSSTransitionGroupChild */ "use strict"; var React = require("./React"); var CSSCore = require("./CSSCore"); var ReactTransitionEvents = require("./ReactTransitionEvents"); var onlyChild = require("./onlyChild"); // We don't remove the element from the DOM until we receive an animationend or // transitionend event. If the user screws up and forgets to add an animation // their node will be stuck in the DOM forever, so we detect if an animation // does not start and if it doesn't, we just call the end listener immediately. var TICK = 17; var NO_EVENT_TIMEOUT = 5000; var noEventListener = null; if ("production" !== "development") { noEventListener = function() { console.warn( 'transition(): tried to perform an animation without ' + 'an animationend or transitionend event after timeout (' + NO_EVENT_TIMEOUT + 'ms). You should either disable this ' + 'transition in JS or add a CSS animation/transition.' ); }; } var ReactCSSTransitionGroupChild = React.createClass({ transition: function(animationType, finishCallback) { var node = this.getDOMNode(); var className = this.props.name + '-' + animationType; var activeClassName = className + '-active'; var noEventTimeout = null; var endListener = function() { if ("production" !== "development") { clearTimeout(noEventTimeout); } CSSCore.removeClass(node, className); CSSCore.removeClass(node, activeClassName); ReactTransitionEvents.removeEndEventListener(node, endListener); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. finishCallback && finishCallback(); }; ReactTransitionEvents.addEndEventListener(node, endListener); CSSCore.addClass(node, className); // Need to do this to actually trigger a transition. this.queueClass(activeClassName); if ("production" !== "development") { noEventTimeout = setTimeout(noEventListener, NO_EVENT_TIMEOUT); } }, queueClass: function(className) { this.classNameQueue.push(className); if (this.props.runNextTick) { this.props.runNextTick(this.flushClassNameQueue); return; } if (!this.timeout) { this.timeout = setTimeout(this.flushClassNameQueue, TICK); } }, flushClassNameQueue: function() { if (this.isMounted()) { this.classNameQueue.forEach( CSSCore.addClass.bind(CSSCore, this.getDOMNode()) ); } this.classNameQueue.length = 0; this.timeout = null; }, componentWillMount: function() { this.classNameQueue = []; }, componentWillUnmount: function() { if (this.timeout) { clearTimeout(this.timeout); } }, componentWillEnter: function(done) { if (this.props.enter) { this.transition('enter', done); } else { done(); } }, componentWillLeave: function(done) { if (this.props.leave) { this.transition('leave', done); } else { done(); } }, render: function() { return onlyChild(this.props.children); } }); module.exports = ReactCSSTransitionGroupChild; },{"./CSSCore":2,"./React":26,"./ReactTransitionEvents":78,"./onlyChild":136}],29:[function(require,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. * * @providesModule ReactChildren */ "use strict"; var PooledClass = require("./PooledClass"); var invariant = require("./invariant"); var traverseAllChildren = require("./traverseAllChildren"); var twoArgumentPooler = PooledClass.twoArgumentPooler; var threeArgumentPooler = PooledClass.threeArgumentPooler; /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.forEachFunction = forEachFunction; this.forEachContext = forEachContext; } PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(traverseContext, child, name, i) { var forEachBookKeeping = traverseContext; forEachBookKeeping.forEachFunction.call( forEachBookKeeping.forEachContext, child, i); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, mapFunction, mapContext) { this.mapResult = mapResult; this.mapFunction = mapFunction; this.mapContext = mapContext; } PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler); function mapSingleChildIntoContext(traverseContext, child, name, i) { var mapBookKeeping = traverseContext; var mapResult = mapBookKeeping.mapResult; var mappedChild = mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i); // We found a component instance ("production" !== "development" ? invariant( !mapResult.hasOwnProperty(name), 'ReactChildren.map(...): Encountered two children with the same key, ' + '`%s`. Children keys must be unique.', name ) : invariant(!mapResult.hasOwnProperty(name))); mapResult[name] = mappedChild; } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * TODO: This may likely break any calls to `ReactChildren.map` that were * previously relying on the fact that we guarded against null children. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var mapResult = {}; var traverseContext = MapBookKeeping.getPooled(mapResult, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); return mapResult; } var ReactChildren = { forEach: forEachChildren, map: mapChildren }; module.exports = ReactChildren; },{"./PooledClass":25,"./invariant":121,"./traverseAllChildren":141}],30:[function(require,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. * * @providesModule ReactComponent */ "use strict"; var ReactComponentEnvironment = require("./ReactComponentEnvironment"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactOwner = require("./ReactOwner"); var ReactUpdates = require("./ReactUpdates"); var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); var merge = require("./merge"); /** * Every React component is in one of these life cycles. */ var ComponentLifeCycle = keyMirror({ /** * Mounted components have a DOM node representation and are capable of * receiving new props. */ MOUNTED: null, /** * Unmounted components are inactive and cannot receive new props. */ UNMOUNTED: null }); /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasExplicitKeyWarning = {}; var ownerHasPropertyWarning = {}; var NUMERIC_PROPERTY_REGEX = /^\d+$/; /** * Warn if the component doesn't have an explicit key assigned to it. * This component is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactComponent} component Component that requires a key. */ function validateExplicitKey(component) { if (component.__keyValidated__ || component.props.key != null) { return; } component.__keyValidated__ = true; // We can't provide friendly warnings for top level components. if (!ReactCurrentOwner.current) { return; } // Name of the component whose render method tried to pass children. var currentName = ReactCurrentOwner.current.constructor.displayName; if (ownerHasExplicitKeyWarning.hasOwnProperty(currentName)) { return; } ownerHasExplicitKeyWarning[currentName] = true; var message = 'Each child in an array should have a unique "key" prop. ' + 'Check the render method of ' + currentName + '.'; if (!component.isOwnedBy(ReactCurrentOwner.current)) { // Name of the component that originally created this child. var childOwnerName = component._owner && component._owner.constructor.displayName; // Usually the current owner is the offender, but if it accepts // children as a property, it may be the creator of the child that's // responsible for assigning it a key. message += ' It was passed a child from ' + childOwnerName + '.'; } message += ' See http://fb.me/react-warning-keys for more information.'; console.warn(message); } /** * Warn if the key is being defined as an object property but has an incorrect * value. * * @internal * @param {string} name Property name of the key. * @param {ReactComponent} component Component that requires a key. */ function validatePropertyKey(name) { if (NUMERIC_PROPERTY_REGEX.test(name)) { // Name of the component whose render method tried to pass children. var currentName = ReactCurrentOwner.current.constructor.displayName; if (ownerHasPropertyWarning.hasOwnProperty(currentName)) { return; } ownerHasPropertyWarning[currentName] = true; console.warn( 'Child objects should have non-numeric keys so ordering is preserved. ' + 'Check the render method of ' + currentName + '. ' + 'See http://fb.me/react-warning-keys for more information.' ); } } /** * Ensure that every component either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {*} component Statically passed child of any type. * @return {boolean} */ function validateChildKeys(component) { if (Array.isArray(component)) { for (var i = 0; i < component.length; i++) { var child = component[i]; if (ReactComponent.isValidComponent(child)) { validateExplicitKey(child); } } } else if (ReactComponent.isValidComponent(component)) { // This component was passed in a valid location. component.__keyValidated__ = true; } else if (component && typeof component === 'object') { for (var name in component) { validatePropertyKey(name, component); } } } /** * Components are the basic units of composition in React. * * Every component accepts a set of keyed input parameters known as "props" that * are initialized by the constructor. Once a component is mounted, the props * can be mutated using `setProps` or `replaceProps`. * * Every component is capable of the following operations: * * `mountComponent` * Initializes the component, renders markup, and registers event listeners. * * `receiveComponent` * Updates the rendered DOM nodes to match the given component. * * `unmountComponent` * Releases any resources allocated by this component. * * Components can also be "owned" by other components. Being owned by another * component means being constructed by that component. This is different from * being the child of a component, which means having a DOM representation that * is a child of the DOM representation of that component. * * @class ReactComponent */ var ReactComponent = { /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ isValidComponent: function(object) { if (!object || !object.type || !object.type.prototype) { return false; } // This is the safer way of duck checking the type of instance this is. // The object can be a generic descriptor but the type property refers to // the constructor and it's prototype can be used to inspect the type that // will actually get mounted. var prototype = object.type.prototype; return ( typeof prototype.mountComponentIntoNode === 'function' && typeof prototype.receiveComponent === 'function' ); }, /** * @internal */ LifeCycle: ComponentLifeCycle, /** * Injected module that provides ability to mutate individual properties. * Injected into the base class because many different subclasses need access * to this. * * @internal */ BackendIDOperations: ReactComponentEnvironment.BackendIDOperations, /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. * * @private */ unmountIDFromEnvironment: ReactComponentEnvironment.unmountIDFromEnvironment, /** * The "image" of a component tree, is the platform specific (typically * serialized) data that represents a tree of lower level UI building blocks. * On the web, this "image" is HTML markup which describes a construction of * low level `div` and `span` nodes. Other platforms may have different * encoding of this "image". This must be injected. * * @private */ mountImageIntoNode: ReactComponentEnvironment.mountImageIntoNode, /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: ReactComponentEnvironment.ReactReconcileTransaction, /** * Base functionality for every ReactComponent constructor. Mixed into the * `ReactComponent` prototype, but exposed statically for easy access. * * @lends {ReactComponent.prototype} */ Mixin: merge(ReactComponentEnvironment.Mixin, { /** * Checks whether or not this component is mounted. * * @return {boolean} True if mounted, false otherwise. * @final * @protected */ isMounted: function() { return this._lifeCycleState === ComponentLifeCycle.MOUNTED; }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public */ setProps: function(partialProps, callback) { // Merge with `_pendingProps` if it exists, otherwise with existing props. this.replaceProps( merge(this._pendingProps || this.props, partialProps), callback ); }, /** * Replaces all of the props. * * @param {object} props New props. * @param {?function} callback Called after props are updated. * @final * @public */ replaceProps: function(props, callback) { ("production" !== "development" ? invariant( this.isMounted(), 'replaceProps(...): Can only update a mounted component.' ) : invariant(this.isMounted())); ("production" !== "development" ? invariant( this._mountDepth === 0, 'replaceProps(...): You called `setProps` or `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(this._mountDepth === 0)); this._pendingProps = props; ReactUpdates.enqueueUpdate(this, callback); }, /** * Base constructor for all React components. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.construct.call(this, ...)`. * * @param {?object} initialProps * @param {*} children * @internal */ construct: function(initialProps, children) { this.props = initialProps || {}; // Record the component responsible for creating this component. this._owner = ReactCurrentOwner.current; // All components start unmounted. this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; this._pendingProps = null; this._pendingCallbacks = null; // Unlike _pendingProps and _pendingCallbacks, we won't use null to // indicate that nothing is pending because it's possible for a component // to have a null owner. Instead, an owner change is pending when // this._owner !== this._pendingOwner. this._pendingOwner = this._owner; // Children can be more than one argument var childrenLength = arguments.length - 1; if (childrenLength === 1) { if ("production" !== "development") { validateChildKeys(children); } this.props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { if ("production" !== "development") { validateChildKeys(arguments[i + 1]); } childArray[i] = arguments[i + 1]; } this.props.children = childArray; } }, /** * Initializes the component, renders markup, and registers event listeners. * * NOTE: This does not insert any nodes into the DOM. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.mountComponent.call(this, ...)`. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy. * @return {?string} Rendered markup to be inserted into the DOM. * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ("production" !== "development" ? invariant( !this.isMounted(), 'mountComponent(%s, ...): Can only mount an unmounted component. ' + 'Make sure to avoid storing components between renders or reusing a ' + 'single component instance in multiple places.', rootID ) : invariant(!this.isMounted())); var props = this.props; if (props.ref != null) { ReactOwner.addComponentAsRefTo(this, props.ref, this._owner); } this._rootNodeID = rootID; this._lifeCycleState = ComponentLifeCycle.MOUNTED; this._mountDepth = mountDepth; // Effectively: return ''; }, /** * Releases any resources allocated by `mountComponent`. * * NOTE: This does not remove any nodes from the DOM. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.unmountComponent.call(this)`. * * @internal */ unmountComponent: function() { ("production" !== "development" ? invariant( this.isMounted(), 'unmountComponent(): Can only unmount a mounted component.' ) : invariant(this.isMounted())); var props = this.props; if (props.ref != null) { ReactOwner.removeComponentAsRefFrom(this, props.ref, this._owner); } ReactComponent.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; }, /** * Given a new instance of this component, updates the rendered DOM nodes * as if that instance was rendered instead. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.receiveComponent.call(this, ...)`. * * @param {object} nextComponent Next set of properties. * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextComponent, transaction) { ("production" !== "development" ? invariant( this.isMounted(), 'receiveComponent(...): Can only update a mounted component.' ) : invariant(this.isMounted())); this._pendingOwner = nextComponent._owner; this._pendingProps = nextComponent.props; this._performUpdateIfNecessary(transaction); }, /** * Call `_performUpdateIfNecessary` within a new transaction. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function() { var transaction = ReactComponent.ReactReconcileTransaction.getPooled(); transaction.perform(this._performUpdateIfNecessary, this, transaction); ReactComponent.ReactReconcileTransaction.release(transaction); }, /** * If `_pendingProps` is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ _performUpdateIfNecessary: function(transaction) { if (this._pendingProps == null) { return; } var prevProps = this.props; var prevOwner = this._owner; this.props = this._pendingProps; this._owner = this._pendingOwner; this._pendingProps = null; this.updateComponent(transaction, prevProps, prevOwner); }, /** * Updates the component's currently mounted representation. * * @param {ReactReconcileTransaction} transaction * @param {object} prevProps * @internal */ updateComponent: function(transaction, prevProps, prevOwner) { var props = this.props; // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. if (this._owner !== prevOwner || props.ref !== prevProps.ref) { if (prevProps.ref != null) { ReactOwner.removeComponentAsRefFrom( this, prevProps.ref, prevOwner ); } // Correct, even if the owner is the same, and only the ref has changed. if (props.ref != null) { ReactOwner.addComponentAsRefTo(this, props.ref, this._owner); } } }, /** * Mounts this component and inserts it into the DOM. * * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup * @final * @internal * @see {ReactMount.renderComponent} */ mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) { var transaction = ReactComponent.ReactReconcileTransaction.getPooled(); transaction.perform( this._mountComponentIntoNode, this, rootID, container, transaction, shouldReuseMarkup ); ReactComponent.ReactReconcileTransaction.release(transaction); }, /** * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup * @final * @private */ _mountComponentIntoNode: function( rootID, container, transaction, shouldReuseMarkup) { var markup = this.mountComponent(rootID, transaction, 0); ReactComponent.mountImageIntoNode(markup, container, shouldReuseMarkup); }, /** * Checks if this component is owned by the supplied `owner` component. * * @param {ReactComponent} owner Component to check. * @return {boolean} True if `owners` owns this component. * @final * @internal */ isOwnedBy: function(owner) { return this._owner === owner; }, /** * Gets another component, that shares the same owner as this one, by ref. * * @param {string} ref of a sibling Component. * @return {?ReactComponent} the actual sibling Component. * @final * @internal */ getSiblingByRef: function(ref) { var owner = this._owner; if (!owner || !owner.refs) { return null; } return owner.refs[ref]; } }) }; module.exports = ReactComponent; },{"./ReactComponentEnvironment":32,"./ReactCurrentOwner":35,"./ReactOwner":64,"./ReactUpdates":80,"./invariant":121,"./keyMirror":127,"./merge":130}],31:[function(require,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. * * @providesModule ReactComponentBrowserEnvironment */ /*jslint evil: true */ "use strict"; var ReactDOMIDOperations = require("./ReactDOMIDOperations"); var ReactMarkupChecksum = require("./ReactMarkupChecksum"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var ReactReconcileTransaction = require("./ReactReconcileTransaction"); var getReactRootElementInContainer = require("./getReactRootElementInContainer"); var invariant = require("./invariant"); var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** * Abstracts away all functionality of `ReactComponent` requires knowledge of * the browser context. */ var ReactComponentBrowserEnvironment = { /** * Mixed into every component instance. */ Mixin: { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function() { ("production" !== "development" ? invariant( this.isMounted(), 'getDOMNode(): A component must be mounted to have a DOM node.' ) : invariant(this.isMounted())); return ReactMount.getNode(this._rootNodeID); } }, ReactReconcileTransaction: ReactReconcileTransaction, BackendIDOperations: ReactDOMIDOperations, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function(rootNodeID) { ReactMount.purgeID(rootNodeID); }, /** * @param {string} markup Markup string to place into the DOM Element. * @param {DOMElement} container DOM Element to insert markup into. * @param {boolean} shouldReuseMarkup Should reuse the existing markup in the * container if possible. */ mountImageIntoNode: ReactPerf.measure( 'ReactComponentBrowserEnvironment', 'mountImageIntoNode', function(markup, container, shouldReuseMarkup) { ("production" !== "development" ? invariant( container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ), 'mountComponentIntoNode(...): Target container is not valid.' ) : invariant(container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ))); if (shouldReuseMarkup) { if (ReactMarkupChecksum.canReuseMarkup( markup, getReactRootElementInContainer(container))) { return; } else { ("production" !== "development" ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); if ("production" !== "development") { console.warn( 'React attempted to use reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server.' ); } } } ("production" !== "development" ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See renderComponentToString() for server rendering.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); // Asynchronously inject markup by ensuring that the container is not in // the document when settings its `innerHTML`. var parent = container.parentNode; if (parent) { var next = container.nextSibling; parent.removeChild(container); container.innerHTML = markup; if (next) { parent.insertBefore(container, next); } else { parent.appendChild(container); } } else { container.innerHTML = markup; } } ) }; module.exports = ReactComponentBrowserEnvironment; },{"./ReactDOMIDOperations":40,"./ReactMarkupChecksum":59,"./ReactMount":60,"./ReactPerf":65,"./ReactReconcileTransaction":71,"./getReactRootElementInContainer":117,"./invariant":121}],32:[function(require,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. * * @providesModule ReactComponentEnvironment */ "use strict"; var ReactComponentBrowserEnvironment = require("./ReactComponentBrowserEnvironment"); var ReactComponentEnvironment = ReactComponentBrowserEnvironment; module.exports = ReactComponentEnvironment; },{"./ReactComponentBrowserEnvironment":31}],33:[function(require,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. * * @providesModule ReactCompositeComponent */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactErrorUtils = require("./ReactErrorUtils"); var ReactOwner = require("./ReactOwner"); var ReactPerf = require("./ReactPerf"); var ReactPropTransferer = require("./ReactPropTransferer"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var ReactUpdates = require("./ReactUpdates"); var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); var merge = require("./merge"); var mixInto = require("./mixInto"); var objMap = require("./objMap"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); /** * Policies that describe methods in `ReactCompositeComponentInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base ReactCompositeComponent class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactCompositeComponent`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will available on the prototype. * * @interface ReactCompositeComponentInterface * @internal */ var ReactCompositeComponentInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(ConvenienceConstructor, displayName) { ConvenienceConstructor.componentConstructor.displayName = displayName; }, mixins: function(ConvenienceConstructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(ConvenienceConstructor, mixins[i]); } } }, childContextTypes: function(ConvenienceConstructor, childContextTypes) { var Constructor = ConvenienceConstructor.componentConstructor; validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); Constructor.childContextTypes = merge( Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(ConvenienceConstructor, contextTypes) { var Constructor = ConvenienceConstructor.componentConstructor; validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.context ); Constructor.contextTypes = merge(Constructor.contextTypes, contextTypes); }, propTypes: function(ConvenienceConstructor, propTypes) { var Constructor = ConvenienceConstructor.componentConstructor; validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); Constructor.propTypes = merge(Constructor.propTypes, propTypes); }, statics: function(ConvenienceConstructor, statics) { mixStaticSpecIntoComponent(ConvenienceConstructor, statics); } }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { ("production" !== "development" ? invariant( typeof typeDef[propName] == 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactCompositeComponent', ReactPropTypeLocationNames[location], propName ) : invariant(typeof typeDef[propName] == 'function')); } } } function validateMethodOverride(proto, name) { var specPolicy = ReactCompositeComponentInterface[name]; // Disallow overriding of base class methods unless explicitly allowed. if (ReactCompositeComponentMixin.hasOwnProperty(name)) { ("production" !== "development" ? invariant( specPolicy === SpecPolicy.OVERRIDE_BASE, 'ReactCompositeComponentInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE)); } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { ("production" !== "development" ? invariant( specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED, 'ReactCompositeComponentInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED)); } } function validateLifeCycleOnReplaceState(instance) { var compositeLifeCycleState = instance._compositeLifeCycleState; ("production" !== "development" ? invariant( instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'replaceState(...): Can only update a mounted or mounting component.' ) : invariant(instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE, 'replaceState(...): Cannot update during an existing state transition ' + '(such as within `render`). This could potentially cause an infinite ' + 'loop so it is forbidden.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE)); ("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, 'replaceState(...): Cannot update while unmounting component. This ' + 'usually means you called setState() on an unmounted component.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING)); } /** * Custom version of `mixInto` which handles policy validation and reserved * specification keys when building `ReactCompositeComponent` classses. */ function mixSpecIntoComponent(ConvenienceConstructor, spec) { ("production" !== "development" ? invariant( !isValidClass(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(!isValidClass(spec))); ("production" !== "development" ? invariant( !ReactComponent.isValidComponent(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactComponent.isValidComponent(spec))); var Constructor = ConvenienceConstructor.componentConstructor; var proto = Constructor.prototype; for (var name in spec) { var property = spec[name]; if (!spec.hasOwnProperty(name)) { continue; } validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](ConvenienceConstructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactCompositeComponent methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isCompositeComponentMethod = name in ReactCompositeComponentInterface; var isInherited = name in proto; var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isCompositeComponentMethod && !isInherited && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isInherited) { // For methods which are defined more than once, call the existing // methods before calling the new property. if (ReactCompositeComponentInterface[name] === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; } } } } } function mixStaticSpecIntoComponent(ConvenienceConstructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name) || !property) { return; } var isInherited = name in ConvenienceConstructor; var result = property; if (isInherited) { var existingProperty = ConvenienceConstructor[name]; var existingType = typeof existingProperty; var propertyType = typeof property; ("production" !== "development" ? invariant( existingType === 'function' && propertyType === 'function', 'ReactCompositeComponent: You are attempting to define ' + '`%s` on your component more than once, but that is only supported ' + 'for functions, which are chained together. This conflict may be ' + 'due to a mixin.', name ) : invariant(existingType === 'function' && propertyType === 'function')); result = createChainedFunction(existingProperty, property); } ConvenienceConstructor[name] = result; ConvenienceConstructor.componentConstructor[name] = result; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeObjectsWithNoDuplicateKeys(one, two) { ("production" !== "development" ? invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects' ) : invariant(one && two && typeof one === 'object' && typeof two === 'object')); objMap(two, function(value, key) { ("production" !== "development" ? invariant( one[key] === undefined, 'mergeObjectsWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: %s', key ) : invariant(one[key] === undefined)); one[key] = value; }); return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } return mergeObjectsWithNoDuplicateKeys(a, b); }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } if ("production" !== "development") { var unmountedPropertyWhitelist = { constructor: true, construct: true, isOwnedBy: true, // should be deprecated but can have code mod (internal) mountComponent: true, mountComponentIntoNode: true, props: true, type: true, _checkPropTypes: true, _mountComponentIntoNode: true, _processContext: true }; var hasWarnedOnComponentType = {}; var warnIfUnmounted = function(instance, key) { if (instance.__hasBeenMounted) { return; } var name = instance.constructor.displayName || 'Unknown'; var owner = ReactCurrentOwner.current; var ownerName = (owner && owner.constructor.displayName) || 'Unknown'; var warningKey = key + '|' + name + '|' + ownerName; if (hasWarnedOnComponentType.hasOwnProperty(warningKey)) { // We have already warned for this combination. Skip it this time. return; } hasWarnedOnComponentType[warningKey] = true; var context = owner ? ' in ' + ownerName + '.' : ' at the top level.'; var staticMethodExample = '<' + name + ' />.type.' + key + '(...)'; console.warn( 'Invalid access to component property "' + key + '" on ' + name + context + ' See http://fb.me/react-warning-descriptors .' + ' Use a static method instead: ' + staticMethodExample ); }; var defineMembraneProperty = function(membrane, prototype, key) { Object.defineProperty(membrane, key, { configurable: false, enumerable: true, get: function() { if (this !== membrane) { // When this is accessed through a prototype chain we need to check if // this component was mounted. warnIfUnmounted(this, key); } return prototype[key]; }, set: function(value) { if (this !== membrane) { // When this is accessed through a prototype chain, we first check if // this component was mounted. Then we define a value on "this" // instance, effectively disabling the membrane on that prototype // chain. warnIfUnmounted(this, key); Object.defineProperty(this, key, { enumerable: true, configurable: true, writable: true, value: value }); } else { // Otherwise, this should modify the prototype prototype[key] = value; } } }); }; /** * Creates a membrane prototype which wraps the original prototype. If any * property is accessed in an unmounted state, a warning is issued. * * @param {object} prototype Original prototype. * @return {object} The membrane prototype. * @private */ var createMountWarningMembrane = function(prototype) { try { var membrane = Object.create(prototype); for (var key in prototype) { if (unmountedPropertyWhitelist.hasOwnProperty(key)) { continue; } defineMembraneProperty(membrane, prototype, key); } membrane.mountComponent = function() { this.__hasBeenMounted = true; return prototype.mountComponent.apply(this, arguments); }; return membrane; } catch(x) { // In IE8 define property will fail on non-DOM objects. If anything in // the membrane creation fails, we'll bail out and just use the prototype // without warnings. return prototype; } }; } /** * `ReactCompositeComponent` maintains an auxiliary life cycle state in * `this._compositeLifeCycleState` (which can be null). * * This is different from the life cycle state maintained by `ReactComponent` in * `this._lifeCycleState`. The following diagram shows how the states overlap in * time. There are times when the CompositeLifeCycle is null - at those times it * is only meaningful to look at ComponentLifeCycle alone. * * Top Row: ReactComponent.ComponentLifeCycle * Low Row: ReactComponent.CompositeLifeCycle * * +-------+------------------------------------------------------+--------+ * | UN | MOUNTED | UN | * |MOUNTED| | MOUNTED| * +-------+------------------------------------------------------+--------+ * | ^--------+ +------+ +------+ +------+ +--------^ | * | | | | | | | | | | | | * | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 | * | | | |PROPS | | PROPS| | STATE| |MOUNTING| | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +--------+ +------+ +------+ +------+ +--------+ | * | | | | * +-------+------------------------------------------------------+--------+ */ var CompositeLifeCycle = keyMirror({ /** * Components in the process of being mounted respond to state changes * differently. */ MOUNTING: null, /** * Components in the process of being unmounted are guarded against state * changes. */ UNMOUNTING: null, /** * Components that are mounted and receiving new props respond to state * changes differently. */ RECEIVING_PROPS: null, /** * Components that are mounted and receiving new state are guarded against * additional state changes. */ RECEIVING_STATE: null }); /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {?object} initialProps * @param {*} children * @final * @internal */ construct: function(initialProps, children) { // Children can be either an array or more than one argument ReactComponent.Mixin.construct.apply(this, arguments); this.state = null; this._pendingState = null; this.context = this._processContext(ReactContext.current); this._currentContext = ReactContext.current; this._pendingContext = null; this._compositeLifeCycleState = null; }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { return ReactComponent.Mixin.isMounted.call(this) && this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: ReactPerf.measure( 'ReactCompositeComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; this._defaultProps = this.getDefaultProps ? this.getDefaultProps() : null; this.props = this._processProps(this.props); if (this.__reactAutoBindMap) { this._bindAutoBindMethods(); } this.state = this.getInitialState ? this.getInitialState() : null; ("production" !== "development" ? invariant( typeof this.state === 'object' && !Array.isArray(this.state), '%s.getInitialState(): must return an object or null', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof this.state === 'object' && !Array.isArray(this.state))); this._pendingState = null; this._pendingForceUpdate = false; if (this.componentWillMount) { this.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingState` without triggering a re-render. if (this._pendingState) { this.state = this._pendingState; this._pendingState = null; } } this._renderedComponent = this._renderValidatedComponent(); // Done with mounting, `setState` will now trigger UI changes. this._compositeLifeCycleState = null; var markup = this._renderedComponent.mountComponent( rootID, transaction, mountDepth + 1 ); if (this.componentDidMount) { transaction.getReactMountReady().enqueue(this, this.componentDidMount); } return markup; } ), /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function() { this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING; if (this.componentWillUnmount) { this.componentWillUnmount(); } this._compositeLifeCycleState = null; this._defaultProps = null; this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); if (this.refs) { this.refs = null; } // Some existing components rely on this.props even after they've been // destroyed (in event handlers). // TODO: this.props = null; // TODO: this.state = null; }, /** * Sets a subset of the state. Always use this or `replaceState` to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after state is updated. * @final * @protected */ setState: function(partialState, callback) { ("production" !== "development" ? invariant( typeof partialState === 'object' || partialState == null, 'setState(...): takes an object of state variables to update.' ) : invariant(typeof partialState === 'object' || partialState == null)); if ("production" !== "development") { if (partialState == null) { console.warn( 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ); } } // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( merge(this._pendingState || this.state, partialState), callback ); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {object} completeState Next state. * @param {?function} callback Called after state is updated. * @final * @protected */ replaceState: function(completeState, callback) { validateLifeCycleOnReplaceState(this); this._pendingState = completeState; ReactUpdates.enqueueUpdate(this, callback); }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function(context) { var maskedContext = null; var contextTypes = this.constructor.contextTypes; if (contextTypes) { maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } if ("production" !== "development") { this._checkPropTypes( contextTypes, maskedContext, ReactPropTypeLocations.context ); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function(currentContext) { var childContext = this.getChildContext && this.getChildContext(); var displayName = this.constructor.displayName || 'ReactCompositeComponent'; if (childContext) { ("production" !== "development" ? invariant( typeof this.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', displayName ) : invariant(typeof this.constructor.childContextTypes === 'object')); if ("production" !== "development") { this._checkPropTypes( this.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { ("production" !== "development" ? invariant( name in this.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', displayName, name ) : invariant(name in this.constructor.childContextTypes)); } return merge(currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { var props = merge(newProps); var defaultProps = this._defaultProps; for (var propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } if ("production" !== "development") { var propTypes = this.constructor.propTypes; if (propTypes) { this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop); } } return props; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { var componentName = this.constructor.displayName; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { propTypes[propName](props, propName, componentName, location); } } }, performUpdateIfNecessary: function() { var compositeLifeCycleState = this._compositeLifeCycleState; // Do not trigger a state transition if we are in the middle of mounting or // receiving props because both of those will already be doing this. if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING || compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) { return; } ReactComponent.Mixin.performUpdateIfNecessary.call(this); }, /** * If any of `_pendingProps`, `_pendingState`, or `_pendingForceUpdate` is * set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ _performUpdateIfNecessary: function(transaction) { if (this._pendingProps == null && this._pendingState == null && this._pendingContext == null && !this._pendingForceUpdate) { return; } var nextFullContext = this._pendingContext || this._currentContext; var nextContext = this._processContext(nextFullContext); this._pendingContext = null; var nextProps = this.props; if (this._pendingProps != null) { nextProps = this._processProps(this._pendingProps); this._pendingProps = null; this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS; if (this.componentWillReceiveProps) { this.componentWillReceiveProps(nextProps, nextContext); } } this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE; // Unlike props, state, and context, we specifically don't want to set // _pendingOwner to null here because it's possible for a component to have // a null owner, so we instead make `this._owner === this._pendingOwner` // mean that there's no owner change pending. var nextOwner = this._pendingOwner; var nextState = this._pendingState || this.state; this._pendingState = null; try { if (this._pendingForceUpdate || !this.shouldComponentUpdate || this.shouldComponentUpdate(nextProps, nextState, nextContext)) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( nextProps, nextOwner, nextState, nextFullContext, nextContext, transaction ); } else { // If it's determined that a component should not update, we still want // to set props and state. this.props = nextProps; this._owner = nextOwner; this.state = nextState; this._currentContext = nextFullContext; this.context = nextContext; } } finally { this._compositeLifeCycleState = null; } }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {object} nextProps Next object to set as properties. * @param {?ReactComponent} nextOwner Next component to set as owner * @param {?object} nextState Next object to set as state. * @param {?object} nextFullContext Next object to set as _currentContext. * @param {?object} nextContext Next object to set as context. * @param {ReactReconcileTransaction} transaction * @private */ _performComponentUpdate: function( nextProps, nextOwner, nextState, nextFullContext, nextContext, transaction ) { var prevProps = this.props; var prevOwner = this._owner; var prevState = this.state; var prevContext = this.context; if (this.componentWillUpdate) { this.componentWillUpdate(nextProps, nextState, nextContext); } this.props = nextProps; this._owner = nextOwner; this.state = nextState; this._currentContext = nextFullContext; this.context = nextContext; this.updateComponent( transaction, prevProps, prevOwner, prevState, prevContext ); if (this.componentDidUpdate) { transaction.getReactMountReady().enqueue( this, this.componentDidUpdate.bind(this, prevProps, prevState, prevContext) ); } }, receiveComponent: function(nextComponent, transaction) { if (nextComponent === this) { // Since props and context are immutable after the component is // mounted, we can do a cheap identity compare here to determine // if this is a superfluous reconcile. return; } this._pendingContext = nextComponent._currentContext; ReactComponent.Mixin.receiveComponent.call( this, nextComponent, transaction ); }, /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {object} prevProps * @param {?ReactComponent} prevOwner * @param {?object} prevState * @param {?object} prevContext * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactCompositeComponent', 'updateComponent', function(transaction, prevProps, prevOwner, prevState, prevContext) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevProps, prevOwner ); var prevComponent = this._renderedComponent; var nextComponent = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevComponent, nextComponent)) { prevComponent.receiveComponent(nextComponent, transaction); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponent._rootNodeID; prevComponent.unmountComponent(); this._renderedComponent = nextComponent; var nextMarkup = nextComponent.mountComponent( thisID, transaction, this._mountDepth + 1 ); ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID( prevComponentID, nextMarkup ); } } ), /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldUpdateComponent`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ forceUpdate: function(callback) { var compositeLifeCycleState = this._compositeLifeCycleState; ("production" !== "development" ? invariant( this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'forceUpdate(...): Can only force an update on mounted or mounting ' + 'components.' ) : invariant(this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== "development" ? invariant( compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, 'forceUpdate(...): Cannot force an update while unmounting component ' + 'or during an existing state transition (such as within `render`).' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING)); this._pendingForceUpdate = true; ReactUpdates.enqueueUpdate(this, callback); }, /** * @private */ _renderValidatedComponent: ReactPerf.measure( 'ReactCompositeComponent', '_renderValidatedComponent', function() { var renderedComponent; var previousContext = ReactContext.current; ReactContext.current = this._processChildContext(this._currentContext); ReactCurrentOwner.current = this; try { renderedComponent = this.render(); } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== "development" ? invariant( ReactComponent.isValidComponent(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned null, undefined, an array, or some other invalid object.', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(ReactComponent.isValidComponent(renderedComponent))); return renderedComponent; } ), /** * @private */ _bindAutoBindMethods: function() { for (var autoBindKey in this.__reactAutoBindMap) { if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { continue; } var method = this.__reactAutoBindMap[autoBindKey]; this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard( method, this.constructor.displayName + '.' + autoBindKey )); } }, /** * Binds a method to the component. * * @param {function} method Method to be bound. * @private */ _bindAutoBindMethod: function(method) { var component = this; var boundMethod = function() { return method.apply(component, arguments); }; if ("production" !== "development") { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1); // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { console.warn( 'bind(): React component methods may only be bound to the ' + 'component instance. See ' + componentName ); } else if (!args.length) { console.warn( 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See ' + componentName ); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } }; var ReactCompositeComponentBase = function() {}; mixInto(ReactCompositeComponentBase, ReactComponent.Mixin); mixInto(ReactCompositeComponentBase, ReactOwner.Mixin); mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin); mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin); /** * Checks if a value is a valid component constructor. * * @param {*} * @return {boolean} * @public */ function isValidClass(componentClass) { return componentClass instanceof Function && 'componentConstructor' in componentClass && componentClass.componentConstructor instanceof Function; } /** * Module for creating composite components. * * @class ReactCompositeComponent * @extends ReactComponent * @extends ReactOwner * @extends ReactPropTransferer */ var ReactCompositeComponent = { LifeCycle: CompositeLifeCycle, Base: ReactCompositeComponentBase, /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function() {}; Constructor.prototype = new ReactCompositeComponentBase(); Constructor.prototype.constructor = Constructor; var ConvenienceConstructor = function(props, children) { var instance = new Constructor(); instance.construct.apply(instance, arguments); return instance; }; ConvenienceConstructor.componentConstructor = Constructor; Constructor.ConvenienceConstructor = ConvenienceConstructor; ConvenienceConstructor.originalSpec = spec; mixSpecIntoComponent(ConvenienceConstructor, spec); ("production" !== "development" ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== "development") { if (Constructor.prototype.componentShouldUpdate) { console.warn( (spec.displayName || 'A component') + ' has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.' ); } } // Expose the convience constructor on the prototype so that it can be // easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for // static methods like <Foo />.type.staticMethod(); // This should not be named constructor since this may not be the function // that created the descriptor, and it may not even be a constructor. ConvenienceConstructor.type = Constructor; Constructor.prototype.type = Constructor; // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactCompositeComponentInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } if ("production" !== "development") { Constructor.prototype = createMountWarningMembrane(Constructor.prototype); } return ConvenienceConstructor; }, isValidClass: isValidClass }; module.exports = ReactCompositeComponent; },{"./ReactComponent":30,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactErrorUtils":51,"./ReactOwner":64,"./ReactPerf":65,"./ReactPropTransferer":66,"./ReactPropTypeLocationNames":67,"./ReactPropTypeLocations":68,"./ReactUpdates":80,"./invariant":121,"./keyMirror":127,"./merge":130,"./mixInto":133,"./objMap":134,"./shouldUpdateReactComponent":139}],34:[function(require,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. * * @providesModule ReactContext */ "use strict"; var merge = require("./merge"); /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: {}, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'} () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { var result; var previousContext = ReactContext.current; ReactContext.current = merge(previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; },{"./merge":130}],35:[function(require,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. * * @providesModule ReactCurrentOwner */ "use strict"; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],36:[function(require,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. * * @providesModule ReactDOM * @typechecks static-only */ "use strict"; var ReactDOMComponent = require("./ReactDOMComponent"); var mergeInto = require("./mergeInto"); var objMapKeyVal = require("./objMapKeyVal"); /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @param {string} tag Tag name (e.g. `div`). * @param {boolean} omitClose True if the close tag should be omitted. * @private */ function createDOMComponentClass(tag, omitClose) { var Constructor = function() {}; Constructor.prototype = new ReactDOMComponent(tag, omitClose); Constructor.prototype.constructor = Constructor; Constructor.displayName = tag; var ConvenienceConstructor = function(props, children) { var instance = new Constructor(); instance.construct.apply(instance, arguments); return instance; }; // Expose the constructor on the ConvenienceConstructor and prototype so that // it can be easily easily accessed on descriptors. // E.g. <div />.type === div.type ConvenienceConstructor.type = Constructor; Constructor.prototype.type = Constructor; Constructor.ConvenienceConstructor = ConvenienceConstructor; ConvenienceConstructor.componentConstructor = Constructor; return ConvenienceConstructor; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOM = objMapKeyVal({ a: false, abbr: false, address: false, area: false, article: false, aside: false, audio: false, b: false, base: false, bdi: false, bdo: false, big: false, blockquote: false, body: false, br: true, button: false, canvas: false, caption: false, cite: false, code: false, col: true, colgroup: false, data: false, datalist: false, dd: false, del: false, details: false, dfn: false, div: false, dl: false, dt: false, em: false, embed: true, fieldset: false, figcaption: false, figure: false, footer: false, form: false, // NOTE: Injected, see `ReactDOMForm`. h1: false, h2: false, h3: false, h4: false, h5: false, h6: false, head: false, header: false, hr: true, html: false, i: false, iframe: false, img: true, input: true, ins: false, kbd: false, keygen: true, label: false, legend: false, li: false, link: false, main: false, map: false, mark: false, menu: false, menuitem: false, // NOTE: Close tag should be omitted, but causes problems. meta: true, meter: false, nav: false, noscript: false, object: false, ol: false, optgroup: false, option: false, output: false, p: false, param: true, pre: false, progress: false, q: false, rp: false, rt: false, ruby: false, s: false, samp: false, script: false, section: false, select: false, small: false, source: false, span: false, strong: false, style: false, sub: false, summary: false, sup: false, table: false, tbody: false, td: false, textarea: false, // NOTE: Injected, see `ReactDOMTextarea`. tfoot: false, th: false, thead: false, time: false, title: false, tr: false, track: true, u: false, ul: false, 'var': false, video: false, wbr: false, // SVG circle: false, defs: false, g: false, line: false, linearGradient: false, path: false, polygon: false, polyline: false, radialGradient: false, rect: false, stop: false, svg: false, text: false }, createDOMComponentClass); var injection = { injectComponentClasses: function(componentClasses) { mergeInto(ReactDOM, componentClasses); } }; ReactDOM.injection = injection; module.exports = ReactDOM; },{"./ReactDOMComponent":38,"./mergeInto":132,"./objMapKeyVal":135}],37:[function(require,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. * * @providesModule ReactDOMButton */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); var keyMirror = require("./keyMirror"); // Store a reference to the <button> `ReactDOMComponent`. var button = ReactDOM.button; var mouseListenerNames = keyMirror({ onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = ReactCompositeComponent.createClass({ displayName: 'ReactDOMButton', mixins: [AutoFocusMixin], render: function() { var props = {}; // Copy the props; except the mouse listeners if we're disabled for (var key in this.props) { if (this.props.hasOwnProperty(key) && (!this.props.disabled || !mouseListenerNames[key])) { props[key] = this.props[key]; } } return button(props, this.props.children); } }); module.exports = ReactDOMButton; },{"./AutoFocusMixin":1,"./ReactCompositeComponent":33,"./ReactDOM":36,"./keyMirror":127}],38:[function(require,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. * * @providesModule ReactDOMComponent * @typechecks static-only */ "use strict"; var CSSPropertyOperations = require("./CSSPropertyOperations"); var DOMProperty = require("./DOMProperty"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactComponent = require("./ReactComponent"); var ReactEventEmitter = require("./ReactEventEmitter"); var ReactMount = require("./ReactMount"); var ReactMultiChild = require("./ReactMultiChild"); var ReactPerf = require("./ReactPerf"); var escapeTextForBrowser = require("./escapeTextForBrowser"); var invariant = require("./invariant"); var keyOf = require("./keyOf"); var merge = require("./merge"); var mixInto = require("./mixInto"); var deleteListener = ReactEventEmitter.deleteListener; var listenTo = ReactEventEmitter.listenTo; var registrationNameModules = ReactEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; var STYLE = keyOf({style: null}); var ELEMENT_NODE_TYPE = 1; /** * @param {?object} props */ function assertValidProps(props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. ("production" !== "development" ? invariant( props.children == null || props.dangerouslySetInnerHTML == null, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.' ) : invariant(props.children == null || props.dangerouslySetInnerHTML == null)); ("production" !== "development" ? invariant( props.style == null || typeof props.style === 'object', 'The `style` prop expects a mapping from style properties to values, ' + 'not a string.' ) : invariant(props.style == null || typeof props.style === 'object')); } function putListener(id, registrationName, listener, transaction) { var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getPutListenerQueue().enqueuePutListener( id, registrationName, listener ); } /** * @constructor ReactDOMComponent * @extends ReactComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag, omitClose) { this._tagOpen = '<' + tag; this._tagClose = omitClose ? '' : '</' + tag + '>'; this.tagName = tag.toUpperCase(); } ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {string} The computed markup. */ mountComponent: ReactPerf.measure( 'ReactDOMComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); assertValidProps(this.props); return ( this._createOpenTagMarkupAndPutListeners(transaction) + this._createContentMarkup(transaction) + this._tagClose ); } ), /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction} transaction * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction) { var props = this.props; var ret = this._tagOpen; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules[propKey]) { putListener(this._rootNodeID, propKey, propValue, transaction); } else { if (propKey === STYLE) { if (propValue) { propValue = props.style = merge(props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); if (markup) { ret += ' ' + markup; } } } var idMarkup = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + idMarkup + '>'; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction} transaction * @return {string} Content markup. */ _createContentMarkup: function(transaction) { // Intentional use of != to avoid catching zero/false. var innerHTML = this.props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof this.props.children] ? this.props.children : null; var childrenToUse = contentToUse != null ? null : this.props.children; if (contentToUse != null) { return escapeTextForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren( childrenToUse, transaction ); return mountImages.join(''); } } return ''; }, receiveComponent: function(nextComponent, transaction) { assertValidProps(nextComponent.props); ReactComponent.Mixin.receiveComponent.call( this, nextComponent, transaction ); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {object} prevProps * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactDOMComponent', 'updateComponent', function(transaction, prevProps, prevOwner) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevProps, prevOwner ); this._updateDOMProperties(prevProps, transaction); this._updateDOMChildren(prevProps, transaction); } ), /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMProperties: function(lastProps, transaction) { var nextProps = this.props; var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[propKey]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } } else if (registrationNameModules[propKey]) { deleteListener(this._rootNodeID, propKey); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.BackendIDOperations.deletePropertyByID( this._rootNodeID, propKey ); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { nextProp = nextProps.style = merge(nextProp); } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && !nextProp.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules[propKey]) { putListener(this._rootNodeID, propKey, nextProp, transaction); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.BackendIDOperations.updatePropertyByID( this._rootNodeID, propKey, nextProp ); } } if (styleUpdates) { ReactComponent.BackendIDOperations.updateStylesByID( this._rootNodeID, styleUpdates ); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMChildren: function(lastProps, transaction) { var nextProps = this.props; var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { ReactComponent.BackendIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function() { this.unmountChildren(); ReactEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponent.Mixin.unmountComponent.call(this); } }; mixInto(ReactDOMComponent, ReactComponent.Mixin); mixInto(ReactDOMComponent, ReactDOMComponent.Mixin); mixInto(ReactDOMComponent, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; },{"./CSSPropertyOperations":4,"./DOMProperty":9,"./DOMPropertyOperations":10,"./ReactComponent":30,"./ReactEventEmitter":52,"./ReactMount":60,"./ReactMultiChild":62,"./ReactPerf":65,"./escapeTextForBrowser":109,"./invariant":121,"./keyOf":128,"./merge":130,"./mixInto":133}],39:[function(require,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. * * @providesModule ReactDOMForm */ "use strict"; var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); var ReactEventEmitter = require("./ReactEventEmitter"); var EventConstants = require("./EventConstants"); // Store a reference to the <form> `ReactDOMComponent`. var form = ReactDOM.form; /** * Since onSubmit doesn't bubble OR capture on the top level in IE8, we need * to capture it on the <form> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <form> a * composite component and use `componentDidMount` to attach the event handlers. */ var ReactDOMForm = ReactCompositeComponent.createClass({ displayName: 'ReactDOMForm', render: function() { // TODO: Instead of using `ReactDOM` directly, we should use JSX. However, // `jshint` fails to parse JSX so in order for linting to work in the open // source repo, we need to just use `ReactDOM.form`. return this.transferPropsTo(form(null, this.props.children)); }, componentDidMount: function() { ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topReset, 'reset', this.getDOMNode() ); ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topSubmit, 'submit', this.getDOMNode() ); } }); module.exports = ReactDOMForm; },{"./EventConstants":15,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEventEmitter":52}],40:[function(require,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. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ /*jslint evil: true */ "use strict"; var CSSPropertyOperations = require("./CSSPropertyOperations"); var DOMChildrenOperations = require("./DOMChildrenOperations"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var invariant = require("./invariant"); /** * Errors for properties that should not be updated with `updatePropertyById()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; var useWhitespaceWorkaround; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactComponent.BackendIDOperations`. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updatePropertyByID', function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== "development" ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } } ), /** * Updates a DOM node to remove a property. This should only be used to remove * DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A property name to remove, see `DOMProperty`. * @internal */ deletePropertyByID: ReactPerf.measure( 'ReactDOMIDOperations', 'deletePropertyByID', function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== "development" ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); DOMPropertyOperations.deleteValueForProperty(node, name, value); } ), /** * Updates a DOM node with new style values. If a value is specified as '', * the corresponding style property will be unset. * * @param {string} id ID of the node to update. * @param {object} styles Mapping from styles to values. * @internal */ updateStylesByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateStylesByID', function(id, styles) { var node = ReactMount.getNode(id); CSSPropertyOperations.setValueForStyles(node, styles); } ), /** * Updates a DOM node's innerHTML. * * @param {string} id ID of the node to update. * @param {string} html An HTML string. * @internal */ updateInnerHTMLByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateInnerHTMLByID', function(id, html) { var node = ReactMount.getNode(id); // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html if (useWhitespaceWorkaround === undefined) { // Feature detection; only IE8 is known to behave improperly like this. var temp = document.createElement('div'); temp.innerHTML = ' '; useWhitespaceWorkaround = temp.innerHTML === ''; } if (useWhitespaceWorkaround) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. node.parentNode.replaceChild(node, node); } if (useWhitespaceWorkaround && html.match(/^[ \r\n\t\f]/)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. node.innerHTML = '\uFEFF' + html; node.firstChild.deleteData(0, 1); } else { node.innerHTML = html; } } ), /** * Updates a DOM node's text content set by `props.content`. * * @param {string} id ID of the node to update. * @param {string} content Text content. * @internal */ updateTextContentByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateTextContentByID', function(id, content) { var node = ReactMount.getNode(id); DOMChildrenOperations.updateTextContent(node, content); } ), /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: ReactPerf.measure( 'ReactDOMIDOperations', 'dangerouslyReplaceNodeWithMarkupByID', function(id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); } ), /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: ReactPerf.measure( 'ReactDOMIDOperations', 'dangerouslyProcessChildrenUpdates', function(updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } ) }; module.exports = ReactDOMIDOperations; },{"./CSSPropertyOperations":4,"./DOMChildrenOperations":8,"./DOMPropertyOperations":10,"./ReactMount":60,"./ReactPerf":65,"./invariant":121}],41:[function(require,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. * * @providesModule ReactDOMImg */ "use strict"; var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); var ReactEventEmitter = require("./ReactEventEmitter"); var EventConstants = require("./EventConstants"); // Store a reference to the <img> `ReactDOMComponent`. var img = ReactDOM.img; /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <img> element itself. There are lots of hacks we could do * to accomplish this, but the most reliable is to make <img> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMImg = ReactCompositeComponent.createClass({ displayName: 'ReactDOMImg', tagName: 'IMG', render: function() { return img(this.props); }, componentDidMount: function() { var node = this.getDOMNode(); ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topLoad, 'load', node ); ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topError, 'error', node ); } }); module.exports = ReactDOMImg; },{"./EventConstants":15,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEventEmitter":52}],42:[function(require,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. * * @providesModule ReactDOMInput */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); var ReactMount = require("./ReactMount"); var invariant = require("./invariant"); var merge = require("./merge"); // Store a reference to the <input> `ReactDOMComponent`. var input = ReactDOM.input; var instancesByReactID = {}; /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = ReactCompositeComponent.createClass({ displayName: 'ReactDOMInput', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin], getInitialState: function() { var defaultValue = this.props.defaultValue; return { checked: this.props.defaultChecked || false, value: defaultValue != null ? defaultValue : null }; }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onChange` handler. return !this._isChanging; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = merge(this.props); props.defaultChecked = null; props.defaultValue = null; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.value; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.checked; props.onChange = this._handleChange; return input(props, this.props.children); }, componentDidMount: function() { var id = ReactMount.getID(this.getDOMNode()); instancesByReactID[id] = this; }, componentWillUnmount: function() { var rootNode = this.getDOMNode(); var id = ReactMount.getID(rootNode); delete instancesByReactID[id]; }, componentDidUpdate: function(prevProps, prevState, prevContext) { var rootNode = this.getDOMNode(); if (this.props.checked != null) { DOMPropertyOperations.setValueForProperty( rootNode, 'checked', this.props.checked || false ); } var value = LinkedValueUtils.getValue(this); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { this._isChanging = true; returnValue = onChange.call(this, event); this._isChanging = false; } this.setState({ checked: event.target.checked, value: event.target.value }); var name = this.props.name; if (this.props.type === 'radio' && name != null) { var rootNode = this.getDOMNode(); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll( 'input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0, groupLen = group.length; i < groupLen; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherID = ReactMount.getID(otherNode); ("production" !== "development" ? invariant( otherID, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.' ) : invariant(otherID)); var otherInstance = instancesByReactID[otherID]; ("production" !== "development" ? invariant( otherInstance, 'ReactDOMInput: Unknown radio button ID %s.', otherID ) : invariant(otherInstance)); // In some cases, this will actually change the `checked` state value. // In other cases, there's no change but this forces a reconcile upon // which componentDidUpdate will reset the DOM property to whatever it // should be. otherInstance.setState({ checked: false }); } } return returnValue; } }); module.exports = ReactDOMInput; },{"./AutoFocusMixin":1,"./DOMPropertyOperations":10,"./LinkedValueUtils":23,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactMount":60,"./invariant":121,"./merge":130}],43:[function(require,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. * * @providesModule ReactDOMOption */ "use strict"; var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); // Store a reference to the <option> `ReactDOMComponent`. var option = ReactDOM.option; /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = ReactCompositeComponent.createClass({ displayName: 'ReactDOMOption', componentWillMount: function() { // TODO (yungsters): Remove support for `selected` in <option>. if (this.props.selected != null) { if ("production" !== "development") { console.warn( 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ); } } }, render: function() { return option(this.props, this.props.children); } }); module.exports = ReactDOMOption; },{"./ReactCompositeComponent":33,"./ReactDOM":36}],44:[function(require,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. * * @providesModule ReactDOMSelect */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); var invariant = require("./invariant"); var merge = require("./merge"); // Store a reference to the <select> `ReactDOMComponent`. var select = ReactDOM.select; /** * Validation function for `value` and `defaultValue`. * @private */ function selectValueType(props, propName, componentName) { if (props[propName] == null) { return; } if (props.multiple) { ("production" !== "development" ? invariant( Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if `multiple` is ' + 'true.', propName ) : invariant(Array.isArray(props[propName]))); } else { ("production" !== "development" ? invariant( !Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar value if ' + '`multiple` is false.', propName ) : invariant(!Array.isArray(props[propName]))); } } /** * If `value` is supplied, updates <option> elements on mount and update. * @param {ReactComponent} component Instance of ReactDOMSelect * @param {?*} propValue For uncontrolled components, null/undefined. For * controlled components, a string (or with `multiple`, a list of strings). * @private */ function updateOptions(component, propValue) { var multiple = component.props.multiple; var value = propValue != null ? propValue : component.state.value; var options = component.getDOMNode().options; var selectedValue, i, l; if (multiple) { selectedValue = {}; for (i = 0, l = value.length; i < l; ++i) { selectedValue['' + value[i]] = true; } } else { selectedValue = '' + value; } for (i = 0, l = options.length; i < l; i++) { var selected = multiple ? selectedValue.hasOwnProperty(options[i].value) : options[i].value === selectedValue; if (selected !== options[i].selected) { options[i].selected = selected; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * string. If `multiple` is true, the prop must be an array of strings. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = ReactCompositeComponent.createClass({ displayName: 'ReactDOMSelect', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin], propTypes: { defaultValue: selectValueType, value: selectValueType }, getInitialState: function() { return {value: this.props.defaultValue || (this.props.multiple ? [] : '')}; }, componentWillReceiveProps: function(nextProps) { if (!this.props.multiple && nextProps.multiple) { this.setState({value: [this.state.value]}); } else if (this.props.multiple && !nextProps.multiple) { this.setState({value: this.state.value[0]}); } }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onChange` handler. return !this._isChanging; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = merge(this.props); props.onChange = this._handleChange; props.value = null; return select(props, this.props.children); }, componentDidMount: function() { updateOptions(this, LinkedValueUtils.getValue(this)); }, componentDidUpdate: function() { var value = LinkedValueUtils.getValue(this); if (value != null) { updateOptions(this, value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { this._isChanging = true; returnValue = onChange.call(this, event); this._isChanging = false; } var selectedValue; if (this.props.multiple) { selectedValue = []; var options = event.target.options; for (var i = 0, l = options.length; i < l; i++) { if (options[i].selected) { selectedValue.push(options[i].value); } } } else { selectedValue = event.target.value; } this.setState({value: selectedValue}); return returnValue; } }); module.exports = ReactDOMSelect; },{"./AutoFocusMixin":1,"./LinkedValueUtils":23,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":121,"./merge":130}],45:[function(require,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. * * @providesModule ReactDOMSelection */ "use strict"; var getNodeForCharacterOffset = require("./getNodeForCharacterOffset"); var getTextContentAccessor = require("./getTextContentAccessor"); /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection(); if (selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); var rangeLength = currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var start = tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; detectionRange.detach(); return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } range.detach(); } } var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: function(node) { var getOffsets = document.selection ? getIEOffsets : getModernOffsets; return getOffsets(node); }, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: function(node, offsets) { var setOffsets = document.selection ? setIEOffsets : setModernOffsets; setOffsets(node, offsets); } }; module.exports = ReactDOMSelection; },{"./getNodeForCharacterOffset":116,"./getTextContentAccessor":118}],46:[function(require,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. * * @providesModule ReactDOMTextarea */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactDOM = require("./ReactDOM"); var invariant = require("./invariant"); var merge = require("./merge"); // Store a reference to the <textarea> `ReactDOMComponent`. var textarea = ReactDOM.textarea; /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = ReactCompositeComponent.createClass({ displayName: 'ReactDOMTextarea', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin], getInitialState: function() { var defaultValue = this.props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = this.props.children; if (children != null) { if ("production" !== "development") { console.warn( 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.' ); } ("production" !== "development" ? invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.' ) : invariant(defaultValue == null)); if (Array.isArray(children)) { ("production" !== "development" ? invariant( children.length <= 1, '<textarea> can only have at most one child.' ) : invariant(children.length <= 1)); children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(this); return { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), value: defaultValue }; }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onChange` handler. return !this._isChanging; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = merge(this.props); var value = LinkedValueUtils.getValue(this); ("production" !== "development" ? invariant( props.dangerouslySetInnerHTML == null, '`dangerouslySetInnerHTML` does not make sense on <textarea>.' ) : invariant(props.dangerouslySetInnerHTML == null)); props.defaultValue = null; props.value = value != null ? value : this.state.value; props.onChange = this._handleChange; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. return textarea(props, this.state.initialValue); }, componentDidUpdate: function(prevProps, prevState, prevContext) { var value = LinkedValueUtils.getValue(this); if (value != null) { var rootNode = this.getDOMNode(); // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { this._isChanging = true; returnValue = onChange.call(this, event); this._isChanging = false; } this.setState({value: event.target.value}); return returnValue; } }); module.exports = ReactDOMTextarea; },{"./AutoFocusMixin":1,"./DOMPropertyOperations":10,"./LinkedValueUtils":23,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":121,"./merge":130}],47:[function(require,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. * * @providesModule ReactDefaultBatchingStrategy */ "use strict"; var ReactUpdates = require("./ReactUpdates"); var Transaction = require("./Transaction"); var emptyFunction = require("./emptyFunction"); var mixInto = require("./mixInto"); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function() { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } mixInto(ReactDefaultBatchingStrategyTransaction, Transaction.Mixin); mixInto(ReactDefaultBatchingStrategyTransaction, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, param) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(param); } else { transaction.perform(callback, null, param); } } }; module.exports = ReactDefaultBatchingStrategy; },{"./ReactUpdates":80,"./Transaction":95,"./emptyFunction":108,"./mixInto":133}],48:[function(require,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. * * @providesModule ReactDefaultInjection */ "use strict"; var ReactInjection = require("./ReactInjection"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var DefaultDOMPropertyConfig = require("./DefaultDOMPropertyConfig"); var ChangeEventPlugin = require("./ChangeEventPlugin"); var ClientReactRootIndex = require("./ClientReactRootIndex"); var CompositionEventPlugin = require("./CompositionEventPlugin"); var DefaultEventPluginOrder = require("./DefaultEventPluginOrder"); var EnterLeaveEventPlugin = require("./EnterLeaveEventPlugin"); var MobileSafariClickEventPlugin = require("./MobileSafariClickEventPlugin"); var ReactEventTopLevelCallback = require("./ReactEventTopLevelCallback"); var ReactDOM = require("./ReactDOM"); var ReactDOMButton = require("./ReactDOMButton"); var ReactDOMForm = require("./ReactDOMForm"); var ReactDOMImg = require("./ReactDOMImg"); var ReactDOMInput = require("./ReactDOMInput"); var ReactDOMOption = require("./ReactDOMOption"); var ReactDOMSelect = require("./ReactDOMSelect"); var ReactDOMTextarea = require("./ReactDOMTextarea"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var SelectEventPlugin = require("./SelectEventPlugin"); var ServerReactRootIndex = require("./ServerReactRootIndex"); var SimpleEventPlugin = require("./SimpleEventPlugin"); var ReactDefaultBatchingStrategy = require("./ReactDefaultBatchingStrategy"); var createFullPageComponent = require("./createFullPageComponent"); function inject() { ReactInjection.EventEmitter.injectTopLevelCallbackCreator( ReactEventTopLevelCallback ); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, CompositionEventPlugin: CompositionEventPlugin, MobileSafariClickEventPlugin: MobileSafariClickEventPlugin, SelectEventPlugin: SelectEventPlugin }); ReactInjection.DOM.injectComponentClasses({ button: ReactDOMButton, form: ReactDOMForm, img: ReactDOMImg, input: ReactDOMInput, option: ReactDOMOption, select: ReactDOMSelect, textarea: ReactDOMTextarea, html: createFullPageComponent(ReactDOM.html), head: createFullPageComponent(ReactDOM.head), title: createFullPageComponent(ReactDOM.title), body: createFullPageComponent(ReactDOM.body) }); ReactInjection.DOMProperty.injectDOMPropertyConfig(DefaultDOMPropertyConfig); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); if ("production" !== "development") { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = require("./ReactDefaultPerf"); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; },{"./ChangeEventPlugin":5,"./ClientReactRootIndex":6,"./CompositionEventPlugin":7,"./DefaultDOMPropertyConfig":12,"./DefaultEventPluginOrder":13,"./EnterLeaveEventPlugin":14,"./ExecutionEnvironment":21,"./MobileSafariClickEventPlugin":24,"./ReactDOM":36,"./ReactDOMButton":37,"./ReactDOMForm":39,"./ReactDOMImg":41,"./ReactDOMInput":42,"./ReactDOMOption":43,"./ReactDOMSelect":44,"./ReactDOMTextarea":46,"./ReactDefaultBatchingStrategy":47,"./ReactDefaultPerf":49,"./ReactEventTopLevelCallback":54,"./ReactInjection":55,"./ReactInstanceHandles":57,"./ReactMount":60,"./SelectEventPlugin":82,"./ServerReactRootIndex":83,"./SimpleEventPlugin":84,"./createFullPageComponent":103}],49:[function(require,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. * * @providesModule ReactDefaultPerf * @typechecks static-only */ "use strict"; var DOMProperty = require("./DOMProperty"); var ReactDefaultPerfAnalysis = require("./ReactDefaultPerfAnalysis"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var performanceNow = require("./performanceNow"); function roundFloat(val) { return Math.floor(val * 100) / 100; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _injected: false, start: function() { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function() { ReactPerf.enableMeasure = false; }, getLastMeasurements: function() { return ReactDefaultPerf._allMeasurements; }, printExclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Total exclusive time (ms)': roundFloat(item.exclusive), 'Exclusive time per instance (ms)': roundFloat(item.exclusive / item.count), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printInclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printWasted: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary( measurements, true ); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printDOM: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function(item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result['type'] = item.type; result['args'] = JSON.stringify(item.args); return result; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, _recordWrite: function(id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf ._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1] .writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function(moduleName, fnName, func) { return function() {var args=Array.prototype.slice.call(arguments,0); var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0 }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ].totalTime = performanceNow() - start; return rv; } else if (moduleName === 'ReactDOMIDOperations' || moduleName === 'ReactComponentBrowserEnvironment') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === 'mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function(update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite( update.parentID, update.type, totalTime, writeArgs ); }); } else { // basic format ReactDefaultPerf._recordWrite( args[0], fnName, totalTime, Array.prototype.slice.call(args, 1) ); } return rv; } else if (moduleName === 'ReactCompositeComponent' && ( fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var entry = ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ]; if (isRender) { entry.counts[rootNodeID] = entry.counts[rootNodeID] || 0; entry.counts[rootNodeID] += 1; } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; var typeOfLog = isRender ? entry.exclusive : entry.inclusive; typeOfLog[rootNodeID] = typeOfLog[rootNodeID] || 0; typeOfLog[rootNodeID] += totalTime; entry.displayNames[rootNodeID] = { current: this.constructor.displayName, owner: this._owner ? this._owner.constructor.displayName : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; },{"./DOMProperty":9,"./ReactDefaultPerfAnalysis":50,"./ReactMount":60,"./ReactPerf":65,"./performanceNow":137}],50:[function(require,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. * * @providesModule ReactDefaultPerfAnalysis */ var merge = require("./merge"); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { 'mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', TEXT_CONTENT: 'set textContent', 'updatePropertyByID': 'update attribute', 'deletePropertyByID': 'delete attribute', 'updateStylesByID': 'update styles', 'updateInnerHTMLByID': 'set innerHTML', 'dangerouslyReplaceNodeWithMarkupByID': 'replace' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var id; for (id in measurement.writes) { measurement.writes[id].forEach(function(write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); } } return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = merge(measurement.exclusive, measurement.inclusive); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, count: 0 }; if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function(a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = merge(measurement.exclusive, measurement.inclusive); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function(a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = merge(measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggerd // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; },{"./merge":130}],51:[function(require,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. * * @providesModule ReactErrorUtils * @typechecks */ "use strict"; var ReactErrorUtils = { /** * Creates a guarded version of a function. This is supposed to make debugging * of event handlers easier. To aid debugging with the browser's debugger, * this currently simply returns the original function. * * @param {function} func Function to be executed * @param {string} name The name of the guard * @return {function} */ guard: function(func, name) { return func; } }; module.exports = ReactErrorUtils; },{}],52:[function(require,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. * * @providesModule ReactEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventListener = require("./EventListener"); var EventPluginHub = require("./EventPluginHub"); var EventPluginRegistry = require("./EventPluginRegistry"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var ReactEventEmitterMixin = require("./ReactEventEmitterMixin"); var ViewportMetrics = require("./ViewportMetrics"); var invariant = require("./invariant"); var isEventSupported = require("./isEventSupported"); var merge = require("./merge"); /** * Summary of `ReactEventEmitter` event handling: * * - Top-level delegation is used to trap native browser events. We normalize * and de-duplicate events to account for browser quirks. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * . * +------------+ . * | DOM | . * +------------+ . +-----------+ * + . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', 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', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { if (mountAt[topListenersIDKey] == null) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {DOMEventTarget} element Element on which to attach listener. * @internal */ function trapBubbledEvent(topLevelType, handlerBaseName, element) { EventListener.listen( element, handlerBaseName, ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( topLevelType ) ); } /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {DOMEventTarget} element Element on which to attach listener. * @internal */ function trapCapturedEvent(topLevelType, handlerBaseName, element) { EventListener.capture( element, handlerBaseName, ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( topLevelType ) ); } /** * `ReactEventEmitter` is used to attach top-level event listeners. For example: * * ReactEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactEventEmitter = merge(ReactEventEmitterMixin, { /** * React references `ReactEventTopLevelCallback` using this property in order * to allow dependency injection. */ TopLevelCallbackCreator: null, injection: { /** * @param {function} TopLevelCallbackCreator */ injectTopLevelCallbackCreator: function(TopLevelCallbackCreator) { ReactEventEmitter.TopLevelCallbackCreator = TopLevelCallbackCreator; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'setEnabled(...): Cannot toggle event listening in a Worker thread. ' + 'This is likely a bug in the framework. Please report immediately.' ) : invariant(ExecutionEnvironment.canUseDOM)); if (ReactEventEmitter.TopLevelCallbackCreator) { ReactEventEmitter.TopLevelCallbackCreator.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactEventEmitter.TopLevelCallbackCreator && ReactEventEmitter.TopLevelCallbackCreator.isEnabled() ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {DOMDocument} contentDocument Document which owns the container */ listenTo: function(registrationName, contentDocument) { var mountAt = contentDocument; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!isListening[dependency]) { var topLevelType = topLevelTypes[dependency]; if (topLevelType === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (topLevelType === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { trapBubbledEvent(topLevelTypes.topScroll, 'scroll', window); } } else if (topLevelType === topLevelTypes.topFocus || topLevelType === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping[dependency]) { trapBubbledEvent(topLevelType, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function(){ if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; EventListener.listen(window, 'scroll', refresh); EventListener.listen(window, 'resize', refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners, trapBubbledEvent: trapBubbledEvent, trapCapturedEvent: trapCapturedEvent }); module.exports = ReactEventEmitter; },{"./EventConstants":15,"./EventListener":16,"./EventPluginHub":17,"./EventPluginRegistry":18,"./ExecutionEnvironment":21,"./ReactEventEmitterMixin":53,"./ViewportMetrics":96,"./invariant":121,"./isEventSupported":122,"./merge":130}],53:[function(require,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. * * @providesModule ReactEventEmitterMixin */ "use strict"; var EventPluginHub = require("./EventPluginHub"); var ReactUpdates = require("./ReactUpdates"); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events = EventPluginHub.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); // Event queue being processed in the same cycle allows `preventDefault`. ReactUpdates.batchedUpdates(runEventQueueInBatch, events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":17,"./ReactUpdates":80}],54:[function(require,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. * * @providesModule ReactEventTopLevelCallback * @typechecks static-only */ "use strict"; var PooledClass = require("./PooledClass"); var ReactEventEmitter = require("./ReactEventEmitter"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var getEventTarget = require("./getEventTarget"); var mixInto = require("./mixInto"); /** * @type {boolean} * @private */ var _topLevelListenersEnabled = true; /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } /** * Calls ReactEventEmitter.handleTopLevel for each node stored in bookKeeping's * ancestor list. Separated from createTopLevelCallback to avoid try/finally * deoptimization. * * @param {string} topLevelType * @param {DOMEvent} nativeEvent * @param {TopLevelCallbackBookKeeping} bookKeeping */ function handleTopLevelImpl(topLevelType, nativeEvent, bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM( getEventTarget(nativeEvent) ) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventEmitter.handleTopLevel( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); } } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping() { this.ancestors = []; } mixInto(TopLevelCallbackBookKeeping, { destructor: function() { this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping); /** * Top-level callback creator used to implement event handling using delegation. * This is used via dependency injection. */ var ReactEventTopLevelCallback = { /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { _topLevelListenersEnabled = !!enabled; }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return _topLevelListenersEnabled; }, /** * Creates a callback for the supplied `topLevelType` that could be added as * a listener to the document. The callback computes a `topLevelTarget` which * should be the root node of a mounted React component where the listener * is attached. * * @param {string} topLevelType Record from `EventConstants`. * @return {function} Callback for handling top-level events. */ createTopLevelCallback: function(topLevelType) { return function(nativeEvent) { if (!_topLevelListenersEnabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(); try { handleTopLevelImpl(topLevelType, nativeEvent, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } }; } }; module.exports = ReactEventTopLevelCallback; },{"./PooledClass":25,"./ReactEventEmitter":52,"./ReactInstanceHandles":57,"./ReactMount":60,"./getEventTarget":114,"./mixInto":133}],55:[function(require,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. * * @providesModule ReactInjection */ "use strict"; var DOMProperty = require("./DOMProperty"); var EventPluginHub = require("./EventPluginHub"); var ReactDOM = require("./ReactDOM"); var ReactEventEmitter = require("./ReactEventEmitter"); var ReactPerf = require("./ReactPerf"); var ReactRootIndex = require("./ReactRootIndex"); var ReactUpdates = require("./ReactUpdates"); var ReactInjection = { DOMProperty: DOMProperty.injection, EventPluginHub: EventPluginHub.injection, DOM: ReactDOM.injection, EventEmitter: ReactEventEmitter.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"./DOMProperty":9,"./EventPluginHub":17,"./ReactDOM":36,"./ReactEventEmitter":52,"./ReactPerf":65,"./ReactRootIndex":72,"./ReactUpdates":80}],56:[function(require,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. * * @providesModule ReactInputSelection */ "use strict"; var ReactDOMSelection = require("./ReactDOMSelection"); var containsNode = require("./containsNode"); var getActiveElement = require("./getActiveElement"); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function(elem) { return elem && ( (elem.nodeName === 'INPUT' && elem.type === 'text') || elem.nodeName === 'TEXTAREA' || elem.contentEditable === 'true' ); }, getSelectionInformation: function() { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function(priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection( priorFocusedElem, priorSelectionRange ); } priorFocusedElem.focus(); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function(input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName === 'INPUT') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || {start: 0, end: 0}; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function(input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName === 'INPUT') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"./ReactDOMSelection":45,"./containsNode":100,"./getActiveElement":112}],57:[function(require,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. * * @providesModule ReactInstanceHandles * @typechecks static-only */ "use strict"; var ReactRootIndex = require("./ReactRootIndex"); var invariant = require("./invariant"); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 100; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { ("production" !== "development" ? invariant( isValidID(ancestorID) && isValidID(destinationID), 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID ) : invariant(isValidID(ancestorID) && isValidID(destinationID))); ("production" !== "development" ? invariant( isAncestorIDOf(ancestorID, destinationID), 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID ) : invariant(isAncestorIDOf(ancestorID, destinationID))); if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; for (var i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); ("production" !== "development" ? invariant( isValidID(longestCommonID), 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID ) : invariant(isValidID(longestCommonID))); return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; ("production" !== "development" ? invariant( start !== stop, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start ) : invariant(start !== stop)); var traverseUp = isAncestorIDOf(stop, start); ("production" !== "development" ? invariant( traverseUp || isAncestorIDOf(start, stop), 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop ) : invariant(traverseUp || isAncestorIDOf(start, stop))); // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start; /* until break */; id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } ("production" !== "development" ? invariant( depth++ < MAX_TREE_DEPTH, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop ) : invariant(depth++ < MAX_TREE_DEPTH)); } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function() { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function(rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function(id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function(targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function(targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, /** * Exposed for unit testing. * @private */ _getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; },{"./ReactRootIndex":72,"./invariant":121}],58:[function(require,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. * * @providesModule ReactLink * @typechecks static-only */ "use strict"; /** * ReactLink encapsulates a common pattern in which a component wants to modify * a prop received from its parent. ReactLink allows the parent to pass down a * value coupled with a callback that, when invoked, expresses an intent to * modify that value. For example: * * React.createClass({ * getInitialState: function() { * return {value: ''}; * }, * render: function() { * var valueLink = new ReactLink(this.state.value, this._handleValueChange); * return <input valueLink={valueLink} />; * }, * this._handleValueChange: function(newValue) { * this.setState({value: newValue}); * } * }); * * We have provided some sugary mixins to make the creation and * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. */ /** * @param {*} value current value of the link * @param {function} requestChange callback to request a change */ function ReactLink(value, requestChange) { this.value = value; this.requestChange = requestChange; } module.exports = ReactLink; },{}],59:[function(require,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. * * @providesModule ReactMarkupChecksum */ "use strict"; var adler32 = require("./adler32"); var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function(markup) { var checksum = adler32(markup); return markup.replace( '>', ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '">' ); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function(markup, element) { var existingChecksum = element.getAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME ); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"./adler32":98}],60:[function(require,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. * * @providesModule ReactMount */ "use strict"; var DOMProperty = require("./DOMProperty"); var ReactEventEmitter = require("./ReactEventEmitter"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactPerf = require("./ReactPerf"); var containsNode = require("./containsNode"); var getReactRootElementInContainer = require("./getReactRootElementInContainer"); var invariant = require("./invariant"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if ("production" !== "development") { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { ("production" !== "development" ? invariant( !isValid(cached, id), 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id ) : invariant(!isValid(cached, id))); nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { ("production" !== "development" ? invariant( internalGetID(node) === id, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME ) : invariant(internalGetID(node) === id)); var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors( targetID, findDeepestCachedAncestorImpl ); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounting is the process of initializing a React component by creatings its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.renderComponent( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { /** Time spent generating markup. */ totalInstantiationTime: 0, /** Time spent inserting markup into the DOM. */ totalInjectionTime: 0, /** Whether support for touch events should be initialized. */ useTouchEvents: false, /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function(container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function( prevComponent, nextComponent, container, callback) { var nextProps = nextComponent.props; ReactMount.scrollMonitor(container, function() { prevComponent.replaceProps(nextProps, callback); }); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function(nextComponent, container) { ("production" !== "development" ? invariant( container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ), '_registerComponent(...): Target container is not a DOM element.' ) : invariant(container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ))); ReactEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: ReactPerf.measure( 'ReactMount', '_renderNewRootComponent', function( nextComponent, container, shouldReuseMarkup) { var reactRootID = ReactMount._registerComponent(nextComponent, container); nextComponent.mountComponentIntoNode( reactRootID, container, shouldReuseMarkup ); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return nextComponent; } ), /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} nextComponent Component instance to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderComponent: function(nextComponent, container, callback) { var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { if (shouldUpdateReactComponent(prevComponent, nextComponent)) { return ReactMount._updateRootComponent( prevComponent, nextComponent, container, callback ); } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && ReactMount.isRenderedByReact(reactRootElement); var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent( nextComponent, container, shouldReuseMarkup ); callback && callback.call(component); return component; }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into the supplied `container`. * * @param {function} constructor React component constructor. * @param {?object} props Initial props of the component instance. * @param {DOMElement} container DOM element to render into. * @return {ReactComponent} Component instance rendered in `container`. */ constructAndRenderComponent: function(constructor, props, container) { return ReactMount.renderComponent(constructor(props), container); }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into a container node identified by supplied `id`. * * @param {function} componentConstructor React component constructor * @param {?object} props Initial props of the component instance. * @param {string} id ID of the DOM element to render into. * @return {ReactComponent} Component instance rendered in the container node. */ constructAndRenderComponentByID: function(constructor, props, id) { var domNode = document.getElementById(id); ("production" !== "development" ? invariant( domNode, 'Tried to get element with id of "%s" but it is not present on the page.', id ) : invariant(domNode)); return ReactMount.constructAndRenderComponent(constructor, props, domNode); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function(container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function(container) { var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== "development") { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ unmountComponentFromNode: function(instance, container) { instance.unmountComponent(); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function(id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if ("production" !== "development") { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { ("production" !== "development" ? invariant( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.' ) : invariant(// Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID)); var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { console.warn( 'ReactMount: Root element has been removed from its original ' + 'container. New container:', rootElement.parentNode ); } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function(id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * True if the supplied `node` is rendered by React. * * @param {*} node DOM Element to check. * @return {boolean} True if the DOM Element appears to be rendered by React. * @internal */ isRenderedByReact: function(node) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component return false; } var id = ReactMount.getID(node); return id ? id.charAt(0) === SEPARATOR : false; }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function(node) { var current = node; while (current && current.parentNode !== current) { if (ReactMount.isRenderedByReact(current)) { return current; } current = current.parentNode; } return null; }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function(ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; ("production" !== "development" ? invariant( false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser). ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode) ) : invariant(false)); }, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, purgeID: purgeID }; module.exports = ReactMount; },{"./DOMProperty":9,"./ReactEventEmitter":52,"./ReactInstanceHandles":57,"./ReactPerf":65,"./containsNode":100,"./getReactRootElementInContainer":117,"./invariant":121,"./shouldUpdateReactComponent":139}],61:[function(require,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. * * @providesModule ReactMountReady */ "use strict"; var PooledClass = require("./PooledClass"); var mixInto = require("./mixInto"); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `ReactMountReady.getPooled()`. * * @param {?array<function>} initialCollection * @class ReactMountReady * @implements PooledClass * @internal */ function ReactMountReady(initialCollection) { this._queue = initialCollection || null; } mixInto(ReactMountReady, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. This is used * to enqueue calls to `componentDidMount` and `componentDidUpdate`. * * @param {ReactComponent} component Component being rendered. * @param {function(DOMElement)} callback Invoked when `notifyAll` is invoked. * @internal */ enqueue: function(component, callback) { this._queue = this._queue || []; this._queue.push({component: component, callback: callback}); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function() { var queue = this._queue; if (queue) { this._queue = null; for (var i = 0, l = queue.length; i < l; i++) { var component = queue[i].component; var callback = queue[i].callback; callback.call(component); } queue.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._queue = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactMountReady); module.exports = ReactMountReady; },{"./PooledClass":25,"./mixInto":133}],62:[function(require,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. * * @providesModule ReactMultiChild * @typechecks static-only */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes"); var flattenChildren = require("./flattenChildren"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, textContent: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, textContent: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates( updateQueue, markupQueue ); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function(nestedChildren, transaction) { var children = flattenChildren(nestedChildren); var mountImages = []; var index = 0; this._renderedChildren = children; for (var name in children) { var child = children[name]; if (children.hasOwnProperty(name)) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = child.mountComponent( rootID, transaction, this._mountDepth + 1 ); child._mountIndex = index; mountImages.push(mountImage); index++; } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function(nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { errorThrown ? clearQueue() : processQueue(); } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function(nextNestedChildren, transaction) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildren, transaction); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { errorThrown ? clearQueue() : processQueue(); } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function(nextNestedChildren, transaction) { var nextChildren = flattenChildren(nextNestedChildren); var prevChildren = this._renderedChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (shouldUpdateReactComponent(prevChild, nextChild)) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild.receiveComponent(nextChild, transaction); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChildByName(prevChild, name); } this._mountChildByNameAtIndex( nextChild, name, nextIndex, transaction ); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren[name])) { this._unmountChildByName(prevChildren[name], name); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function() { var renderedChildren = this._renderedChildren; for (var name in renderedChildren) { var renderedChild = renderedChildren[name]; // TODO: When is this not true? if (renderedChild.unmountComponent) { renderedChild.unmountComponent(); } } this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function(child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child, mountImage) { enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function(child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function(textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function(child, name, index, transaction) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = child.mountComponent( rootID, transaction, this._mountDepth + 1 ); child._mountIndex = index; this.createChild(child, mountImage); this._renderedChildren = this._renderedChildren || {}; this._renderedChildren[name] = child; }, /** * Unmounts a rendered child by name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @param {string} name Name of the child in `this._renderedChildren`. * @private */ _unmountChildByName: function(child, name) { // TODO: When is this not true? if (ReactComponent.isValidComponent(child)) { this.removeChild(child); child._mountIndex = null; child.unmountComponent(); delete this._renderedChildren[name]; } } } }; module.exports = ReactMultiChild; },{"./ReactComponent":30,"./ReactMultiChildUpdateTypes":63,"./flattenChildren":110,"./shouldUpdateReactComponent":139}],63:[function(require,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. * * @providesModule ReactMultiChildUpdateTypes */ "use strict"; var keyMirror = require("./keyMirror"); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"./keyMirror":127}],64:[function(require,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. * * @providesModule ReactOwner */ "use strict"; var invariant = require("./invariant"); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function(object) { return !!( object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function' ); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function(component, ref, owner) { ("production" !== "development" ? invariant( ReactOwner.isValidOwner(owner), 'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to add a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function(component, ref, owner) { ("production" !== "development" ? invariant( ReactOwner.isValidOwner(owner), 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to remove a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.refs[ref] === component) { owner.detachRef(ref); } }, /** * A ReactComponent must mix this in to have refs. * * @lends {ReactOwner.prototype} */ Mixin: { /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function(ref, component) { ("production" !== "development" ? invariant( component.isOwnedBy(this), 'attachRef(%s, ...): Only a component\'s owner can store a ref to it.', ref ) : invariant(component.isOwnedBy(this))); var refs = this.refs || (this.refs = {}); refs[ref] = component; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function(ref) { delete this.refs[ref]; } } }; module.exports = ReactOwner; },{"./invariant":121}],65:[function(require,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. * * @providesModule ReactPerf * @typechecks static-only */ "use strict"; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function(objName, fnName, func) { if ("production" !== "development") { var measuredFunc = null; return function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function(measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; },{}],66:[function(require,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. * * @providesModule ReactPropTransferer */ "use strict"; var emptyFunction = require("./emptyFunction"); var invariant = require("./invariant"); var joinClasses = require("./joinClasses"); var merge = require("./merge"); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Never transfer the `key` prop. */ key: emptyFunction, /** * Never transfer the `ref` prop. */ ref: emptyFunction, /** * Transfer the `style` prop (which is an object) by merging them. */ style: createTransferStrategy(merge) }; /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { TransferStrategies: TransferStrategies, /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { var props = merge(oldProps); for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; }, /** * @lends {ReactPropTransferer.prototype} */ Mixin: { /** * Transfer props from this component to a target component. * * Props that do not have an explicit transfer strategy will be transferred * only if the target component does not already have the prop set. * * This is usually used to pass down props to a returned root component. * * @param {ReactComponent} component Component receiving the properties. * @return {ReactComponent} The supplied `component`. * @final * @protected */ transferPropsTo: function(component) { ("production" !== "development" ? invariant( component._owner === this, '%s: You can\'t call transferPropsTo() on a component that you ' + 'don\'t own, %s. This usually means you are calling ' + 'transferPropsTo() on a component passed in as props or children.', this.constructor.displayName, component.constructor.displayName ) : invariant(component._owner === this)); component.props = ReactPropTransferer.mergeProps( component.props, this.props ); return component; } } }; module.exports = ReactPropTransferer; },{"./emptyFunction":108,"./invariant":121,"./joinClasses":126,"./merge":130}],67:[function(require,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. * * @providesModule ReactPropTypeLocationNames */ "use strict"; var ReactPropTypeLocationNames = {}; if ("production" !== "development") { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],68:[function(require,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. * * @providesModule ReactPropTypeLocations */ "use strict"; var keyMirror = require("./keyMirror"); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"./keyMirror":127}],69:[function(require,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. * * @providesModule ReactPropTypes */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var warning = require("./warning"); var createObjectFrom = require("./createObjectFrom"); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var Props = require('ReactPropTypes'); * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * warning( * propValue == null || * typeof propValue === 'string' || * propValue instanceof URI, * 'Invalid `%s` supplied to `%s`, expected string or URI.', * propName, * componentName * ); * } * }, * render: function() { ... } * }); * * @internal */ var Props = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), shape: createShapeTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, arrayOf: createArrayOfTypeChecker, instanceOf: createInstanceTypeChecker, renderable: createRenderableTypeChecker(), component: createComponentTypeChecker(), any: createAnyTypeChecker() }; var ANONYMOUS = '<<anonymous>>'; function isRenderable(propValue) { switch(typeof propValue) { case 'number': case 'string': return true; case 'object': if (Array.isArray(propValue)) { return propValue.every(isRenderable); } if (ReactComponent.isValidComponent(propValue)) { return true; } for (var k in propValue) { if (!isRenderable(propValue[k])) { return false; } } return true; default: return false; } } // Equivalent of typeof but with special handling for arrays function getPropType(propValue) { var propType = typeof propValue; if (propType === 'object' && Array.isArray(propValue)) { return 'array'; } return propType; } function createAnyTypeChecker() { function validateAnyType( shouldWarn, propValue, propName, componentName, location ) { return true; // is always valid } return createChainableTypeChecker(validateAnyType); } function createPrimitiveTypeChecker(expectedType) { function validatePrimitiveType( shouldWarn, propValue, propName, componentName, location ) { var propType = getPropType(propValue); var isValid = propType === expectedType; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` of type `%s` supplied to `%s`, expected `%s`.', ReactPropTypeLocationNames[location], propName, propType, componentName, expectedType ) : null); } return isValid; } return createChainableTypeChecker(validatePrimitiveType); } function createEnumTypeChecker(expectedValues) { var expectedEnum = createObjectFrom(expectedValues); function validateEnumType( shouldWarn, propValue, propName, componentName, location ) { var isValid = expectedEnum[propValue]; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected one of %s.', ReactPropTypeLocationNames[location], propName, componentName, JSON.stringify(Object.keys(expectedEnum)) ) : null); } return isValid; } return createChainableTypeChecker(validateEnumType); } function createShapeTypeChecker(shapeTypes) { function validateShapeType( shouldWarn, propValue, propName, componentName, location ) { var propType = getPropType(propValue); var isValid = propType === 'object'; if (isValid) { for (var key in shapeTypes) { var checker = shapeTypes[key]; if (checker && !checker(propValue, key, componentName, location)) { return false; } } } if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` of type `%s` supplied to `%s`, expected `object`.', ReactPropTypeLocationNames[location], propName, propType, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateShapeType); } function createInstanceTypeChecker(expectedClass) { function validateInstanceType( shouldWarn, propValue, propName, componentName, location ) { var isValid = propValue instanceof expectedClass; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected instance of `%s`.', ReactPropTypeLocationNames[location], propName, componentName, expectedClass.name || ANONYMOUS ) : null); } return isValid; } return createChainableTypeChecker(validateInstanceType); } function createArrayOfTypeChecker(propTypeChecker) { function validateArrayType( shouldWarn, propValue, propName, componentName, location ) { var isValid = Array.isArray(propValue); if (isValid) { for (var i = 0; i < propValue.length; i++) { if (!propTypeChecker(propValue, i, componentName, location)) { return false; } } } if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected an array.', ReactPropTypeLocationNames[location], propName, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateArrayType); } function createRenderableTypeChecker() { function validateRenderableType( shouldWarn, propValue, propName, componentName, location ) { var isValid = isRenderable(propValue); if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected a renderable prop.', ReactPropTypeLocationNames[location], propName, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateRenderableType); } function createComponentTypeChecker() { function validateComponentType( shouldWarn, propValue, propName, componentName, location ) { var isValid = ReactComponent.isValidComponent(propValue); if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected a React component.', ReactPropTypeLocationNames[location], propName, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateComponentType); } function createUnionTypeChecker(arrayOfValidators) { return function(props, propName, componentName, location) { var isValid = false; for (var ii = 0; ii < arrayOfValidators.length; ii++) { var validate = arrayOfValidators[ii]; if (typeof validate.weak === 'function') { validate = validate.weak; } if (validate(props, propName, componentName, location)) { isValid = true; break; } } ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`.', ReactPropTypeLocationNames[location], propName, componentName || ANONYMOUS ) : null); return isValid; }; } function createChainableTypeChecker(validate) { function checkType( isRequired, shouldWarn, props, propName, componentName, location ) { var propValue = props[propName]; if (propValue != null) { // Only validate if there is a value to check. return validate( shouldWarn, propValue, propName, componentName || ANONYMOUS, location ); } else { var isValid = !isRequired; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Required %s `%s` was not specified in `%s`.', ReactPropTypeLocationNames[location], propName, componentName || ANONYMOUS ) : null); } return isValid; } } var checker = checkType.bind(null, false, true); checker.weak = checkType.bind(null, false, false); checker.isRequired = checkType.bind(null, true, true); checker.weak.isRequired = checkType.bind(null, true, false); checker.isRequired.weak = checker.weak.isRequired; return checker; } module.exports = Props; },{"./ReactComponent":30,"./ReactPropTypeLocationNames":67,"./createObjectFrom":105,"./warning":142}],70:[function(require,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. * * @providesModule ReactPutListenerQueue */ "use strict"; var PooledClass = require("./PooledClass"); var ReactEventEmitter = require("./ReactEventEmitter"); var mixInto = require("./mixInto"); function ReactPutListenerQueue() { this.listenersToPut = []; } mixInto(ReactPutListenerQueue, { enqueuePutListener: function(rootNodeID, propKey, propValue) { this.listenersToPut.push({ rootNodeID: rootNodeID, propKey: propKey, propValue: propValue }); }, putListeners: function() { for (var i = 0; i < this.listenersToPut.length; i++) { var listenerToPut = this.listenersToPut[i]; ReactEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"./PooledClass":25,"./ReactEventEmitter":52,"./mixInto":133}],71:[function(require,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. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var PooledClass = require("./PooledClass"); var ReactEventEmitter = require("./ReactEventEmitter"); var ReactInputSelection = require("./ReactInputSelection"); var ReactMountReady = require("./ReactMountReady"); var ReactPutListenerQueue = require("./ReactPutListenerQueue"); var Transaction = require("./Transaction"); var mixInto = require("./mixInto"); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactEventEmitter` before the * reconciliation. */ initialize: function() { var currentlyEnabled = ReactEventEmitter.isEnabled(); ReactEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of `ReactEventEmitter` * before the reconciliation occured. `close` restores the previous value. */ close: function(previouslyEnabled) { ReactEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a `ReactMountReady` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function() { this.reactMountReady.notifyAll(); } }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: function() { this.putListenerQueue.putListeners(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction() { this.reinitializeTransaction(); this.reactMountReady = ReactMountReady.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap proceedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { if (ExecutionEnvironment.canUseDOM) { return TRANSACTION_WRAPPERS; } else { return []; } }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. * TODO: convert to ReactMountReady */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { ReactMountReady.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; mixInto(ReactReconcileTransaction, Transaction.Mixin); mixInto(ReactReconcileTransaction, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"./ExecutionEnvironment":21,"./PooledClass":25,"./ReactEventEmitter":52,"./ReactInputSelection":56,"./ReactMountReady":61,"./ReactPutListenerQueue":70,"./Transaction":95,"./mixInto":133}],72:[function(require,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. * * @providesModule ReactRootIndex * @typechecks */ "use strict"; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],73:[function(require,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. * * @typechecks static-only * @providesModule ReactServerRendering */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMarkupChecksum = require("./ReactMarkupChecksum"); var ReactReconcileTransaction = require("./ReactReconcileTransaction"); var invariant = require("./invariant"); /** * @param {ReactComponent} component * @return {string} the markup */ function renderComponentToString(component) { ("production" !== "development" ? invariant( ReactComponent.isValidComponent(component), 'renderComponentToString(): You must pass a valid ReactComponent.' ) : invariant(ReactComponent.isValidComponent(component))); ("production" !== "development" ? invariant( !(arguments.length === 2 && typeof arguments[1] === 'function'), 'renderComponentToString(): This function became synchronous and now ' + 'returns the generated markup. Please remove the second parameter.' ) : invariant(!(arguments.length === 2 && typeof arguments[1] === 'function'))); var id = ReactInstanceHandles.createReactRootID(); var transaction = ReactReconcileTransaction.getPooled(); transaction.reinitializeTransaction(); try { return transaction.perform(function() { var markup = component.mountComponent(id, transaction, 0); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactReconcileTransaction.release(transaction); } } module.exports = { renderComponentToString: renderComponentToString }; },{"./ReactComponent":30,"./ReactInstanceHandles":57,"./ReactMarkupChecksum":59,"./ReactReconcileTransaction":71,"./invariant":121}],74:[function(require,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. * * @providesModule ReactStateSetters */ "use strict"; var ReactStateSetters = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * @param {ReactCompositeComponent} component * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function(component, funcReturningState) { return function(a, b, c, d, e, f) { var partialState = funcReturningState.call(component, a, b, c, d, e, f); if (partialState) { component.setState(partialState); } }; }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * Note: this is memoized function, which makes it inexpensive to call. * * @param {ReactCompositeComponent} component * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function(component, key) { // Memoize the setters. var cache = component.__keySetters || (component.__keySetters = {}); return cache[key] || (cache[key] = createStateKeySetter(component, key)); } }; function createStateKeySetter(component, key) { // Partial state is allocated outside of the function closure so it can be // reused with every call, avoiding memory allocation when this function // is called. var partialState = {}; return function stateKeySetter(value) { partialState[key] = value; component.setState(partialState); }; } ReactStateSetters.Mixin = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateSetter(function(xValue) { * return {x: xValue}; * })(1); * * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function(funcReturningState) { return ReactStateSetters.createStateSetter(this, funcReturningState); }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateKeySetter('x')(1); * * Note: this is memoized function, which makes it inexpensive to call. * * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function(key) { return ReactStateSetters.createStateKeySetter(this, key); } }; module.exports = ReactStateSetters; },{}],75:[function(require,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. * * @providesModule ReactTestUtils */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPropagators = require("./EventPropagators"); var React = require("./React"); var ReactComponent = require("./ReactComponent"); var ReactDOM = require("./ReactDOM"); var ReactEventEmitter = require("./ReactEventEmitter"); var ReactMount = require("./ReactMount"); var ReactTextComponent = require("./ReactTextComponent"); var ReactUpdates = require("./ReactUpdates"); var SyntheticEvent = require("./SyntheticEvent"); var mergeInto = require("./mergeInto"); var copyProperties = require("./copyProperties"); var topLevelTypes = EventConstants.topLevelTypes; function Event(suffix) {} /** * @class ReactTestUtils */ /** * Todo: Support the entire DOM.scry query syntax. For now, these simple * utilities will suffice for testing purposes. * @lends ReactTestUtils */ var ReactTestUtils = { renderIntoDocument: function(instance) { var div = document.createElement('div'); // None of our tests actually require attaching the container to the // DOM, and doing so creates a mess that we rely on test isolation to // clean up, so we're going to stop honoring the name of this method // (and probably rename it eventually) if no problems arise. // document.documentElement.appendChild(div); return React.renderComponent(instance, div); }, isComponentOfType: function(inst, convenienceConstructor) { return ( ReactComponent.isValidComponent(inst) && inst.type === convenienceConstructor.type ); }, isDOMComponent: function(inst) { return !!(inst && ReactComponent.isValidComponent(inst) && !!inst.tagName); }, isCompositeComponent: function(inst) { if (!ReactComponent.isValidComponent(inst)) { return false; } // We check the prototype of the type that will get mounted, not the // instance itself. This is a future proof way of duck typing. var prototype = inst.type.prototype; return ( typeof prototype.render === 'function' && typeof prototype.setState === 'function' && typeof prototype.updateComponent === 'function' ); }, isCompositeComponentWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponent(inst) && (inst.constructor === type.componentConstructor || inst.constructor === type)); }, isTextComponent: function(inst) { return inst instanceof ReactTextComponent; }, findAllInRenderedTree: function(inst, test) { if (!inst) { return []; } var ret = test(inst) ? [inst] : []; if (ReactTestUtils.isDOMComponent(inst)) { var renderedChildren = inst._renderedChildren; var key; for (key in renderedChildren) { if (!renderedChildren.hasOwnProperty(key)) { continue; } ret = ret.concat( ReactTestUtils.findAllInRenderedTree(renderedChildren[key], test) ); } } else if (ReactTestUtils.isCompositeComponent(inst)) { ret = ret.concat( ReactTestUtils.findAllInRenderedTree(inst._renderedComponent, test) ); } return ret; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the class name matching `className`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithClass: function(root, className) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { var instClassName = inst.props.className; return ReactTestUtils.isDOMComponent(inst) && ( instClassName && (' ' + instClassName + ' ').indexOf(' ' + className + ' ') !== -1 ); }); }, /** * Like scryRenderedDOMComponentsWithClass but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithClass: function(root, className) { var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); if (all.length !== 1) { throw new Error('Did not find exactly one match for class:' + className); } return all[0]; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the tag name matching `tagName`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithTag: function(root, tagName) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isDOMComponent(inst) && inst.tagName === tagName.toUpperCase(); }); }, /** * Like scryRenderedDOMComponentsWithTag but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithTag: function(root, tagName) { var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); if (all.length !== 1) { throw new Error('Did not find exactly one match for tag:' + tagName); } return all[0]; }, /** * Finds all instances of components with type equal to `componentType`. * @return an array of all the matches. */ scryRenderedComponentsWithType: function(root, componentType) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isCompositeComponentWithType(inst, componentType); }); }, /** * Same as `scryRenderedComponentsWithType` but expects there to be one result * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactComponent} The one match. */ findRenderedComponentWithType: function(root, componentType) { var all = ReactTestUtils.scryRenderedComponentsWithType( root, componentType ); if (all.length !== 1) { throw new Error( 'Did not find exactly one match for componentType:' + componentType ); } return all[0]; }, /** * Pass a mocked component module to this method to augment it with * useful methods that allow it to be used as a dummy React component. * Instead of rendering as usual, the component will become a simple * <div> containing any provided children. * * @param {object} module the mock function object exported from a * module that defines the component to be mocked * @param {?string} mockTagName optional dummy root tag name to return * from render method (overrides * module.mockTagName if provided) * @return {object} the ReactTestUtils object (for chaining) */ mockComponent: function(module, mockTagName) { var ConvenienceConstructor = React.createClass({ render: function() { var mockTagName = mockTagName || module.mockTagName || "div"; return ReactDOM[mockTagName](null, this.props.children); } }); copyProperties(module, ConvenienceConstructor); module.mockImplementation(ConvenienceConstructor); return this; }, /** * Simulates a top level event being dispatched from a raw event that occured * on an `Element` node. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes` * @param {!Element} node The dom to simulate an event occurring on. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnNode: function(topLevelType, node, fakeNativeEvent) { var virtualHandler = ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( topLevelType ); fakeNativeEvent.target = node; virtualHandler(fakeNativeEvent); }, /** * Simulates a top level event being dispatched from a raw event that occured * on the `ReactDOMComponent` `comp`. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes`. * @param comp {!ReactDOMComponent} * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnDOMComponent: function( topLevelType, comp, fakeNativeEvent) { ReactTestUtils.simulateNativeEventOnNode( topLevelType, comp.getDOMNode(), fakeNativeEvent ); }, nativeTouchData: function(x, y) { return { touches: [ {pageX: x, pageY: y} ] }; }, Simulate: null, SimulateNative: {} }; /** * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)` * - ... (All keys from event plugin `eventTypes` objects) */ function makeSimulator(eventType) { return function(domComponentOrNode, eventData) { var node; if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { node = domComponentOrNode.getDOMNode(); } else if (domComponentOrNode.tagName) { node = domComponentOrNode; } var fakeNativeEvent = new Event(); fakeNativeEvent.target = node; // We don't use SyntheticEvent.getPooled in order to not have to worry about // properly destroying any properties assigned from `eventData` upon release var event = new SyntheticEvent( ReactEventEmitter.eventNameDispatchConfigs[eventType], ReactMount.getID(node), fakeNativeEvent ); mergeInto(event, eventData); EventPropagators.accumulateTwoPhaseDispatches(event); ReactUpdates.batchedUpdates(function() { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); }); }; } function buildSimulators() { ReactTestUtils.Simulate = {}; var eventType; for (eventType in ReactEventEmitter.eventNameDispatchConfigs) { /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?object} eventData Fake event data to use in SyntheticEvent. */ ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); } } // Rebuild ReactTestUtils.Simulate whenever event plugins are injected var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder; EventPluginHub.injection.injectEventPluginOrder = function() { oldInjectEventPluginOrder.apply(this, arguments); buildSimulators(); }; var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName; EventPluginHub.injection.injectEventPluginsByName = function() { oldInjectEventPlugins.apply(this, arguments); buildSimulators(); }; buildSimulators(); /** * Exports: * * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` * - ... (All keys from `EventConstants.topLevelTypes`) * * Note: Top level event types are a subset of the entire set of handler types * (which include a broader set of "synthetic" events). For example, onDragDone * is a synthetic event. Except when testing an event plugin or React's event * handling code specifically, you probably want to use ReactTestUtils.Simulate * to dispatch synthetic events. */ function makeNativeSimulator(eventType) { return function(domComponentOrNode, nativeEventData) { var fakeNativeEvent = new Event(eventType); mergeInto(fakeNativeEvent, nativeEventData); if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { ReactTestUtils.simulateNativeEventOnDOMComponent( eventType, domComponentOrNode, fakeNativeEvent ); } else if (!!domComponentOrNode.tagName) { // Will allow on actual dom nodes. ReactTestUtils.simulateNativeEventOnNode( eventType, domComponentOrNode, fakeNativeEvent ); } }; } var eventType; for (eventType in topLevelTypes) { // Event type is stored as 'topClick' - we transform that to 'click' var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. */ ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType); } module.exports = ReactTestUtils; },{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./React":26,"./ReactComponent":30,"./ReactDOM":36,"./ReactEventEmitter":52,"./ReactMount":60,"./ReactTextComponent":76,"./ReactUpdates":80,"./SyntheticEvent":88,"./copyProperties":101,"./mergeInto":132}],76:[function(require,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. * * @providesModule ReactTextComponent * @typechecks static-only */ "use strict"; var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactComponent = require("./ReactComponent"); var escapeTextForBrowser = require("./escapeTextForBrowser"); var mixInto = require("./mixInto"); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactTextComponent * @extends ReactComponent * @internal */ var ReactTextComponent = function(initialText) { this.construct({text: initialText}); }; mixInto(ReactTextComponent, ReactComponent.Mixin); mixInto(ReactTextComponent, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {string} Markup for this text node. * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); return ( '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapeTextForBrowser(this.props.text) + '</span>' ); }, /** * Updates this component by updating the text content. * * @param {object} nextComponent Contains the next text content. * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextComponent, transaction) { var nextProps = nextComponent.props; if (nextProps.text !== this.props.text) { this.props.text = nextProps.text; ReactComponent.BackendIDOperations.updateTextContentByID( this._rootNodeID, nextProps.text ); } } }); // Expose the constructor on itself and the prototype for consistency with other // descriptors. ReactTextComponent.type = ReactTextComponent; ReactTextComponent.prototype.type = ReactTextComponent; module.exports = ReactTextComponent; },{"./DOMPropertyOperations":10,"./ReactComponent":30,"./escapeTextForBrowser":109,"./mixInto":133}],77:[function(require,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. * * @typechecks static-only * @providesModule ReactTransitionChildMapping */ "use strict"; var ReactChildren = require("./ReactChildren"); var ReactTransitionChildMapping = { /** * Given `this.props.children`, return an object mapping key to child. Just * simple syntactic sugar around ReactChildren.map(). * * @param {*} children `this.props.children` * @return {object} Mapping of key to child */ getChildMapping: function(children) { return ReactChildren.map(children, function(child) { return child; }); }, /** * When you're adding or removing children some may be added or removed in the * same render pass. We want ot show *both* since we want to simultaneously * animate elements in and out. This function takes a previous set of keys * and a new set of keys and merges them with its best guess of the correct * ordering. In the future we may expose some of the utilities in * ReactMultiChild to make this easy, but for now React itself does not * directly have this concept of the union of prevChildren and nextChildren * so we implement it here. * * @param {object} prev prev children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @param {object} next next children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @return {object} a key set that contains all keys in `prev` and all keys * in `next` in a reasonable order. */ mergeChildMappings: function(prev, next) { prev = prev || {}; next = next || {}; function getValueForKey(key) { if (next.hasOwnProperty(key)) { return next[key]; } else { return prev[key]; } } // For each key of `next`, the list of keys to insert before that key in // the combined list var nextKeysPending = {}; var pendingKeys = []; for (var prevKey in prev) { if (next[prevKey]) { if (pendingKeys.length) { nextKeysPending[prevKey] = pendingKeys; pendingKeys = []; } } else { pendingKeys.push(prevKey); } } var i; var childMapping = {}; for (var nextKey in next) { if (nextKeysPending[nextKey]) { for (i = 0; i < nextKeysPending[nextKey].length; i++) { var pendingNextKey = nextKeysPending[nextKey][i]; childMapping[nextKeysPending[nextKey][i]] = getValueForKey( pendingNextKey ); } } childMapping[nextKey] = getValueForKey(nextKey); } // Finally, add the keys which didn't appear before any key in `next` for (i = 0; i < pendingKeys.length; i++) { childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]); } return childMapping; } }; module.exports = ReactTransitionChildMapping; },{"./ReactChildren":29}],78:[function(require,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. * * @providesModule ReactTransitionEvents */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function(endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function(endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; },{"./ExecutionEnvironment":21}],79:[function(require,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. * * @providesModule ReactTransitionGroup */ "use strict"; var React = require("./React"); var ReactTransitionChildMapping = require("./ReactTransitionChildMapping"); var cloneWithProps = require("./cloneWithProps"); var emptyFunction = require("./emptyFunction"); var merge = require("./merge"); var ReactTransitionGroup = React.createClass({ propTypes: { component: React.PropTypes.func, childFactory: React.PropTypes.func }, getDefaultProps: function() { return { component: React.DOM.span, childFactory: emptyFunction.thatReturnsArgument }; }, getInitialState: function() { return { children: ReactTransitionChildMapping.getChildMapping(this.props.children) }; }, componentWillReceiveProps: function(nextProps) { var nextChildMapping = ReactTransitionChildMapping.getChildMapping( nextProps.children ); var prevChildMapping = this.state.children; this.setState({ children: ReactTransitionChildMapping.mergeChildMappings( prevChildMapping, nextChildMapping ) }); var key; for (key in nextChildMapping) { if (!prevChildMapping.hasOwnProperty(key) && !this.currentlyTransitioningKeys[key]) { this.keysToEnter.push(key); } } for (key in prevChildMapping) { if (!nextChildMapping.hasOwnProperty(key) && !this.currentlyTransitioningKeys[key]) { this.keysToLeave.push(key); } } // If we want to someday check for reordering, we could do it here. }, componentWillMount: function() { this.currentlyTransitioningKeys = {}; this.keysToEnter = []; this.keysToLeave = []; }, componentDidUpdate: function() { var keysToEnter = this.keysToEnter; this.keysToEnter = []; keysToEnter.forEach(this.performEnter); var keysToLeave = this.keysToLeave; this.keysToLeave = []; keysToLeave.forEach(this.performLeave); }, performEnter: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillEnter) { component.componentWillEnter( this._handleDoneEntering.bind(this, key) ); } else { this._handleDoneEntering(key); } }, _handleDoneEntering: function(key) { var component = this.refs[key]; if (component.componentDidEnter) { component.componentDidEnter(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (!currentChildMapping.hasOwnProperty(key)) { // This was removed before it had fully entered. Remove it. this.performLeave(key); } }, performLeave: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillLeave) { component.componentWillLeave(this._handleDoneLeaving.bind(this, key)); } else { // Note that this is somewhat dangerous b/c it calls setState() // again, effectively mutating the component before all the work // is done. this._handleDoneLeaving(key); } }, _handleDoneLeaving: function(key) { var component = this.refs[key]; if (component.componentDidLeave) { component.componentDidLeave(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (currentChildMapping.hasOwnProperty(key)) { // This entered again before it fully left. Add it again. this.performEnter(key); } else { var newChildren = merge(this.state.children); delete newChildren[key]; this.setState({children: newChildren}); } }, render: function() { // TODO: we could get rid of the need for the wrapper node // by cloning a single child var childrenToRender = {}; for (var key in this.state.children) { var child = this.state.children[key]; if (child) { // You may need to apply reactive updates to a child as it is leaving. // The normal React way to do it won't work since the child will have // already been removed. In case you need this behavior you can provide // a childFactory function to wrap every child, even the ones that are // leaving. childrenToRender[key] = cloneWithProps( this.props.childFactory(child), {ref: key} ); } } return this.transferPropsTo(this.props.component(null, childrenToRender)); } }); module.exports = ReactTransitionGroup; },{"./React":26,"./ReactTransitionChildMapping":77,"./cloneWithProps":99,"./emptyFunction":108,"./merge":130}],80:[function(require,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. * * @providesModule ReactUpdates */ "use strict"; var ReactPerf = require("./ReactPerf"); var invariant = require("./invariant"); var dirtyComponents = []; var batchingStrategy = null; function ensureBatchingStrategy() { ("production" !== "development" ? invariant(batchingStrategy, 'ReactUpdates: must inject a batching strategy') : invariant(batchingStrategy)); } function batchedUpdates(callback, param) { ensureBatchingStrategy(); batchingStrategy.batchedUpdates(callback, param); } /** * Array comparator for ReactComponents by owner depth * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountDepthComparator(c1, c2) { return c1._mountDepth - c2._mountDepth; } function runBatchedUpdates() { // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountDepthComparator); for (var i = 0; i < dirtyComponents.length; i++) { // If a component is unmounted before pending changes apply, ignore them // TODO: Queue unmounts in the same list to avoid this happening at all var component = dirtyComponents[i]; if (component.isMounted()) { // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; component.performUpdateIfNecessary(); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { callbacks[j].call(component); } } } } } function clearDirtyComponents() { dirtyComponents.length = 0; } var flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', function() { // Run these in separate functions so the JIT can optimize try { runBatchedUpdates(); } finally { clearDirtyComponents(); } } ); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component, callback) { ("production" !== "development" ? invariant( !callback || typeof callback === "function", 'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(!callback || typeof callback === "function")); ensureBatchingStrategy(); if (!batchingStrategy.isBatchingUpdates) { component.performUpdateIfNecessary(); callback && callback.call(component); return; } dirtyComponents.push(component); if (callback) { if (component._pendingCallbacks) { component._pendingCallbacks.push(callback); } else { component._pendingCallbacks = [callback]; } } } var ReactUpdatesInjection = { injectBatchingStrategy: function(_batchingStrategy) { ("production" !== "development" ? invariant( _batchingStrategy, 'ReactUpdates: must provide a batching strategy' ) : invariant(_batchingStrategy)); ("production" !== "development" ? invariant( typeof _batchingStrategy.batchedUpdates === 'function', 'ReactUpdates: must provide a batchedUpdates() function' ) : invariant(typeof _batchingStrategy.batchedUpdates === 'function')); ("production" !== "development" ? invariant( typeof _batchingStrategy.isBatchingUpdates === 'boolean', 'ReactUpdates: must provide an isBatchingUpdates boolean attribute' ) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean')); batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection }; module.exports = ReactUpdates; },{"./ReactPerf":65,"./invariant":121}],81:[function(require,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. * * @providesModule ReactWithAddons */ /** * This module exists purely in the open source project, and is meant as a way * to create a separate standalone build of React. This build has "addons", or * functionality we've built and think might be useful but doesn't have a good * place to live inside React core. */ "use strict"; var LinkedStateMixin = require("./LinkedStateMixin"); var React = require("./React"); var ReactCSSTransitionGroup = require("./ReactCSSTransitionGroup"); var ReactTransitionGroup = require("./ReactTransitionGroup"); var ReactCSSTransitionGroup = require("./ReactCSSTransitionGroup"); var cx = require("./cx"); var cloneWithProps = require("./cloneWithProps"); React.addons = { LinkedStateMixin: LinkedStateMixin, CSSTransitionGroup: ReactCSSTransitionGroup, TransitionGroup: ReactTransitionGroup, classSet: cx, cloneWithProps: cloneWithProps }; if ("production" !== "development") { React.addons.TestUtils = require("./ReactTestUtils"); } module.exports = React; },{"./LinkedStateMixin":22,"./React":26,"./ReactCSSTransitionGroup":27,"./ReactTestUtils":75,"./ReactTransitionGroup":79,"./cloneWithProps":99,"./cx":106}],82:[function(require,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. * * @providesModule SelectEventPlugin */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ReactInputSelection = require("./ReactInputSelection"); var SyntheticEvent = require("./SyntheticEvent"); var getActiveElement = require("./getActiveElement"); var isTextInputElement = require("./isTextInputElement"); var keyOf = require("./keyOf"); var shallowEqual = require("./shallowEqual"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({onSelect: null}), captured: keyOf({onSelectCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @param {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } else { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement != getActiveElement()) { return; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled( eventTypes.select, activeElementID, nativeEvent ); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. case topLevelTypes.topSelectionChange: case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent); } } }; module.exports = SelectEventPlugin; },{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":56,"./SyntheticEvent":88,"./getActiveElement":112,"./isTextInputElement":124,"./keyOf":128,"./shallowEqual":138}],83:[function(require,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. * * @providesModule ServerReactRootIndex * @typechecks */ "use strict"; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function() { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; },{}],84:[function(require,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. * * @providesModule SimpleEventPlugin */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginUtils = require("./EventPluginUtils"); var EventPropagators = require("./EventPropagators"); var SyntheticClipboardEvent = require("./SyntheticClipboardEvent"); var SyntheticEvent = require("./SyntheticEvent"); var SyntheticFocusEvent = require("./SyntheticFocusEvent"); var SyntheticKeyboardEvent = require("./SyntheticKeyboardEvent"); var SyntheticMouseEvent = require("./SyntheticMouseEvent"); var SyntheticDragEvent = require("./SyntheticDragEvent"); var SyntheticTouchEvent = require("./SyntheticTouchEvent"); var SyntheticUIEvent = require("./SyntheticUIEvent"); var SyntheticWheelEvent = require("./SyntheticWheelEvent"); var invariant = require("./invariant"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { blur: { phasedRegistrationNames: { bubbled: keyOf({onBlur: true}), captured: keyOf({onBlurCapture: true}) } }, click: { phasedRegistrationNames: { bubbled: keyOf({onClick: true}), captured: keyOf({onClickCapture: true}) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({onContextMenu: true}), captured: keyOf({onContextMenuCapture: true}) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({onCopy: true}), captured: keyOf({onCopyCapture: true}) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({onCut: true}), captured: keyOf({onCutCapture: true}) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({onDoubleClick: true}), captured: keyOf({onDoubleClickCapture: true}) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({onDrag: true}), captured: keyOf({onDragCapture: true}) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({onDragEnd: true}), captured: keyOf({onDragEndCapture: true}) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({onDragEnter: true}), captured: keyOf({onDragEnterCapture: true}) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({onDragExit: true}), captured: keyOf({onDragExitCapture: true}) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({onDragLeave: true}), captured: keyOf({onDragLeaveCapture: true}) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({onDragOver: true}), captured: keyOf({onDragOverCapture: true}) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({onDragStart: true}), captured: keyOf({onDragStartCapture: true}) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({onDrop: true}), captured: keyOf({onDropCapture: true}) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({onFocus: true}), captured: keyOf({onFocusCapture: true}) } }, input: { phasedRegistrationNames: { bubbled: keyOf({onInput: true}), captured: keyOf({onInputCapture: true}) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({onKeyDown: true}), captured: keyOf({onKeyDownCapture: true}) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({onKeyPress: true}), captured: keyOf({onKeyPressCapture: true}) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({onKeyUp: true}), captured: keyOf({onKeyUpCapture: true}) } }, load: { phasedRegistrationNames: { bubbled: keyOf({onLoad: true}), captured: keyOf({onLoadCapture: true}) } }, error: { phasedRegistrationNames: { bubbled: keyOf({onError: true}), captured: keyOf({onErrorCapture: true}) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({onMouseDown: true}), captured: keyOf({onMouseDownCapture: true}) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({onMouseMove: true}), captured: keyOf({onMouseMoveCapture: true}) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({onMouseOut: true}), captured: keyOf({onMouseOutCapture: true}) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({onMouseOver: true}), captured: keyOf({onMouseOverCapture: true}) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({onMouseUp: true}), captured: keyOf({onMouseUpCapture: true}) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({onPaste: true}), captured: keyOf({onPasteCapture: true}) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({onReset: true}), captured: keyOf({onResetCapture: true}) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({onScroll: true}), captured: keyOf({onScrollCapture: true}) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({onSubmit: true}), captured: keyOf({onSubmitCapture: true}) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({onTouchCancel: true}), captured: keyOf({onTouchCancelCapture: true}) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({onTouchEnd: true}), captured: keyOf({onTouchEndCapture: true}) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({onTouchMove: true}), captured: keyOf({onTouchMoveCapture: true}) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({onTouchStart: true}), captured: keyOf({onTouchStartCapture: true}) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({onWheel: true}), captured: keyOf({onWheelCapture: true}) } } }; var topLevelEventsToDispatchConfig = { topBlur: eventTypes.blur, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSubmit: eventTypes.submit, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topWheel: eventTypes.wheel }; for (var topLevelType in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType]; } var SimpleEventPlugin = { eventTypes: eventTypes, /** * Same as the default implementation, except cancels the event when return * value is false. * * @param {object} Event to be dispatched. * @param {function} Application-level callback. * @param {string} domID DOM ID to pass to the callback. */ executeDispatch: function(event, listener, domID) { var returnValue = EventPluginUtils.executeDispatch(event, listener, domID); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } }, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topError: case topLevelTypes.topReset: case topLevelTypes.topSubmit: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyDown: case topLevelTypes.topKeyPress: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } ("production" !== "development" ? invariant( EventConstructor, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType ) : invariant(EventConstructor)); var event = EventConstructor.getPooled( dispatchConfig, topLevelTargetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = SimpleEventPlugin; },{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":85,"./SyntheticDragEvent":87,"./SyntheticEvent":88,"./SyntheticFocusEvent":89,"./SyntheticKeyboardEvent":90,"./SyntheticMouseEvent":91,"./SyntheticTouchEvent":92,"./SyntheticUIEvent":93,"./SyntheticWheelEvent":94,"./invariant":121,"./keyOf":128}],85:[function(require,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. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function(event) { return ( 'clipboardData' in event ? event.clipboardData : window.clipboardData ); } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"./SyntheticEvent":88}],86:[function(require,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. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent( dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticCompositionEvent, CompositionEventInterface ); module.exports = SyntheticCompositionEvent; },{"./SyntheticEvent":88}],87:[function(require,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. * * @providesModule SyntheticDragEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = require("./SyntheticMouseEvent"); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"./SyntheticMouseEvent":91}],88:[function(require,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. * * @providesModule SyntheticEvent * @typechecks static-only */ "use strict"; var PooledClass = require("./PooledClass"); var emptyFunction = require("./emptyFunction"); var getEventTarget = require("./getEventTarget"); var merge = require("./merge"); var mergeInto = require("./mergeInto"); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: getEventTarget, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function(event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { this[propName] = nativeEvent[propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } mergeInto(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; event.preventDefault ? event.preventDefault() : event.returnValue = false; this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function() { var event = this.nativeEvent; event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true; this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function() { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function() { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); mergeInto(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = merge(Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler); module.exports = SyntheticEvent; },{"./PooledClass":25,"./emptyFunction":108,"./getEventTarget":114,"./merge":130,"./mergeInto":132}],89:[function(require,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. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"./SyntheticUIEvent":93}],90:[function(require,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. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); var getEventKey = require("./getEventKey"); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, // Legacy Interface 'char': null, charCode: null, keyCode: null, which: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"./SyntheticUIEvent":93,"./getEventKey":113}],91:[function(require,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. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); var ViewportMetrics = require("./ViewportMetrics"); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, button: function(event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function(event) { return event.relatedTarget || ( event.fromElement === event.srcElement ? event.toElement : event.fromElement ); }, // "Proprietary" Interface. pageX: function(event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function(event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"./SyntheticUIEvent":93,"./ViewportMetrics":96}],92:[function(require,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. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"./SyntheticUIEvent":93}],93:[function(require,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. * * @providesModule SyntheticUIEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: null, detail: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"./SyntheticEvent":88}],94:[function(require,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. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = require("./SyntheticMouseEvent"); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function(event) { return ( 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0 ); }, deltaY: function(event) { return ( 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0 ); }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"./SyntheticMouseEvent":91}],95:[function(require,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. * * @providesModule Transaction */ "use strict"; var invariant = require("./invariant"); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Bonus: * - Reports timing metrics by method name and wrapper index. * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM upates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function() { this.transactionWrappers = this.getTransactionWrappers(); if (!this.wrapperInitData) { this.wrapperInitData = []; } else { this.wrapperInitData.length = 0; } if (!this.timingMetrics) { this.timingMetrics = {}; } this.timingMetrics.methodInvocationTime = 0; if (!this.timingMetrics.wrapperInitTimes) { this.timingMetrics.wrapperInitTimes = []; } else { this.timingMetrics.wrapperInitTimes.length = 0; } if (!this.timingMetrics.wrapperCloseTimes) { this.timingMetrics.wrapperCloseTimes = []; } else { this.timingMetrics.wrapperCloseTimes.length = 0; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function() { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { ("production" !== "development" ? invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ) : invariant(!this.isInTransaction())); var memberStart = Date.now(); var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { var memberEnd = Date.now(); this.methodInvocationTime += (memberEnd - memberStart); try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) { } } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function(startIndex) { var transactionWrappers = this.transactionWrappers; var wrapperInitTimes = this.timingMetrics.wrapperInitTimes; for (var i = startIndex; i < transactionWrappers.length; i++) { var initStart = Date.now(); var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { var curInitTime = wrapperInitTimes[i]; var initEnd = Date.now(); wrapperInitTimes[i] = (curInitTime || 0) + (initEnd - initStart); if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) { } } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function(startIndex) { ("production" !== "development" ? invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ) : invariant(this.isInTransaction())); var transactionWrappers = this.transactionWrappers; var wrapperCloseTimes = this.timingMetrics.wrapperCloseTimes; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var closeStart = Date.now(); var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR) { wrapper.close && wrapper.close.call(this, initData); } errorThrown = false; } finally { var closeEnd = Date.now(); var curCloseTime = wrapperCloseTimes[i]; wrapperCloseTimes[i] = (curCloseTime || 0) + (closeEnd - closeStart); if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) { } } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"./invariant":121}],96:[function(require,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. * * @providesModule ViewportMetrics */ "use strict"; var getUnboundedScrollPosition = require("./getUnboundedScrollPosition"); var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function() { var scrollPosition = getUnboundedScrollPosition(window); ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{"./getUnboundedScrollPosition":119}],97:[function(require,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. * * @providesModule accumulate */ "use strict"; var invariant = require("./invariant"); /** * Accumulates items that must not be null or undefined. * * This is used to conserve memory by avoiding array allocations. * * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { ("production" !== "development" ? invariant( next != null, 'accumulate(...): Accumulated items must be not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } else { // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray) { return current.concat(next); } else { if (nextIsArray) { return [current].concat(next); } else { return [current, next]; } } } } module.exports = accumulate; },{"./invariant":121}],98:[function(require,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. * * @providesModule adler32 */ /* jslint bitwise:true */ "use strict"; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonable good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],99:[function(require,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. * * @typechecks * @providesModule cloneWithProps */ "use strict"; var ReactPropTransferer = require("./ReactPropTransferer"); var keyOf = require("./keyOf"); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {object} child child component you'd like to clone * @param {object} props props you'd like to modify. They will be merged * as if you used `transferPropsTo()`. * @return {object} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== "development") { if (child.props.ref) { console.warn( 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ); } } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } return child.constructor.ConvenienceConstructor(newProps); } module.exports = cloneWithProps; },{"./ReactPropTransferer":66,"./keyOf":128}],100:[function(require,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. * * @providesModule containsNode * @typechecks */ var isTextNode = require("./isTextNode"); /*jslint bitwise:true */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"./isTextNode":125}],101:[function(require,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. * * @providesModule copyProperties */ /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function copyProperties(obj, a, b, c, d, e, f) { obj = obj || {}; if ("production" !== "development") { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++]; for (var k in v) { obj[k] = v[k]; } // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString != 'undefined') && (obj.toString !== v.toString)) { obj.toString = v.toString; } } return obj; } module.exports = copyProperties; },{}],102:[function(require,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. * * @providesModule createArrayFrom * @typechecks */ var toArray = require("./toArray"); /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && // arrays are objects, NodeLists are functions in Safari (typeof obj == 'object' || typeof obj == 'function') && // quacks like an array ('length' in obj) && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 (typeof obj.nodeType != 'number') && ( // a real array (// HTMLCollection/NodeList (Array.isArray(obj) || // arguments ('callee' in obj) || 'item' in obj)) ) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFrom = require('createArrayFrom'); * * function takesOneOrMoreThings(things) { * things = createArrayFrom(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFrom(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFrom; },{"./toArray":140}],103:[function(require,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. * * @providesModule createFullPageComponent * @typechecks */ "use strict"; // Defeat circular references by requiring this directly. var ReactCompositeComponent = require("./ReactCompositeComponent"); var invariant = require("./invariant"); /** * Create a component that will throw an exception when unmounted. * * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. * * @param {function} componentClass convenience constructor to wrap * @return {function} convenience constructor of new component */ function createFullPageComponent(componentClass) { var FullPageComponent = ReactCompositeComponent.createClass({ displayName: 'ReactFullPageComponent' + ( componentClass.componentConstructor.displayName || '' ), componentWillUnmount: function() { ("production" !== "development" ? invariant( false, '%s tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, <head>, ' + 'and <body>) reliably and efficiently. To fix this, have a single ' + 'top-level component that never unmounts render these elements.', this.constructor.displayName ) : invariant(false)); }, render: function() { return this.transferPropsTo(componentClass(null, this.props.children)); } }); return FullPageComponent; } module.exports = createFullPageComponent; },{"./ReactCompositeComponent":33,"./invariant":121}],104:[function(require,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. * * @providesModule createNodesFromMarkup * @typechecks */ /*jslint evil: true, sub: true */ var ExecutionEnvironment = require("./ExecutionEnvironment"); var createArrayFrom = require("./createArrayFrom"); var getMarkupWrap = require("./getMarkupWrap"); var invariant = require("./invariant"); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; ("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode)); var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { ("production" !== "development" ? invariant( handleScript, 'createNodesFromMarkup(...): Unexpected <script> element rendered.' ) : invariant(handleScript)); createArrayFrom(scripts).forEach(handleScript); } var nodes = createArrayFrom(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"./ExecutionEnvironment":21,"./createArrayFrom":102,"./getMarkupWrap":115,"./invariant":121}],105:[function(require,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. * * @providesModule createObjectFrom */ /** * Construct an object from an array of keys * and optionally specified value or list of values. * * >>> createObjectFrom(['a','b','c']); * {a: true, b: true, c: true} * * >>> createObjectFrom(['a','b','c'], false); * {a: false, b: false, c: false} * * >>> createObjectFrom(['a','b','c'], 'monkey'); * {c:'monkey', b:'monkey' c:'monkey'} * * >>> createObjectFrom(['a','b','c'], [1,2,3]); * {a: 1, b: 2, c: 3} * * >>> createObjectFrom(['women', 'men'], [true, false]); * {women: true, men: false} * * @param Array list of keys * @param mixed optional value or value array. defaults true. * @returns object */ function createObjectFrom(keys, values /* = true */) { if ("production" !== "development") { if (!Array.isArray(keys)) { throw new TypeError('Must pass an array of keys.'); } } var object = {}; var isArray = Array.isArray(values); if (typeof values == 'undefined') { values = true; } for (var ii = keys.length; ii--;) { object[keys[ii]] = isArray ? values[ii] : values; } return object; } module.exports = createObjectFrom; },{}],106:[function(require,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. * * @providesModule cx */ /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ function cx(classNames) { if (typeof classNames == 'object') { return Object.keys(classNames).filter(function(className) { return classNames[className]; }).join(' '); } else { return Array.prototype.join.call(arguments, ' '); } } module.exports = cx; },{}],107:[function(require,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. * * @providesModule dangerousStyleValue * @typechecks static-only */ "use strict"; var CSSProperty = require("./CSSProperty"); /** * Convert a value into the proper css writable value. The `styleName` name * name should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} styleName CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(styleName, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || CSSProperty.isUnitlessNumber[styleName]) { return '' + value; // cast to string } return value + 'px'; } module.exports = dangerousStyleValue; },{"./CSSProperty":3}],108:[function(require,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. * * @providesModule emptyFunction */ var copyProperties = require("./copyProperties"); function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} copyProperties(emptyFunction, { thatReturns: makeEmptyFunction, thatReturnsFalse: makeEmptyFunction(false), thatReturnsTrue: makeEmptyFunction(true), thatReturnsNull: makeEmptyFunction(null), thatReturnsThis: function() { return this; }, thatReturnsArgument: function(arg) { return arg; } }); module.exports = emptyFunction; },{"./copyProperties":101}],109:[function(require,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. * * @providesModule escapeTextForBrowser * @typechecks static-only */ "use strict"; var ESCAPE_LOOKUP = { "&": "&amp;", ">": "&gt;", "<": "&lt;", "\"": "&quot;", "'": "&#x27;", "/": "&#x2f;" }; var ESCAPE_REGEX = /[&><"'\/]/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextForBrowser; },{}],110:[function(require,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. * * @providesModule flattenChildren */ "use strict"; var invariant = require("./invariant"); var traverseAllChildren = require("./traverseAllChildren"); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; ("production" !== "development" ? invariant( !result.hasOwnProperty(name), 'flattenChildren(...): Encountered two children with the same key, `%s`. ' + 'Children keys must be unique.', name ) : invariant(!result.hasOwnProperty(name))); if (child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; },{"./invariant":121,"./traverseAllChildren":141}],111:[function(require,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. * * @providesModule forEachAccumulated */ "use strict"; /** * @param {array} an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],112:[function(require,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. * * @providesModule getActiveElement * @typechecks */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document body is not yet defined. */ function getActiveElement() /*?DOMElement*/ { try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],113:[function(require,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. * * @providesModule getEventKey * @typechecks static-only */ "use strict"; /** * Normalization of deprecated HTML5 "key" values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy "which/keyCode" to HTML5 "key" * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 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' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { return 'key' in nativeEvent ? normalizeKey[nativeEvent.key] || nativeEvent.key : translateToKey[nativeEvent.which || nativeEvent.keyCode] || 'Unidentified'; } module.exports = getEventKey; },{}],114:[function(require,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. * * @providesModule getEventTarget * @typechecks static-only */ "use strict"; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],115:[function(require,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. * * @providesModule getMarkupWrap */ var ExecutionEnvironment = require("./ExecutionEnvironment"); var invariant = require("./invariant"); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = { // Force wrapping for SVG elements because if they get created inside a <div>, // they will be initialized in the wrong namespace (and will not display). 'circle': true, 'defs': true, 'g': true, 'line': true, 'linearGradient': true, 'path': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'text': true }; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg>', '</svg>']; var markupWrap = { '*': [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': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap, 'circle': svgWrap, 'defs': svgWrap, 'g': svgWrap, 'line': svgWrap, 'linearGradient': svgWrap, 'path': svgWrap, 'polygon': svgWrap, 'polyline': svgWrap, 'radialGradient': svgWrap, 'rect': svgWrap, 'stop': svgWrap, 'text': svgWrap }; /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { ("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode)); if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; },{"./ExecutionEnvironment":21,"./invariant":121}],116:[function(require,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. * * @providesModule getNodeForCharacterOffset */ "use strict"; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType == 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],117:[function(require,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. * * @providesModule getReactRootElementInContainer */ "use strict"; var DOC_NODE_TYPE = 9; /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } module.exports = getReactRootElementInContainer; },{}],118:[function(require,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. * * @providesModule getTextContentAccessor */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.createElement('div') ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"./ExecutionEnvironment":21}],119:[function(require,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. * * @providesModule getUnboundedScrollPosition * @typechecks */ "use strict"; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],120:[function(require,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. * * @providesModule hyphenate * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],121:[function(require,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. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition) { if (!condition) { var error = new Error( 'Minified exception occured; use the non-minified dev environment for ' + 'the full error message and additional helpful warnings.' ); error.framesToPop = 1; throw error; } }; if ("production" !== "development") { invariant = function(condition, format, a, b, c, d, e, f) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } if (!condition) { var args = [a, b, c, d, e, f]; var argIndex = 0; var error = new Error( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; } module.exports = invariant; },{}],122:[function(require,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. * * @providesModule isEventSupported */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * 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 isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"./ExecutionEnvironment":21}],123:[function(require,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. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && ( typeof Node !== 'undefined' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string' )); } module.exports = isNode; },{}],124:[function(require,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. * * @providesModule isTextInputElement */ "use strict"; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { return elem && ( (elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) || elem.nodeName === 'TEXTAREA' ); } module.exports = isTextInputElement; },{}],125:[function(require,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. * * @providesModule isTextNode * @typechecks */ var isNode = require("./isNode"); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"./isNode":123}],126:[function(require,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. * * @providesModule joinClasses * @typechecks static-only */ "use strict"; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; nextClass && (className += ' ' + nextClass); } } return className; } module.exports = joinClasses; },{}],127:[function(require,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. * * @providesModule keyMirror * @typechecks static-only */ "use strict"; var invariant = require("./invariant"); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function(obj) { var ret = {}; var key; ("production" !== "development" ? invariant( obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.' ) : invariant(obj instanceof Object && !Array.isArray(obj))); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"./invariant":121}],128:[function(require,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. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],129:[function(require,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. * * @providesModule memoizeStringOnly * @typechecks static-only */ "use strict"; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function(string) { if (cache.hasOwnProperty(string)) { return cache[string]; } else { return cache[string] = callback.call(this, string); } }; } module.exports = memoizeStringOnly; },{}],130:[function(require,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. * * @providesModule merge */ "use strict"; var mergeInto = require("./mergeInto"); /** * Shallow merges two structures into a return value, without mutating either. * * @param {?object} one Optional object with properties to merge from. * @param {?object} two Optional object with properties to merge from. * @return {object} The shallow extension of one by two. */ var merge = function(one, two) { var result = {}; mergeInto(result, one); mergeInto(result, two); return result; }; module.exports = merge; },{"./mergeInto":132}],131:[function(require,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. * * @providesModule mergeHelpers * * requiresPolyfills: Array.isArray */ "use strict"; var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); /** * Maximum number of levels to traverse. Will catch circular structures. * @const */ var MAX_MERGE_DEPTH = 36; /** * We won't worry about edge cases like new String('x') or new Boolean(true). * Functions are considered terminals, and arrays are not. * @param {*} o The item/object/value to test. * @return {boolean} true iff the argument is a terminal. */ var isTerminal = function(o) { return typeof o !== 'object' || o === null; }; var mergeHelpers = { MAX_MERGE_DEPTH: MAX_MERGE_DEPTH, isTerminal: isTerminal, /** * Converts null/undefined values into empty object. * * @param {?Object=} arg Argument to be normalized (nullable optional) * @return {!Object} */ normalizeMergeArg: function(arg) { return arg === undefined || arg === null ? {} : arg; }, /** * If merging Arrays, a merge strategy *must* be supplied. If not, it is * likely the caller's fault. If this function is ever called with anything * but `one` and `two` being `Array`s, it is the fault of the merge utilities. * * @param {*} one Array to merge into. * @param {*} two Array to merge from. */ checkMergeArrayArgs: function(one, two) { ("production" !== "development" ? invariant( Array.isArray(one) && Array.isArray(two), 'Tried to merge arrays, instead got %s and %s.', one, two ) : invariant(Array.isArray(one) && Array.isArray(two))); }, /** * @param {*} one Object to merge into. * @param {*} two Object to merge from. */ checkMergeObjectArgs: function(one, two) { mergeHelpers.checkMergeObjectArg(one); mergeHelpers.checkMergeObjectArg(two); }, /** * @param {*} arg */ checkMergeObjectArg: function(arg) { ("production" !== "development" ? invariant( !isTerminal(arg) && !Array.isArray(arg), 'Tried to merge an object, instead got %s.', arg ) : invariant(!isTerminal(arg) && !Array.isArray(arg))); }, /** * Checks that a merge was not given a circular object or an object that had * too great of depth. * * @param {number} Level of recursion to validate against maximum. */ checkMergeLevel: function(level) { ("production" !== "development" ? invariant( level < MAX_MERGE_DEPTH, 'Maximum deep merge depth exceeded. You may be attempting to merge ' + 'circular structures in an unsupported way.' ) : invariant(level < MAX_MERGE_DEPTH)); }, /** * Checks that the supplied merge strategy is valid. * * @param {string} Array merge strategy. */ checkArrayStrategy: function(strategy) { ("production" !== "development" ? invariant( strategy === undefined || strategy in mergeHelpers.ArrayStrategies, 'You must provide an array strategy to deep merge functions to ' + 'instruct the deep merge how to resolve merging two arrays.' ) : invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies)); }, /** * Set of possible behaviors of merge algorithms when encountering two Arrays * that must be merged together. * - `clobber`: The left `Array` is ignored. * - `indexByIndex`: The result is achieved by recursively deep merging at * each index. (not yet supported.) */ ArrayStrategies: keyMirror({ Clobber: true, IndexByIndex: true }) }; module.exports = mergeHelpers; },{"./invariant":121,"./keyMirror":127}],132:[function(require,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. * * @providesModule mergeInto * @typechecks static-only */ "use strict"; var mergeHelpers = require("./mergeHelpers"); var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg; /** * Shallow merges two structures by mutating the first parameter. * * @param {object} one Object to be merged into. * @param {?object} two Optional object with properties to merge from. */ function mergeInto(one, two) { checkMergeObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } } module.exports = mergeInto; },{"./mergeHelpers":131}],133:[function(require,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. * * @providesModule mixInto */ "use strict"; /** * Simply copies properties to the prototype. */ var mixInto = function(constructor, methodBag) { var methodName; for (methodName in methodBag) { if (!methodBag.hasOwnProperty(methodName)) { continue; } constructor.prototype[methodName] = methodBag[methodName]; } }; module.exports = mixInto; },{}],134:[function(require,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. * * @providesModule objMap */ "use strict"; /** * For each key/value pair, invokes callback func and constructs a resulting * object which contains, for every key in obj, values that are the result of * of invoking the function: * * func(value, key, iteration) * * @param {?object} obj Object to map keys over * @param {function} func Invoked for each key/val pair. * @param {?*} context * @return {?object} Result of mapping or null if obj is falsey */ function objMap(obj, func, context) { if (!obj) { return null; } var i = 0; var ret = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { ret[key] = func.call(context, obj[key], key, i++); } } return ret; } module.exports = objMap; },{}],135:[function(require,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. * * @providesModule objMapKeyVal */ "use strict"; /** * Behaves the same as `objMap` but invokes func with the key first, and value * second. Use `objMap` unless you need this special case. * Invokes func as: * * func(key, value, iteration) * * @param {?object} obj Object to map keys over * @param {!function} func Invoked for each key/val pair. * @param {?*} context * @return {?object} Result of mapping or null if obj is falsey */ function objMapKeyVal(obj, func, context) { if (!obj) { return null; } var i = 0; var ret = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { ret[key] = func.call(context, key, obj[key], i++); } } return ret; } module.exports = objMapKeyVal; },{}],136:[function(require,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. * * @providesModule onlyChild */ "use strict"; var ReactComponent = require("./ReactComponent"); var invariant = require("./invariant"); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { ("production" !== "development" ? invariant( ReactComponent.isValidComponent(children), 'onlyChild must be passed a children with exactly one child.' ) : invariant(ReactComponent.isValidComponent(children))); return children; } module.exports = onlyChild; },{"./ReactComponent":30,"./invariant":121}],137:[function(require,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. * * @providesModule performanceNow * @typechecks static-only */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); /** * Detect if we can use window.performance.now() and gracefully * fallback to Date.now() if it doesn't exist. * We need to support Firefox < 15 for now due to Facebook's webdriver * infrastructure. */ var performance = null; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.webkitPerformance; } if (!performance || !performance.now) { performance = Date; } var performanceNow = performance.now.bind(performance); module.exports = performanceNow; },{"./ExecutionEnvironment":21}],138:[function(require,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. * * @providesModule shallowEqual */ "use strict"; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B'a keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; },{}],139:[function(require,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. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ "use strict"; /** * Given a `prevComponent` and `nextComponent`, determines if `prevComponent` * should be updated as opposed to being destroyed or replaced. * * @param {?object} prevComponent * @param {?object} nextComponent * @return {boolean} True if `prevComponent` should be updated. * @protected */ function shouldUpdateReactComponent(prevComponent, nextComponent) { // TODO: Remove warning after a release. if (prevComponent && nextComponent && prevComponent.constructor === nextComponent.constructor && ( (prevComponent.props && prevComponent.props.key) === (nextComponent.props && nextComponent.props.key) )) { if (prevComponent._owner === nextComponent._owner) { return true; } else { if ("production" !== "development") { if (prevComponent.state) { console.warn( 'A recent change to React has been found to impact your code. ' + 'A mounted component will now be unmounted and replaced by a ' + 'component (of the same class) if their owners are different. ' + 'Previously, ownership was not considered when updating.', prevComponent, nextComponent ); } } } } return false; } module.exports = shouldUpdateReactComponent; },{}],140:[function(require,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. * * @providesModule toArray * @typechecks */ var invariant = require("./invariant"); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFrom. * * @param {object|function} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). ("production" !== "development" ? invariant( !Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'), 'toArray: Array-like object expected' ) : invariant(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'))); ("production" !== "development" ? invariant( typeof length === 'number', 'toArray: Object needs a length property' ) : invariant(typeof length === 'number')); ("production" !== "development" ? invariant( length === 0 || (length - 1) in obj, 'toArray: Object should have keys for indices' ) : invariant(length === 0 || (length - 1) in obj)); // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; },{"./invariant":121}],141:[function(require,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. * * @providesModule traverseAllChildren */ "use strict"; var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactTextComponent = require("./ReactTextComponent"); var invariant = require("./invariant"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that: * 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`. * 2. it('should fail when supplied duplicate key', function() { * 3. That a single child and an array with one item have the same key pattern. * }); */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { if (component && component.props && component.props.key != null) { // Explicit key return wrapUserProvidedKey(component.props.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} key Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace( userProvidedKeyEscapeRegex, userProvidedKeyEscaper ); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!number} indexSoFar Number of children encountered until this point. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ var traverseAllChildrenImpl = function(children, nameSoFar, indexSoFar, callback, traverseContext) { var subtreeCount = 0; // Count of children found in the current subtree. if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var nextName = ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + getComponentKey(child, i) ); var nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } else { var type = typeof children; var isOnlyChild = nameSoFar === ''; // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows var storageName = isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar; if (children == null || type === 'boolean') { // All of the above are perceived as null. callback(traverseContext, null, storageName, indexSoFar); subtreeCount = 1; } else if (children.mountComponentIntoNode) { callback(traverseContext, children, storageName, indexSoFar); subtreeCount = 1; } else { if (type === 'object') { ("production" !== "development" ? invariant( !children || children.nodeType !== 1, 'traverseAllChildren(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.' ) : invariant(!children || children.nodeType !== 1)); for (var key in children) { if (children.hasOwnProperty(key)) { subtreeCount += traverseAllChildrenImpl( children[key], ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(key) + SUBSEPARATOR + getComponentKey(children[key], 0) ), indexSoFar + subtreeCount, callback, traverseContext ); } } } else if (type === 'string') { var normalizedText = new ReactTextComponent(children); callback(traverseContext, normalizedText, storageName, indexSoFar); subtreeCount += 1; } else if (type === 'number') { var normalizedNumber = new ReactTextComponent('' + children); callback(traverseContext, normalizedNumber, storageName, indexSoFar); subtreeCount += 1; } } } return subtreeCount; }; /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. */ function traverseAllChildren(children, callback, traverseContext) { if (children !== null && children !== undefined) { traverseAllChildrenImpl(children, '', 0, callback, traverseContext); } } module.exports = traverseAllChildren; },{"./ReactInstanceHandles":57,"./ReactTextComponent":76,"./invariant":121}],142:[function(require,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. * * @providesModule warning */ "use strict"; var emptyFunction = require("./emptyFunction"); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== "development") { warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (!condition) { var argIndex = 0; console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];})); } }; } module.exports = warning; },{"./emptyFunction":108}]},{},[81]) (81) });
ajax/libs/pusher/4.2.1/react-native/pusher.js
jdh8/cdnjs
/*! * Pusher JavaScript Library v4.2.1 * https://pusher.com/ * * Copyright 2017, Pusher * Released under the MIT licence. */ module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var pusher_1 = __webpack_require__(1); module.exports = pusher_1["default"]; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(2); var Collections = __webpack_require__(4); var dispatcher_1 = __webpack_require__(14); var timeline_1 = __webpack_require__(31); var level_1 = __webpack_require__(32); var StrategyBuilder = __webpack_require__(33); var timers_1 = __webpack_require__(7); var defaults_1 = __webpack_require__(11); var DefaultConfig = __webpack_require__(56); var logger_1 = __webpack_require__(16); var factory_1 = __webpack_require__(35); var url_store_1 = __webpack_require__(29); var Pusher = (function () { function Pusher(app_key, options) { var _this = this; checkAppKey(app_key); options = options || {}; if (!options.cluster) { var suffix = url_store_1["default"].buildLogSuffix("javascriptQuickStart"); logger_1["default"].warn("You should always specify a cluster when connecting. " + suffix); } this.key = app_key; this.config = Collections.extend(DefaultConfig.getGlobalConfig(), options.cluster ? DefaultConfig.getClusterConfig(options.cluster) : {}, options); this.channels = factory_1["default"].createChannels(); this.global_emitter = new dispatcher_1["default"](); this.sessionID = Math.floor(Math.random() * 1000000000); this.timeline = new timeline_1["default"](this.key, this.sessionID, { cluster: this.config.cluster, features: Pusher.getClientFeatures(), params: this.config.timelineParams || {}, limit: 50, level: level_1["default"].INFO, version: defaults_1["default"].VERSION }); if (!this.config.disableStats) { this.timelineSender = factory_1["default"].createTimelineSender(this.timeline, { host: this.config.statsHost, path: "/timeline/v2/" + runtime_1["default"].TimelineTransport.name }); } var getStrategy = function (options) { var config = Collections.extend({}, _this.config, options); return StrategyBuilder.build(runtime_1["default"].getDefaultStrategy(config), config); }; this.connection = factory_1["default"].createConnectionManager(this.key, Collections.extend({ getStrategy: getStrategy, timeline: this.timeline, activityTimeout: this.config.activity_timeout, pongTimeout: this.config.pong_timeout, unavailableTimeout: this.config.unavailable_timeout }, this.config, { encrypted: this.isEncrypted() })); this.connection.bind('connected', function () { _this.subscribeAll(); if (_this.timelineSender) { _this.timelineSender.send(_this.connection.isEncrypted()); } }); this.connection.bind('message', function (params) { var internal = (params.event.indexOf('pusher_internal:') === 0); if (params.channel) { var channel = _this.channel(params.channel); if (channel) { channel.handleEvent(params.event, params.data); } } if (!internal) { _this.global_emitter.emit(params.event, params.data); } }); this.connection.bind('connecting', function () { _this.channels.disconnect(); }); this.connection.bind('disconnected', function () { _this.channels.disconnect(); }); this.connection.bind('error', function (err) { logger_1["default"].warn('Error', err); }); Pusher.instances.push(this); this.timeline.info({ instances: Pusher.instances.length }); if (Pusher.isReady) { this.connect(); } } Pusher.ready = function () { Pusher.isReady = true; for (var i = 0, l = Pusher.instances.length; i < l; i++) { Pusher.instances[i].connect(); } }; Pusher.log = function (message) { if (Pusher.logToConsole && global.console && global.console.log) { global.console.log(message); } }; Pusher.getClientFeatures = function () { return Collections.keys(Collections.filterObject({ "ws": runtime_1["default"].Transports.ws }, function (t) { return t.isSupported({}); })); }; Pusher.prototype.channel = function (name) { return this.channels.find(name); }; Pusher.prototype.allChannels = function () { return this.channels.all(); }; Pusher.prototype.connect = function () { this.connection.connect(); if (this.timelineSender) { if (!this.timelineSenderTimer) { var encrypted = this.connection.isEncrypted(); var timelineSender = this.timelineSender; this.timelineSenderTimer = new timers_1.PeriodicTimer(60000, function () { timelineSender.send(encrypted); }); } } }; Pusher.prototype.disconnect = function () { this.connection.disconnect(); if (this.timelineSenderTimer) { this.timelineSenderTimer.ensureAborted(); this.timelineSenderTimer = null; } }; Pusher.prototype.bind = function (event_name, callback, context) { this.global_emitter.bind(event_name, callback, context); return this; }; Pusher.prototype.unbind = function (event_name, callback, context) { this.global_emitter.unbind(event_name, callback, context); return this; }; Pusher.prototype.bind_global = function (callback) { this.global_emitter.bind_global(callback); return this; }; Pusher.prototype.unbind_global = function (callback) { this.global_emitter.unbind_global(callback); return this; }; Pusher.prototype.unbind_all = function (callback) { this.global_emitter.unbind_all(); return this; }; Pusher.prototype.subscribeAll = function () { var channelName; for (channelName in this.channels.channels) { if (this.channels.channels.hasOwnProperty(channelName)) { this.subscribe(channelName); } } }; Pusher.prototype.subscribe = function (channel_name) { var channel = this.channels.add(channel_name, this); if (channel.subscriptionPending && channel.subscriptionCancelled) { channel.reinstateSubscription(); } else if (!channel.subscriptionPending && this.connection.state === "connected") { channel.subscribe(); } return channel; }; Pusher.prototype.unsubscribe = function (channel_name) { var channel = this.channels.find(channel_name); if (channel && channel.subscriptionPending) { channel.cancelSubscription(); } else { channel = this.channels.remove(channel_name); if (channel && this.connection.state === "connected") { channel.unsubscribe(); } } }; Pusher.prototype.send_event = function (event_name, data, channel) { return this.connection.send_event(event_name, data, channel); }; Pusher.prototype.isEncrypted = function () { if (runtime_1["default"].getProtocol() === "https:") { return true; } else { return Boolean(this.config.encrypted); } }; Pusher.instances = []; Pusher.isReady = false; Pusher.logToConsole = false; Pusher.Runtime = runtime_1["default"]; Pusher.ScriptReceivers = runtime_1["default"].ScriptReceivers; Pusher.DependenciesReceivers = runtime_1["default"].DependenciesReceivers; Pusher.auth_callbacks = runtime_1["default"].auth_callbacks; return Pusher; }()); exports.__esModule = true; exports["default"] = Pusher; function checkAppKey(key) { if (key === null || key === undefined) { throw "You must pass your app key when you instantiate Pusher."; } } runtime_1["default"].setup(Pusher); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(3); var net_info_1 = __webpack_require__(26); var xhr_auth_1 = __webpack_require__(28); var xhr_timeline_1 = __webpack_require__(30); var getDefaultStrategy = runtime_1["default"].getDefaultStrategy, Transports = runtime_1["default"].Transports, setup = runtime_1["default"].setup, getProtocol = runtime_1["default"].getProtocol, isXHRSupported = runtime_1["default"].isXHRSupported, getLocalStorage = runtime_1["default"].getLocalStorage, createXHR = runtime_1["default"].createXHR, createWebSocket = runtime_1["default"].createWebSocket, addUnloadListener = runtime_1["default"].addUnloadListener, removeUnloadListener = runtime_1["default"].removeUnloadListener, transportConnectionInitializer = runtime_1["default"].transportConnectionInitializer, createSocketRequest = runtime_1["default"].createSocketRequest, HTTPFactory = runtime_1["default"].HTTPFactory; var ReactNative = { getDefaultStrategy: getDefaultStrategy, Transports: Transports, setup: setup, getProtocol: getProtocol, isXHRSupported: isXHRSupported, getLocalStorage: getLocalStorage, createXHR: createXHR, createWebSocket: createWebSocket, addUnloadListener: addUnloadListener, removeUnloadListener: removeUnloadListener, transportConnectionInitializer: transportConnectionInitializer, createSocketRequest: createSocketRequest, HTTPFactory: HTTPFactory, TimelineTransport: xhr_timeline_1["default"], getAuthorizers: function () { return { ajax: xhr_auth_1["default"] }; }, getWebSocketAPI: function () { return WebSocket; }, getXHRAPI: function () { return XMLHttpRequest; }, getNetwork: function () { return net_info_1.Network; } }; exports.__esModule = true; exports["default"] = ReactNative; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var transports_1 = __webpack_require__(9); var default_strategy_1 = __webpack_require__(17); var transport_connection_initializer_1 = __webpack_require__(18); var http_1 = __webpack_require__(19); var Isomorphic = { getDefaultStrategy: default_strategy_1["default"], Transports: transports_1["default"], transportConnectionInitializer: transport_connection_initializer_1["default"], HTTPFactory: http_1["default"], setup: function (PusherClass) { PusherClass.ready(); }, getLocalStorage: function () { return undefined; }, getClientFeatures: function () { return Collections.keys(Collections.filterObject({ "ws": transports_1["default"].ws }, function (t) { return t.isSupported({}); })); }, getProtocol: function () { return "http:"; }, isXHRSupported: function () { return true; }, createSocketRequest: function (method, url) { if (this.isXHRSupported()) { return this.HTTPFactory.createXHR(method, url); } else { throw "Cross-origin HTTP requests are not supported"; } }, createXHR: function () { var Constructor = this.getXHRAPI(); return new Constructor(); }, createWebSocket: function (url) { var Constructor = this.getWebSocketAPI(); return new Constructor(url); }, addUnloadListener: function (listener) { }, removeUnloadListener: function (listener) { } }; exports.__esModule = true; exports["default"] = Isomorphic; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var base64_1 = __webpack_require__(5); var util_1 = __webpack_require__(6); function extend(target) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } for (var i = 0; i < sources.length; i++) { var extensions = sources[i]; for (var property in extensions) { if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) { target[property] = extend(target[property] || {}, extensions[property]); } else { target[property] = extensions[property]; } } } return target; } exports.extend = extend; function stringify() { var m = ["Pusher"]; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === "string") { m.push(arguments[i]); } else { m.push(safeJSONStringify(arguments[i])); } } return m.join(" : "); } exports.stringify = stringify; function arrayIndexOf(array, item) { var nativeIndexOf = Array.prototype.indexOf; if (array === null) { return -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) { return array.indexOf(item); } for (var i = 0, l = array.length; i < l; i++) { if (array[i] === item) { return i; } } return -1; } exports.arrayIndexOf = arrayIndexOf; function objectApply(object, f) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { f(object[key], key, object); } } } exports.objectApply = objectApply; function keys(object) { var keys = []; objectApply(object, function (_, key) { keys.push(key); }); return keys; } exports.keys = keys; function values(object) { var values = []; objectApply(object, function (value) { values.push(value); }); return values; } exports.values = values; function apply(array, f, context) { for (var i = 0; i < array.length; i++) { f.call(context || global, array[i], i, array); } } exports.apply = apply; function map(array, f) { var result = []; for (var i = 0; i < array.length; i++) { result.push(f(array[i], i, array, result)); } return result; } exports.map = map; function mapObject(object, f) { var result = {}; objectApply(object, function (value, key) { result[key] = f(value); }); return result; } exports.mapObject = mapObject; function filter(array, test) { test = test || function (value) { return !!value; }; var result = []; for (var i = 0; i < array.length; i++) { if (test(array[i], i, array, result)) { result.push(array[i]); } } return result; } exports.filter = filter; function filterObject(object, test) { var result = {}; objectApply(object, function (value, key) { if ((test && test(value, key, object, result)) || Boolean(value)) { result[key] = value; } }); return result; } exports.filterObject = filterObject; function flatten(object) { var result = []; objectApply(object, function (value, key) { result.push([key, value]); }); return result; } exports.flatten = flatten; function any(array, test) { for (var i = 0; i < array.length; i++) { if (test(array[i], i, array)) { return true; } } return false; } exports.any = any; function all(array, test) { for (var i = 0; i < array.length; i++) { if (!test(array[i], i, array)) { return false; } } return true; } exports.all = all; function encodeParamsObject(data) { return mapObject(data, function (value) { if (typeof value === "object") { value = safeJSONStringify(value); } return encodeURIComponent(base64_1["default"](value.toString())); }); } exports.encodeParamsObject = encodeParamsObject; function buildQueryString(data) { var params = filterObject(data, function (value) { return value !== undefined; }); var query = map(flatten(encodeParamsObject(params)), util_1["default"].method("join", "=")).join("&"); return query; } exports.buildQueryString = buildQueryString; function decycleObject(object) { var objects = [], paths = []; return (function derez(value, path) { var i, name, nu; switch (typeof value) { case 'object': if (!value) { return null; } for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return { $ref: paths[i] }; } } objects.push(value); paths.push(path); if (Object.prototype.toString.apply(value) === '[object Array]') { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = derez(value[i], path + '[' + i + ']'); } } else { nu = {}; for (name in value) { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']'); } } } return nu; case 'number': case 'string': case 'boolean': return value; } }(object, '$')); } exports.decycleObject = decycleObject; function safeJSONStringify(source) { try { return JSON.stringify(source); } catch (e) { return JSON.stringify(decycleObject(source)); } } exports.safeJSONStringify = safeJSONStringify; /***/ }), /* 5 */ /***/ (function(module, exports) { "use strict"; function encode(s) { return btoa(utob(s)); } exports.__esModule = true; exports["default"] = encode; var fromCharCode = String.fromCharCode; var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = {}; for (var i = 0, l = b64chars.length; i < l; i++) { b64tab[b64chars.charAt(i)] = i; } var cb_utob = function (c) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f)) : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | (cc & 0x3f)); }; var utob = function (u) { return u.replace(/[^\x00-\x7F]/g, cb_utob); }; var cb_encode = function (ccc) { var padlen = [0, 2, 1][ccc.length % 3]; var ord = ccc.charCodeAt(0) << 16 | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)); var chars = [ b64chars.charAt(ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = global.btoa || function (b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var timers_1 = __webpack_require__(7); var Util = { now: function () { if (Date.now) { return Date.now(); } else { return new Date().valueOf(); } }, defer: function (callback) { return new timers_1.OneOffTimer(0, callback); }, method: function (name) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var boundArguments = Array.prototype.slice.call(arguments, 1); return function (object) { return object[name].apply(object, boundArguments.concat(arguments)); }; } }; exports.__esModule = true; exports["default"] = Util; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var abstract_timer_1 = __webpack_require__(8); function clearTimeout(timer) { global.clearTimeout(timer); } function clearInterval(timer) { global.clearInterval(timer); } var OneOffTimer = (function (_super) { __extends(OneOffTimer, _super); function OneOffTimer(delay, callback) { _super.call(this, setTimeout, clearTimeout, delay, function (timer) { callback(); return null; }); } return OneOffTimer; }(abstract_timer_1["default"])); exports.OneOffTimer = OneOffTimer; var PeriodicTimer = (function (_super) { __extends(PeriodicTimer, _super); function PeriodicTimer(delay, callback) { _super.call(this, setInterval, clearInterval, delay, function (timer) { callback(); return timer; }); } return PeriodicTimer; }(abstract_timer_1["default"])); exports.PeriodicTimer = PeriodicTimer; /***/ }), /* 8 */ /***/ (function(module, exports) { "use strict"; var Timer = (function () { function Timer(set, clear, delay, callback) { var _this = this; this.clear = clear; this.timer = set(function () { if (_this.timer) { _this.timer = callback(_this.timer); } }, delay); } Timer.prototype.isRunning = function () { return this.timer !== null; }; Timer.prototype.ensureAborted = function () { if (this.timer) { this.clear(this.timer); this.timer = null; } }; return Timer; }()); exports.__esModule = true; exports["default"] = Timer; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var URLSchemes = __webpack_require__(10); var transport_1 = __webpack_require__(12); var Collections = __webpack_require__(4); var runtime_1 = __webpack_require__(2); var WSTransport = new transport_1["default"]({ urls: URLSchemes.ws, handlesActivityChecks: false, supportsPing: false, isInitialized: function () { return Boolean(runtime_1["default"].getWebSocketAPI()); }, isSupported: function () { return Boolean(runtime_1["default"].getWebSocketAPI()); }, getSocket: function (url) { return runtime_1["default"].createWebSocket(url); } }); var httpConfiguration = { urls: URLSchemes.http, handlesActivityChecks: false, supportsPing: true, isInitialized: function () { return true; } }; exports.streamingConfiguration = Collections.extend({ getSocket: function (url) { return runtime_1["default"].HTTPFactory.createStreamingSocket(url); } }, httpConfiguration); exports.pollingConfiguration = Collections.extend({ getSocket: function (url) { return runtime_1["default"].HTTPFactory.createPollingSocket(url); } }, httpConfiguration); var xhrConfiguration = { isSupported: function () { return runtime_1["default"].isXHRSupported(); } }; var XHRStreamingTransport = new transport_1["default"](Collections.extend({}, exports.streamingConfiguration, xhrConfiguration)); var XHRPollingTransport = new transport_1["default"](Collections.extend({}, exports.pollingConfiguration, xhrConfiguration)); var Transports = { ws: WSTransport, xhr_streaming: XHRStreamingTransport, xhr_polling: XHRPollingTransport }; exports.__esModule = true; exports["default"] = Transports; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var defaults_1 = __webpack_require__(11); function getGenericURL(baseScheme, params, path) { var scheme = baseScheme + (params.encrypted ? "s" : ""); var host = params.encrypted ? params.hostEncrypted : params.hostUnencrypted; return scheme + "://" + host + path; } function getGenericPath(key, queryString) { var path = "/app/" + key; var query = "?protocol=" + defaults_1["default"].PROTOCOL + "&client=js" + "&version=" + defaults_1["default"].VERSION + (queryString ? ("&" + queryString) : ""); return path + query; } exports.ws = { getInitial: function (key, params) { return getGenericURL("ws", params, getGenericPath(key, "flash=false")); } }; exports.http = { getInitial: function (key, params) { var path = (params.httpPath || "/pusher") + getGenericPath(key); return getGenericURL("http", params, path); } }; exports.sockjs = { getInitial: function (key, params) { return getGenericURL("http", params, params.httpPath || "/pusher"); }, getPath: function (key, params) { return getGenericPath(key); } }; /***/ }), /* 11 */ /***/ (function(module, exports) { "use strict"; var Defaults = { VERSION: "4.2.1", PROTOCOL: 7, host: 'ws.pusherapp.com', ws_port: 80, wss_port: 443, sockjs_host: 'sockjs.pusher.com', sockjs_http_port: 80, sockjs_https_port: 443, sockjs_path: "/pusher", stats_host: 'stats.pusher.com', channel_auth_endpoint: '/pusher/auth', channel_auth_transport: 'ajax', activity_timeout: 120000, pong_timeout: 30000, unavailable_timeout: 10000, cdn_http: 'http://js.pusher.com', cdn_https: 'https://js.pusher.com', dependency_suffix: '' }; exports.__esModule = true; exports["default"] = Defaults; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var transport_connection_1 = __webpack_require__(13); var Transport = (function () { function Transport(hooks) { this.hooks = hooks; } Transport.prototype.isSupported = function (environment) { return this.hooks.isSupported(environment); }; Transport.prototype.createConnection = function (name, priority, key, options) { return new transport_connection_1["default"](this.hooks, name, priority, key, options); }; return Transport; }()); exports.__esModule = true; exports["default"] = Transport; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var util_1 = __webpack_require__(6); var Collections = __webpack_require__(4); var dispatcher_1 = __webpack_require__(14); var logger_1 = __webpack_require__(16); var runtime_1 = __webpack_require__(2); var TransportConnection = (function (_super) { __extends(TransportConnection, _super); function TransportConnection(hooks, name, priority, key, options) { _super.call(this); this.initialize = runtime_1["default"].transportConnectionInitializer; this.hooks = hooks; this.name = name; this.priority = priority; this.key = key; this.options = options; this.state = "new"; this.timeline = options.timeline; this.activityTimeout = options.activityTimeout; this.id = this.timeline.generateUniqueID(); } TransportConnection.prototype.handlesActivityChecks = function () { return Boolean(this.hooks.handlesActivityChecks); }; TransportConnection.prototype.supportsPing = function () { return Boolean(this.hooks.supportsPing); }; TransportConnection.prototype.connect = function () { var _this = this; if (this.socket || this.state !== "initialized") { return false; } var url = this.hooks.urls.getInitial(this.key, this.options); try { this.socket = this.hooks.getSocket(url, this.options); } catch (e) { util_1["default"].defer(function () { _this.onError(e); _this.changeState("closed"); }); return false; } this.bindListeners(); logger_1["default"].debug("Connecting", { transport: this.name, url: url }); this.changeState("connecting"); return true; }; TransportConnection.prototype.close = function () { if (this.socket) { this.socket.close(); return true; } else { return false; } }; TransportConnection.prototype.send = function (data) { var _this = this; if (this.state === "open") { util_1["default"].defer(function () { if (_this.socket) { _this.socket.send(data); } }); return true; } else { return false; } }; TransportConnection.prototype.ping = function () { if (this.state === "open" && this.supportsPing()) { this.socket.ping(); } }; TransportConnection.prototype.onOpen = function () { if (this.hooks.beforeOpen) { this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options)); } this.changeState("open"); this.socket.onopen = undefined; }; TransportConnection.prototype.onError = function (error) { this.emit("error", { type: 'WebSocketError', error: error }); this.timeline.error(this.buildTimelineMessage({ error: error.toString() })); }; TransportConnection.prototype.onClose = function (closeEvent) { if (closeEvent) { this.changeState("closed", { code: closeEvent.code, reason: closeEvent.reason, wasClean: closeEvent.wasClean }); } else { this.changeState("closed"); } this.unbindListeners(); this.socket = undefined; }; TransportConnection.prototype.onMessage = function (message) { this.emit("message", message); }; TransportConnection.prototype.onActivity = function () { this.emit("activity"); }; TransportConnection.prototype.bindListeners = function () { var _this = this; this.socket.onopen = function () { _this.onOpen(); }; this.socket.onerror = function (error) { _this.onError(error); }; this.socket.onclose = function (closeEvent) { _this.onClose(closeEvent); }; this.socket.onmessage = function (message) { _this.onMessage(message); }; if (this.supportsPing()) { this.socket.onactivity = function () { _this.onActivity(); }; } }; TransportConnection.prototype.unbindListeners = function () { if (this.socket) { this.socket.onopen = undefined; this.socket.onerror = undefined; this.socket.onclose = undefined; this.socket.onmessage = undefined; if (this.supportsPing()) { this.socket.onactivity = undefined; } } }; TransportConnection.prototype.changeState = function (state, params) { this.state = state; this.timeline.info(this.buildTimelineMessage({ state: state, params: params })); this.emit(state, params); }; TransportConnection.prototype.buildTimelineMessage = function (message) { return Collections.extend({ cid: this.id }, message); }; return TransportConnection; }(dispatcher_1["default"])); exports.__esModule = true; exports["default"] = TransportConnection; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var callback_registry_1 = __webpack_require__(15); var Dispatcher = (function () { function Dispatcher(failThrough) { this.callbacks = new callback_registry_1["default"](); this.global_callbacks = []; this.failThrough = failThrough; } Dispatcher.prototype.bind = function (eventName, callback, context) { this.callbacks.add(eventName, callback, context); return this; }; Dispatcher.prototype.bind_global = function (callback) { this.global_callbacks.push(callback); return this; }; Dispatcher.prototype.unbind = function (eventName, callback, context) { this.callbacks.remove(eventName, callback, context); return this; }; Dispatcher.prototype.unbind_global = function (callback) { if (!callback) { this.global_callbacks = []; return this; } this.global_callbacks = Collections.filter(this.global_callbacks || [], function (c) { return c !== callback; }); return this; }; Dispatcher.prototype.unbind_all = function () { this.unbind(); this.unbind_global(); return this; }; Dispatcher.prototype.emit = function (eventName, data) { var i; for (i = 0; i < this.global_callbacks.length; i++) { this.global_callbacks[i](eventName, data); } var callbacks = this.callbacks.get(eventName); if (callbacks && callbacks.length > 0) { for (i = 0; i < callbacks.length; i++) { callbacks[i].fn.call(callbacks[i].context || global, data); } } else if (this.failThrough) { this.failThrough(eventName, data); } return this; }; return Dispatcher; }()); exports.__esModule = true; exports["default"] = Dispatcher; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var CallbackRegistry = (function () { function CallbackRegistry() { this._callbacks = {}; } CallbackRegistry.prototype.get = function (name) { return this._callbacks[prefix(name)]; }; CallbackRegistry.prototype.add = function (name, callback, context) { var prefixedEventName = prefix(name); this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || []; this._callbacks[prefixedEventName].push({ fn: callback, context: context }); }; CallbackRegistry.prototype.remove = function (name, callback, context) { if (!name && !callback && !context) { this._callbacks = {}; return; } var names = name ? [prefix(name)] : Collections.keys(this._callbacks); if (callback || context) { this.removeCallback(names, callback, context); } else { this.removeAllCallbacks(names); } }; CallbackRegistry.prototype.removeCallback = function (names, callback, context) { Collections.apply(names, function (name) { this._callbacks[name] = Collections.filter(this._callbacks[name] || [], function (binding) { return (callback && callback !== binding.fn) || (context && context !== binding.context); }); if (this._callbacks[name].length === 0) { delete this._callbacks[name]; } }, this); }; CallbackRegistry.prototype.removeAllCallbacks = function (names) { Collections.apply(names, function (name) { delete this._callbacks[name]; }, this); }; return CallbackRegistry; }()); exports.__esModule = true; exports["default"] = CallbackRegistry; function prefix(name) { return "_" + name; } /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var collections_1 = __webpack_require__(4); var pusher_1 = __webpack_require__(1); var Logger = { debug: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } if (!pusher_1["default"].log) { return; } pusher_1["default"].log(collections_1.stringify.apply(this, arguments)); }, warn: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } var message = collections_1.stringify.apply(this, arguments); if (global.console) { if (global.console.warn) { global.console.warn(message); } else if (global.console.log) { global.console.log(message); } } if (pusher_1["default"].log) { pusher_1["default"].log(message); } } }; exports.__esModule = true; exports["default"] = Logger; /***/ }), /* 17 */ /***/ (function(module, exports) { "use strict"; var getDefaultStrategy = function (config) { var wsStrategy; if (config.encrypted) { wsStrategy = [ ":best_connected_ever", ":ws_loop", [":delayed", 2000, [":http_loop"]] ]; } else { wsStrategy = [ ":best_connected_ever", ":ws_loop", [":delayed", 2000, [":wss_loop"]], [":delayed", 5000, [":http_loop"]] ]; } return [ [":def", "ws_options", { hostUnencrypted: config.wsHost + ":" + config.wsPort, hostEncrypted: config.wsHost + ":" + config.wssPort }], [":def", "wss_options", [":extend", ":ws_options", { encrypted: true }]], [":def", "http_options", { hostUnencrypted: config.httpHost + ":" + config.httpPort, hostEncrypted: config.httpHost + ":" + config.httpsPort, httpPath: config.httpPath }], [":def", "timeouts", { loop: true, timeout: 15000, timeoutLimit: 60000 }], [":def", "ws_manager", [":transport_manager", { lives: 2, minPingDelay: 10000, maxPingDelay: config.activity_timeout }]], [":def", "streaming_manager", [":transport_manager", { lives: 2, minPingDelay: 10000, maxPingDelay: config.activity_timeout }]], [":def_transport", "ws", "ws", 3, ":ws_options", ":ws_manager"], [":def_transport", "wss", "ws", 3, ":wss_options", ":ws_manager"], [":def_transport", "xhr_streaming", "xhr_streaming", 1, ":http_options", ":streaming_manager"], [":def_transport", "xhr_polling", "xhr_polling", 1, ":http_options"], [":def", "ws_loop", [":sequential", ":timeouts", ":ws"]], [":def", "wss_loop", [":sequential", ":timeouts", ":wss"]], [":def", "streaming_loop", [":sequential", ":timeouts", ":xhr_streaming"]], [":def", "polling_loop", [":sequential", ":timeouts", ":xhr_polling"]], [":def", "http_loop", [":if", [":is_supported", ":streaming_loop"], [ ":best_connected_ever", ":streaming_loop", [":delayed", 4000, [":polling_loop"]] ], [ ":polling_loop" ]]], [":def", "strategy", [":cached", 1800000, [":first_connected", [":if", [":is_supported", ":ws"], wsStrategy, ":http_loop" ] ] ] ] ]; }; exports.__esModule = true; exports["default"] = getDefaultStrategy; /***/ }), /* 18 */ /***/ (function(module, exports) { "use strict"; function default_1() { var self = this; self.timeline.info(self.buildTimelineMessage({ transport: self.name + (self.options.encrypted ? "s" : "") })); if (self.hooks.isInitialized()) { self.changeState("initialized"); } else { self.onClose(); } } exports.__esModule = true; exports["default"] = default_1; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var http_request_1 = __webpack_require__(20); var http_socket_1 = __webpack_require__(21); var http_streaming_socket_1 = __webpack_require__(23); var http_polling_socket_1 = __webpack_require__(24); var http_xhr_request_1 = __webpack_require__(25); var HTTP = { createStreamingSocket: function (url) { return this.createSocket(http_streaming_socket_1["default"], url); }, createPollingSocket: function (url) { return this.createSocket(http_polling_socket_1["default"], url); }, createSocket: function (hooks, url) { return new http_socket_1["default"](hooks, url); }, createXHR: function (method, url) { return this.createRequest(http_xhr_request_1["default"], method, url); }, createRequest: function (hooks, method, url) { return new http_request_1["default"](hooks, method, url); } }; exports.__esModule = true; exports["default"] = HTTP; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var runtime_1 = __webpack_require__(2); var dispatcher_1 = __webpack_require__(14); var MAX_BUFFER_LENGTH = 256 * 1024; var HTTPRequest = (function (_super) { __extends(HTTPRequest, _super); function HTTPRequest(hooks, method, url) { _super.call(this); this.hooks = hooks; this.method = method; this.url = url; } HTTPRequest.prototype.start = function (payload) { var _this = this; this.position = 0; this.xhr = this.hooks.getRequest(this); this.unloader = function () { _this.close(); }; runtime_1["default"].addUnloadListener(this.unloader); this.xhr.open(this.method, this.url, true); if (this.xhr.setRequestHeader) { this.xhr.setRequestHeader("Content-Type", "application/json"); } this.xhr.send(payload); }; HTTPRequest.prototype.close = function () { if (this.unloader) { runtime_1["default"].removeUnloadListener(this.unloader); this.unloader = null; } if (this.xhr) { this.hooks.abortRequest(this.xhr); this.xhr = null; } }; HTTPRequest.prototype.onChunk = function (status, data) { while (true) { var chunk = this.advanceBuffer(data); if (chunk) { this.emit("chunk", { status: status, data: chunk }); } else { break; } } if (this.isBufferTooLong(data)) { this.emit("buffer_too_long"); } }; HTTPRequest.prototype.advanceBuffer = function (buffer) { var unreadData = buffer.slice(this.position); var endOfLinePosition = unreadData.indexOf("\n"); if (endOfLinePosition !== -1) { this.position += endOfLinePosition + 1; return unreadData.slice(0, endOfLinePosition); } else { return null; } }; HTTPRequest.prototype.isBufferTooLong = function (buffer) { return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH; }; return HTTPRequest; }(dispatcher_1["default"])); exports.__esModule = true; exports["default"] = HTTPRequest; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var state_1 = __webpack_require__(22); var util_1 = __webpack_require__(6); var runtime_1 = __webpack_require__(2); var autoIncrement = 1; var HTTPSocket = (function () { function HTTPSocket(hooks, url) { this.hooks = hooks; this.session = randomNumber(1000) + "/" + randomString(8); this.location = getLocation(url); this.readyState = state_1["default"].CONNECTING; this.openStream(); } HTTPSocket.prototype.send = function (payload) { return this.sendRaw(JSON.stringify([payload])); }; HTTPSocket.prototype.ping = function () { this.hooks.sendHeartbeat(this); }; HTTPSocket.prototype.close = function (code, reason) { this.onClose(code, reason, true); }; HTTPSocket.prototype.sendRaw = function (payload) { if (this.readyState === state_1["default"].OPEN) { try { runtime_1["default"].createSocketRequest("POST", getUniqueURL(getSendURL(this.location, this.session))).start(payload); return true; } catch (e) { return false; } } else { return false; } }; HTTPSocket.prototype.reconnect = function () { this.closeStream(); this.openStream(); }; ; HTTPSocket.prototype.onClose = function (code, reason, wasClean) { this.closeStream(); this.readyState = state_1["default"].CLOSED; if (this.onclose) { this.onclose({ code: code, reason: reason, wasClean: wasClean }); } }; HTTPSocket.prototype.onChunk = function (chunk) { if (chunk.status !== 200) { return; } if (this.readyState === state_1["default"].OPEN) { this.onActivity(); } var payload; var type = chunk.data.slice(0, 1); switch (type) { case 'o': payload = JSON.parse(chunk.data.slice(1) || '{}'); this.onOpen(payload); break; case 'a': payload = JSON.parse(chunk.data.slice(1) || '[]'); for (var i = 0; i < payload.length; i++) { this.onEvent(payload[i]); } break; case 'm': payload = JSON.parse(chunk.data.slice(1) || 'null'); this.onEvent(payload); break; case 'h': this.hooks.onHeartbeat(this); break; case 'c': payload = JSON.parse(chunk.data.slice(1) || '[]'); this.onClose(payload[0], payload[1], true); break; } }; HTTPSocket.prototype.onOpen = function (options) { if (this.readyState === state_1["default"].CONNECTING) { if (options && options.hostname) { this.location.base = replaceHost(this.location.base, options.hostname); } this.readyState = state_1["default"].OPEN; if (this.onopen) { this.onopen(); } } else { this.onClose(1006, "Server lost session", true); } }; HTTPSocket.prototype.onEvent = function (event) { if (this.readyState === state_1["default"].OPEN && this.onmessage) { this.onmessage({ data: event }); } }; HTTPSocket.prototype.onActivity = function () { if (this.onactivity) { this.onactivity(); } }; HTTPSocket.prototype.onError = function (error) { if (this.onerror) { this.onerror(error); } }; HTTPSocket.prototype.openStream = function () { var _this = this; this.stream = runtime_1["default"].createSocketRequest("POST", getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))); this.stream.bind("chunk", function (chunk) { _this.onChunk(chunk); }); this.stream.bind("finished", function (status) { _this.hooks.onFinished(_this, status); }); this.stream.bind("buffer_too_long", function () { _this.reconnect(); }); try { this.stream.start(); } catch (error) { util_1["default"].defer(function () { _this.onError(error); _this.onClose(1006, "Could not start streaming", false); }); } }; HTTPSocket.prototype.closeStream = function () { if (this.stream) { this.stream.unbind_all(); this.stream.close(); this.stream = null; } }; return HTTPSocket; }()); function getLocation(url) { var parts = /([^\?]*)\/*(\??.*)/.exec(url); return { base: parts[1], queryString: parts[2] }; } function getSendURL(url, session) { return url.base + "/" + session + "/xhr_send"; } function getUniqueURL(url) { var separator = (url.indexOf('?') === -1) ? "?" : "&"; return url + separator + "t=" + (+new Date()) + "&n=" + autoIncrement++; } function replaceHost(url, hostname) { var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url); return urlParts[1] + hostname + urlParts[3]; } function randomNumber(max) { return Math.floor(Math.random() * max); } function randomString(length) { var result = []; for (var i = 0; i < length; i++) { result.push(randomNumber(32).toString(32)); } return result.join(''); } exports.__esModule = true; exports["default"] = HTTPSocket; /***/ }), /* 22 */ /***/ (function(module, exports) { "use strict"; var State; (function (State) { State[State["CONNECTING"] = 0] = "CONNECTING"; State[State["OPEN"] = 1] = "OPEN"; State[State["CLOSED"] = 3] = "CLOSED"; })(State || (State = {})); exports.__esModule = true; exports["default"] = State; /***/ }), /* 23 */ /***/ (function(module, exports) { "use strict"; var hooks = { getReceiveURL: function (url, session) { return url.base + "/" + session + "/xhr_streaming" + url.queryString; }, onHeartbeat: function (socket) { socket.sendRaw("[]"); }, sendHeartbeat: function (socket) { socket.sendRaw("[]"); }, onFinished: function (socket, status) { socket.onClose(1006, "Connection interrupted (" + status + ")", false); } }; exports.__esModule = true; exports["default"] = hooks; /***/ }), /* 24 */ /***/ (function(module, exports) { "use strict"; var hooks = { getReceiveURL: function (url, session) { return url.base + "/" + session + "/xhr" + url.queryString; }, onHeartbeat: function () { }, sendHeartbeat: function (socket) { socket.sendRaw("[]"); }, onFinished: function (socket, status) { if (status === 200) { socket.reconnect(); } else { socket.onClose(1006, "Connection interrupted (" + status + ")", false); } } }; exports.__esModule = true; exports["default"] = hooks; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(2); var hooks = { getRequest: function (socket) { var Constructor = runtime_1["default"].getXHRAPI(); var xhr = new Constructor(); xhr.onreadystatechange = xhr.onprogress = function () { switch (xhr.readyState) { case 3: if (xhr.responseText && xhr.responseText.length > 0) { socket.onChunk(xhr.status, xhr.responseText); } break; case 4: if (xhr.responseText && xhr.responseText.length > 0) { socket.onChunk(xhr.status, xhr.responseText); } socket.emit("finished", xhr.status); socket.close(); break; } }; return xhr; }, abortRequest: function (xhr) { xhr.onreadystatechange = null; xhr.abort(); } }; exports.__esModule = true; exports["default"] = hooks; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var react_native_1 = __webpack_require__(27); var dispatcher_1 = __webpack_require__(14); function hasOnlineConnectionState(connectionState) { return connectionState.toLowerCase() !== "none"; } var NetInfo = (function (_super) { __extends(NetInfo, _super); function NetInfo() { var _this = this; _super.call(this); this.online = true; react_native_1.NetInfo.fetch().then(function (connectionState) { _this.online = hasOnlineConnectionState(connectionState); }); react_native_1.NetInfo.addEventListener('change', function (connectionState) { var isNowOnline = hasOnlineConnectionState(connectionState); if (_this.online === isNowOnline) return; _this.online = isNowOnline; if (_this.online) { _this.emit("online"); } else { _this.emit("offline"); } }); } NetInfo.prototype.isOnline = function () { return this.online; }; return NetInfo; }(dispatcher_1["default"])); exports.NetInfo = NetInfo; exports.Network = new NetInfo(); /***/ }), /* 27 */ /***/ (function(module, exports) { module.exports = require("react-native"); /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var logger_1 = __webpack_require__(16); var runtime_1 = __webpack_require__(2); var url_store_1 = __webpack_require__(29); var ajax = function (context, socketId, callback) { var self = this, xhr; xhr = runtime_1["default"].createXHR(); xhr.open("POST", self.options.authEndpoint, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); for (var headerName in this.authOptions.headers) { xhr.setRequestHeader(headerName, this.authOptions.headers[headerName]); } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { var data, parsed = false; try { data = JSON.parse(xhr.responseText); parsed = true; } catch (e) { callback(true, 'JSON returned from webapp was invalid, yet status code was 200. Data was: ' + xhr.responseText); } if (parsed) { callback(false, data); } } else { var suffix = url_store_1["default"].buildLogSuffix("authenticationEndpoint"); logger_1["default"].warn(("Couldn't retrieve authentication info. " + xhr.status) + ("Clients must be authenticated to join private or presence channels. " + suffix)); callback(true, xhr.status); } } }; xhr.send(this.composeQuery(socketId)); return xhr; }; exports.__esModule = true; exports["default"] = ajax; /***/ }), /* 29 */ /***/ (function(module, exports) { "use strict"; var urlStore = { baseUrl: "https://pusher.com", urls: { authenticationEndpoint: { path: "/docs/authenticating_users" }, javascriptQuickStart: { path: "/docs/javascript_quick_start" } } }; var buildLogSuffix = function (key) { var urlPrefix = "See:"; var urlObj = urlStore.urls[key]; if (!urlObj) return ""; var url; if (urlObj.fullUrl) { url = urlObj.fullUrl; } else if (urlObj.path) { url = urlStore.baseUrl + urlObj.path; } if (!url) return ""; return urlPrefix + " " + url; }; exports.__esModule = true; exports["default"] = { buildLogSuffix: buildLogSuffix }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var logger_1 = __webpack_require__(16); var Collections = __webpack_require__(4); var runtime_1 = __webpack_require__(2); var getAgent = function (sender, encrypted) { return function (data, callback) { var scheme = "http" + (encrypted ? "s" : "") + "://"; var url = scheme + (sender.host || sender.options.host) + sender.options.path; var query = Collections.buildQueryString(data); url += ("/" + 2 + "?" + query); var xhr = runtime_1["default"].createXHR(); xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { var status_1 = xhr.status, responseText = xhr.responseText; if (status_1 !== 200) { logger_1["default"].debug("TimelineSender Error: received " + status_1 + " from stats.pusher.com"); return; } try { var host = JSON.parse(responseText).host; } catch (e) { logger_1["default"].debug("TimelineSenderError: invalid response " + responseText); } if (host) { sender.host = host; } } }; xhr.send(); }; }; var xhr = { name: 'xhr', getAgent: getAgent }; exports.__esModule = true; exports["default"] = xhr; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var util_1 = __webpack_require__(6); var level_1 = __webpack_require__(32); var Timeline = (function () { function Timeline(key, session, options) { this.key = key; this.session = session; this.events = []; this.options = options || {}; this.sent = 0; this.uniqueID = 0; } Timeline.prototype.log = function (level, event) { if (level <= this.options.level) { this.events.push(Collections.extend({}, event, { timestamp: util_1["default"].now() })); if (this.options.limit && this.events.length > this.options.limit) { this.events.shift(); } } }; Timeline.prototype.error = function (event) { this.log(level_1["default"].ERROR, event); }; Timeline.prototype.info = function (event) { this.log(level_1["default"].INFO, event); }; Timeline.prototype.debug = function (event) { this.log(level_1["default"].DEBUG, event); }; Timeline.prototype.isEmpty = function () { return this.events.length === 0; }; Timeline.prototype.send = function (sendfn, callback) { var _this = this; var data = Collections.extend({ session: this.session, bundle: this.sent + 1, key: this.key, lib: "js", version: this.options.version, cluster: this.options.cluster, features: this.options.features, timeline: this.events }, this.options.params); this.events = []; sendfn(data, function (error, result) { if (!error) { _this.sent++; } if (callback) { callback(error, result); } }); return true; }; Timeline.prototype.generateUniqueID = function () { this.uniqueID++; return this.uniqueID; }; return Timeline; }()); exports.__esModule = true; exports["default"] = Timeline; /***/ }), /* 32 */ /***/ (function(module, exports) { "use strict"; var TimelineLevel; (function (TimelineLevel) { TimelineLevel[TimelineLevel["ERROR"] = 3] = "ERROR"; TimelineLevel[TimelineLevel["INFO"] = 6] = "INFO"; TimelineLevel[TimelineLevel["DEBUG"] = 7] = "DEBUG"; })(TimelineLevel || (TimelineLevel = {})); exports.__esModule = true; exports["default"] = TimelineLevel; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var util_1 = __webpack_require__(6); var transport_manager_1 = __webpack_require__(34); var Errors = __webpack_require__(45); var transport_strategy_1 = __webpack_require__(49); var sequential_strategy_1 = __webpack_require__(50); var best_connected_ever_strategy_1 = __webpack_require__(51); var cached_strategy_1 = __webpack_require__(52); var delayed_strategy_1 = __webpack_require__(53); var if_strategy_1 = __webpack_require__(54); var first_connected_strategy_1 = __webpack_require__(55); var runtime_1 = __webpack_require__(2); var Transports = runtime_1["default"].Transports; exports.build = function (scheme, options) { var context = Collections.extend({}, globalContext, options); return evaluate(scheme, context)[1].strategy; }; var UnsupportedStrategy = { isSupported: function () { return false; }, connect: function (_, callback) { var deferred = util_1["default"].defer(function () { callback(new Errors.UnsupportedStrategy()); }); return { abort: function () { deferred.ensureAborted(); }, forceMinPriority: function () { } }; } }; function returnWithOriginalContext(f) { return function (context) { return [f.apply(this, arguments), context]; }; } var globalContext = { extend: function (context, first, second) { return [Collections.extend({}, first, second), context]; }, def: function (context, name, value) { if (context[name] !== undefined) { throw "Redefining symbol " + name; } context[name] = value; return [undefined, context]; }, def_transport: function (context, name, type, priority, options, manager) { var transportClass = Transports[type]; if (!transportClass) { throw new Errors.UnsupportedTransport(type); } var enabled = (!context.enabledTransports || Collections.arrayIndexOf(context.enabledTransports, name) !== -1) && (!context.disabledTransports || Collections.arrayIndexOf(context.disabledTransports, name) === -1); var transport; if (enabled) { transport = new transport_strategy_1["default"](name, priority, manager ? manager.getAssistant(transportClass) : transportClass, Collections.extend({ key: context.key, encrypted: context.encrypted, timeline: context.timeline, ignoreNullOrigin: context.ignoreNullOrigin }, options)); } else { transport = UnsupportedStrategy; } var newContext = context.def(context, name, transport)[1]; newContext.Transports = context.Transports || {}; newContext.Transports[name] = transport; return [undefined, newContext]; }, transport_manager: returnWithOriginalContext(function (_, options) { return new transport_manager_1["default"](options); }), sequential: returnWithOriginalContext(function (_, options) { var strategies = Array.prototype.slice.call(arguments, 2); return new sequential_strategy_1["default"](strategies, options); }), cached: returnWithOriginalContext(function (context, ttl, strategy) { return new cached_strategy_1["default"](strategy, context.Transports, { ttl: ttl, timeline: context.timeline, encrypted: context.encrypted }); }), first_connected: returnWithOriginalContext(function (_, strategy) { return new first_connected_strategy_1["default"](strategy); }), best_connected_ever: returnWithOriginalContext(function () { var strategies = Array.prototype.slice.call(arguments, 1); return new best_connected_ever_strategy_1["default"](strategies); }), delayed: returnWithOriginalContext(function (_, delay, strategy) { return new delayed_strategy_1["default"](strategy, { delay: delay }); }), "if": returnWithOriginalContext(function (_, test, trueBranch, falseBranch) { return new if_strategy_1["default"](test, trueBranch, falseBranch); }), is_supported: returnWithOriginalContext(function (_, strategy) { return function () { return strategy.isSupported(); }; }) }; function isSymbol(expression) { return (typeof expression === "string") && expression.charAt(0) === ":"; } function getSymbolValue(expression, context) { return context[expression.slice(1)]; } function evaluateListOfExpressions(expressions, context) { if (expressions.length === 0) { return [[], context]; } var head = evaluate(expressions[0], context); var tail = evaluateListOfExpressions(expressions.slice(1), head[1]); return [[head[0]].concat(tail[0]), tail[1]]; } function evaluateString(expression, context) { if (!isSymbol(expression)) { return [expression, context]; } var value = getSymbolValue(expression, context); if (value === undefined) { throw "Undefined symbol " + expression; } return [value, context]; } function evaluateArray(expression, context) { if (isSymbol(expression[0])) { var f = getSymbolValue(expression[0], context); if (expression.length > 1) { if (typeof f !== "function") { throw "Calling non-function " + expression[0]; } var args = [Collections.extend({}, context)].concat(Collections.map(expression.slice(1), function (arg) { return evaluate(arg, Collections.extend({}, context))[0]; })); return f.apply(this, args); } else { return [f, context]; } } else { return evaluateListOfExpressions(expression, context); } } function evaluate(expression, context) { if (typeof expression === "string") { return evaluateString(expression, context); } else if (typeof expression === "object") { if (expression instanceof Array && expression.length > 0) { return evaluateArray(expression, context); } } return [expression, context]; } /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var factory_1 = __webpack_require__(35); var TransportManager = (function () { function TransportManager(options) { this.options = options || {}; this.livesLeft = this.options.lives || Infinity; } TransportManager.prototype.getAssistant = function (transport) { return factory_1["default"].createAssistantToTheTransportManager(this, transport, { minPingDelay: this.options.minPingDelay, maxPingDelay: this.options.maxPingDelay }); }; TransportManager.prototype.isAlive = function () { return this.livesLeft > 0; }; TransportManager.prototype.reportDeath = function () { this.livesLeft -= 1; }; return TransportManager; }()); exports.__esModule = true; exports["default"] = TransportManager; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assistant_to_the_transport_manager_1 = __webpack_require__(36); var handshake_1 = __webpack_require__(37); var pusher_authorizer_1 = __webpack_require__(40); var timeline_sender_1 = __webpack_require__(41); var presence_channel_1 = __webpack_require__(42); var private_channel_1 = __webpack_require__(43); var channel_1 = __webpack_require__(44); var connection_manager_1 = __webpack_require__(47); var channels_1 = __webpack_require__(48); var Factory = { createChannels: function () { return new channels_1["default"](); }, createConnectionManager: function (key, options) { return new connection_manager_1["default"](key, options); }, createChannel: function (name, pusher) { return new channel_1["default"](name, pusher); }, createPrivateChannel: function (name, pusher) { return new private_channel_1["default"](name, pusher); }, createPresenceChannel: function (name, pusher) { return new presence_channel_1["default"](name, pusher); }, createTimelineSender: function (timeline, options) { return new timeline_sender_1["default"](timeline, options); }, createAuthorizer: function (channel, options) { if (options.authorizer) { return options.authorizer(channel, options); } return new pusher_authorizer_1["default"](channel, options); }, createHandshake: function (transport, callback) { return new handshake_1["default"](transport, callback); }, createAssistantToTheTransportManager: function (manager, transport, options) { return new assistant_to_the_transport_manager_1["default"](manager, transport, options); } }; exports.__esModule = true; exports["default"] = Factory; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util_1 = __webpack_require__(6); var Collections = __webpack_require__(4); var AssistantToTheTransportManager = (function () { function AssistantToTheTransportManager(manager, transport, options) { this.manager = manager; this.transport = transport; this.minPingDelay = options.minPingDelay; this.maxPingDelay = options.maxPingDelay; this.pingDelay = undefined; } AssistantToTheTransportManager.prototype.createConnection = function (name, priority, key, options) { var _this = this; options = Collections.extend({}, options, { activityTimeout: this.pingDelay }); var connection = this.transport.createConnection(name, priority, key, options); var openTimestamp = null; var onOpen = function () { connection.unbind("open", onOpen); connection.bind("closed", onClosed); openTimestamp = util_1["default"].now(); }; var onClosed = function (closeEvent) { connection.unbind("closed", onClosed); if (closeEvent.code === 1002 || closeEvent.code === 1003) { _this.manager.reportDeath(); } else if (!closeEvent.wasClean && openTimestamp) { var lifespan = util_1["default"].now() - openTimestamp; if (lifespan < 2 * _this.maxPingDelay) { _this.manager.reportDeath(); _this.pingDelay = Math.max(lifespan / 2, _this.minPingDelay); } } }; connection.bind("open", onOpen); return connection; }; AssistantToTheTransportManager.prototype.isSupported = function (environment) { return this.manager.isAlive() && this.transport.isSupported(environment); }; return AssistantToTheTransportManager; }()); exports.__esModule = true; exports["default"] = AssistantToTheTransportManager; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var Protocol = __webpack_require__(38); var connection_1 = __webpack_require__(39); var Handshake = (function () { function Handshake(transport, callback) { this.transport = transport; this.callback = callback; this.bindListeners(); } Handshake.prototype.close = function () { this.unbindListeners(); this.transport.close(); }; Handshake.prototype.bindListeners = function () { var _this = this; this.onMessage = function (m) { _this.unbindListeners(); var result; try { result = Protocol.processHandshake(m); } catch (e) { _this.finish("error", { error: e }); _this.transport.close(); return; } if (result.action === "connected") { _this.finish("connected", { connection: new connection_1["default"](result.id, _this.transport), activityTimeout: result.activityTimeout }); } else { _this.finish(result.action, { error: result.error }); _this.transport.close(); } }; this.onClosed = function (closeEvent) { _this.unbindListeners(); var action = Protocol.getCloseAction(closeEvent) || "backoff"; var error = Protocol.getCloseError(closeEvent); _this.finish(action, { error: error }); }; this.transport.bind("message", this.onMessage); this.transport.bind("closed", this.onClosed); }; Handshake.prototype.unbindListeners = function () { this.transport.unbind("message", this.onMessage); this.transport.unbind("closed", this.onClosed); }; Handshake.prototype.finish = function (action, params) { this.callback(Collections.extend({ transport: this.transport, action: action }, params)); }; return Handshake; }()); exports.__esModule = true; exports["default"] = Handshake; /***/ }), /* 38 */ /***/ (function(module, exports) { "use strict"; exports.decodeMessage = function (message) { try { var params = JSON.parse(message.data); if (typeof params.data === 'string') { try { params.data = JSON.parse(params.data); } catch (e) { if (!(e instanceof SyntaxError)) { throw e; } } } return params; } catch (e) { throw { type: 'MessageParseError', error: e, data: message.data }; } }; exports.encodeMessage = function (message) { return JSON.stringify(message); }; exports.processHandshake = function (message) { message = exports.decodeMessage(message); if (message.event === "pusher:connection_established") { if (!message.data.activity_timeout) { throw "No activity timeout specified in handshake"; } return { action: "connected", id: message.data.socket_id, activityTimeout: message.data.activity_timeout * 1000 }; } else if (message.event === "pusher:error") { return { action: this.getCloseAction(message.data), error: this.getCloseError(message.data) }; } else { throw "Invalid handshake"; } }; exports.getCloseAction = function (closeEvent) { if (closeEvent.code < 4000) { if (closeEvent.code >= 1002 && closeEvent.code <= 1004) { return "backoff"; } else { return null; } } else if (closeEvent.code === 4000) { return "ssl_only"; } else if (closeEvent.code < 4100) { return "refused"; } else if (closeEvent.code < 4200) { return "backoff"; } else if (closeEvent.code < 4300) { return "retry"; } else { return "refused"; } }; exports.getCloseError = function (closeEvent) { if (closeEvent.code !== 1000 && closeEvent.code !== 1001) { return { type: 'PusherError', data: { code: closeEvent.code, message: closeEvent.reason || closeEvent.message } }; } else { return null; } }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Collections = __webpack_require__(4); var dispatcher_1 = __webpack_require__(14); var Protocol = __webpack_require__(38); var logger_1 = __webpack_require__(16); var Connection = (function (_super) { __extends(Connection, _super); function Connection(id, transport) { _super.call(this); this.id = id; this.transport = transport; this.activityTimeout = transport.activityTimeout; this.bindListeners(); } Connection.prototype.handlesActivityChecks = function () { return this.transport.handlesActivityChecks(); }; Connection.prototype.send = function (data) { return this.transport.send(data); }; Connection.prototype.send_event = function (name, data, channel) { var message = { event: name, data: data }; if (channel) { message.channel = channel; } logger_1["default"].debug('Event sent', message); return this.send(Protocol.encodeMessage(message)); }; Connection.prototype.ping = function () { if (this.transport.supportsPing()) { this.transport.ping(); } else { this.send_event('pusher:ping', {}); } }; Connection.prototype.close = function () { this.transport.close(); }; Connection.prototype.bindListeners = function () { var _this = this; var listeners = { message: function (m) { var message; try { message = Protocol.decodeMessage(m); } catch (e) { _this.emit('error', { type: 'MessageParseError', error: e, data: m.data }); } if (message !== undefined) { logger_1["default"].debug('Event recd', message); switch (message.event) { case 'pusher:error': _this.emit('error', { type: 'PusherError', data: message.data }); break; case 'pusher:ping': _this.emit("ping"); break; case 'pusher:pong': _this.emit("pong"); break; } _this.emit('message', message); } }, activity: function () { _this.emit("activity"); }, error: function (error) { _this.emit("error", { type: "WebSocketError", error: error }); }, closed: function (closeEvent) { unbindListeners(); if (closeEvent && closeEvent.code) { _this.handleCloseEvent(closeEvent); } _this.transport = null; _this.emit("closed"); } }; var unbindListeners = function () { Collections.objectApply(listeners, function (listener, event) { _this.transport.unbind(event, listener); }); }; Collections.objectApply(listeners, function (listener, event) { _this.transport.bind(event, listener); }); }; Connection.prototype.handleCloseEvent = function (closeEvent) { var action = Protocol.getCloseAction(closeEvent); var error = Protocol.getCloseError(closeEvent); if (error) { this.emit('error', error); } if (action) { this.emit(action); } }; return Connection; }(dispatcher_1["default"])); exports.__esModule = true; exports["default"] = Connection; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(2); var PusherAuthorizer = (function () { function PusherAuthorizer(channel, options) { this.channel = channel; var authTransport = options.authTransport; if (typeof runtime_1["default"].getAuthorizers()[authTransport] === "undefined") { throw "'" + authTransport + "' is not a recognized auth transport"; } this.type = authTransport; this.options = options; this.authOptions = (options || {}).auth || {}; } PusherAuthorizer.prototype.composeQuery = function (socketId) { var query = 'socket_id=' + encodeURIComponent(socketId) + '&channel_name=' + encodeURIComponent(this.channel.name); for (var i in this.authOptions.params) { query += "&" + encodeURIComponent(i) + "=" + encodeURIComponent(this.authOptions.params[i]); } return query; }; PusherAuthorizer.prototype.authorize = function (socketId, callback) { PusherAuthorizer.authorizers = PusherAuthorizer.authorizers || runtime_1["default"].getAuthorizers(); return PusherAuthorizer.authorizers[this.type].call(this, runtime_1["default"], socketId, callback); }; return PusherAuthorizer; }()); exports.__esModule = true; exports["default"] = PusherAuthorizer; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(2); var TimelineSender = (function () { function TimelineSender(timeline, options) { this.timeline = timeline; this.options = options || {}; } TimelineSender.prototype.send = function (encrypted, callback) { if (this.timeline.isEmpty()) { return; } this.timeline.send(runtime_1["default"].TimelineTransport.getAgent(this, encrypted), callback); }; return TimelineSender; }()); exports.__esModule = true; exports["default"] = TimelineSender; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var private_channel_1 = __webpack_require__(43); var logger_1 = __webpack_require__(16); var members_1 = __webpack_require__(46); var url_store_1 = __webpack_require__(29); var PresenceChannel = (function (_super) { __extends(PresenceChannel, _super); function PresenceChannel(name, pusher) { _super.call(this, name, pusher); this.members = new members_1["default"](); } PresenceChannel.prototype.authorize = function (socketId, callback) { var _this = this; _super.prototype.authorize.call(this, socketId, function (error, authData) { if (!error) { if (authData.channel_data === undefined) { var suffix = url_store_1["default"].buildLogSuffix("authenticationEndpoint"); logger_1["default"].warn(("Invalid auth response for channel '" + _this.name + "',") + ("expected 'channel_data' field. " + suffix)); callback("Invalid auth response"); return; } var channelData = JSON.parse(authData.channel_data); _this.members.setMyID(channelData.user_id); } callback(error, authData); }); }; PresenceChannel.prototype.handleEvent = function (event, data) { switch (event) { case "pusher_internal:subscription_succeeded": this.subscriptionPending = false; this.subscribed = true; if (this.subscriptionCancelled) { this.pusher.unsubscribe(this.name); } else { this.members.onSubscription(data); this.emit("pusher:subscription_succeeded", this.members); } break; case "pusher_internal:member_added": var addedMember = this.members.addMember(data); this.emit('pusher:member_added', addedMember); break; case "pusher_internal:member_removed": var removedMember = this.members.removeMember(data); if (removedMember) { this.emit('pusher:member_removed', removedMember); } break; default: private_channel_1["default"].prototype.handleEvent.call(this, event, data); } }; PresenceChannel.prototype.disconnect = function () { this.members.reset(); _super.prototype.disconnect.call(this); }; return PresenceChannel; }(private_channel_1["default"])); exports.__esModule = true; exports["default"] = PresenceChannel; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var factory_1 = __webpack_require__(35); var channel_1 = __webpack_require__(44); var PrivateChannel = (function (_super) { __extends(PrivateChannel, _super); function PrivateChannel() { _super.apply(this, arguments); } PrivateChannel.prototype.authorize = function (socketId, callback) { var authorizer = factory_1["default"].createAuthorizer(this, this.pusher.config); return authorizer.authorize(socketId, callback); }; return PrivateChannel; }(channel_1["default"])); exports.__esModule = true; exports["default"] = PrivateChannel; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var dispatcher_1 = __webpack_require__(14); var Errors = __webpack_require__(45); var logger_1 = __webpack_require__(16); var Channel = (function (_super) { __extends(Channel, _super); function Channel(name, pusher) { _super.call(this, function (event, data) { logger_1["default"].debug('No callbacks on ' + name + ' for ' + event); }); this.name = name; this.pusher = pusher; this.subscribed = false; this.subscriptionPending = false; this.subscriptionCancelled = false; } Channel.prototype.authorize = function (socketId, callback) { return callback(false, {}); }; Channel.prototype.trigger = function (event, data) { if (event.indexOf("client-") !== 0) { throw new Errors.BadEventName("Event '" + event + "' does not start with 'client-'"); } return this.pusher.send_event(event, data, this.name); }; Channel.prototype.disconnect = function () { this.subscribed = false; this.subscriptionPending = false; }; Channel.prototype.handleEvent = function (event, data) { if (event.indexOf("pusher_internal:") === 0) { if (event === "pusher_internal:subscription_succeeded") { this.subscriptionPending = false; this.subscribed = true; if (this.subscriptionCancelled) { this.pusher.unsubscribe(this.name); } else { this.emit("pusher:subscription_succeeded", data); } } } else { this.emit(event, data); } }; Channel.prototype.subscribe = function () { var _this = this; if (this.subscribed) { return; } this.subscriptionPending = true; this.subscriptionCancelled = false; this.authorize(this.pusher.connection.socket_id, function (error, data) { if (error) { _this.handleEvent('pusher:subscription_error', data); } else { _this.pusher.send_event('pusher:subscribe', { auth: data.auth, channel_data: data.channel_data, channel: _this.name }); } }); }; Channel.prototype.unsubscribe = function () { this.subscribed = false; this.pusher.send_event('pusher:unsubscribe', { channel: this.name }); }; Channel.prototype.cancelSubscription = function () { this.subscriptionCancelled = true; }; Channel.prototype.reinstateSubscription = function () { this.subscriptionCancelled = false; }; return Channel; }(dispatcher_1["default"])); exports.__esModule = true; exports["default"] = Channel; /***/ }), /* 45 */ /***/ (function(module, exports) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var BadEventName = (function (_super) { __extends(BadEventName, _super); function BadEventName() { _super.apply(this, arguments); } return BadEventName; }(Error)); exports.BadEventName = BadEventName; var RequestTimedOut = (function (_super) { __extends(RequestTimedOut, _super); function RequestTimedOut() { _super.apply(this, arguments); } return RequestTimedOut; }(Error)); exports.RequestTimedOut = RequestTimedOut; var TransportPriorityTooLow = (function (_super) { __extends(TransportPriorityTooLow, _super); function TransportPriorityTooLow() { _super.apply(this, arguments); } return TransportPriorityTooLow; }(Error)); exports.TransportPriorityTooLow = TransportPriorityTooLow; var TransportClosed = (function (_super) { __extends(TransportClosed, _super); function TransportClosed() { _super.apply(this, arguments); } return TransportClosed; }(Error)); exports.TransportClosed = TransportClosed; var UnsupportedTransport = (function (_super) { __extends(UnsupportedTransport, _super); function UnsupportedTransport() { _super.apply(this, arguments); } return UnsupportedTransport; }(Error)); exports.UnsupportedTransport = UnsupportedTransport; var UnsupportedStrategy = (function (_super) { __extends(UnsupportedStrategy, _super); function UnsupportedStrategy() { _super.apply(this, arguments); } return UnsupportedStrategy; }(Error)); exports.UnsupportedStrategy = UnsupportedStrategy; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var Members = (function () { function Members() { this.reset(); } Members.prototype.get = function (id) { if (Object.prototype.hasOwnProperty.call(this.members, id)) { return { id: id, info: this.members[id] }; } else { return null; } }; Members.prototype.each = function (callback) { var _this = this; Collections.objectApply(this.members, function (member, id) { callback(_this.get(id)); }); }; Members.prototype.setMyID = function (id) { this.myID = id; }; Members.prototype.onSubscription = function (subscriptionData) { this.members = subscriptionData.presence.hash; this.count = subscriptionData.presence.count; this.me = this.get(this.myID); }; Members.prototype.addMember = function (memberData) { if (this.get(memberData.user_id) === null) { this.count++; } this.members[memberData.user_id] = memberData.user_info; return this.get(memberData.user_id); }; Members.prototype.removeMember = function (memberData) { var member = this.get(memberData.user_id); if (member) { delete this.members[memberData.user_id]; this.count--; } return member; }; Members.prototype.reset = function () { this.members = {}; this.count = 0; this.myID = null; this.me = null; }; return Members; }()); exports.__esModule = true; exports["default"] = Members; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var dispatcher_1 = __webpack_require__(14); var timers_1 = __webpack_require__(7); var logger_1 = __webpack_require__(16); var Collections = __webpack_require__(4); var runtime_1 = __webpack_require__(2); var ConnectionManager = (function (_super) { __extends(ConnectionManager, _super); function ConnectionManager(key, options) { var _this = this; _super.call(this); this.key = key; this.options = options || {}; this.state = "initialized"; this.connection = null; this.encrypted = !!options.encrypted; this.timeline = this.options.timeline; this.connectionCallbacks = this.buildConnectionCallbacks(); this.errorCallbacks = this.buildErrorCallbacks(); this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks); var Network = runtime_1["default"].getNetwork(); Network.bind("online", function () { _this.timeline.info({ netinfo: "online" }); if (_this.state === "connecting" || _this.state === "unavailable") { _this.retryIn(0); } }); Network.bind("offline", function () { _this.timeline.info({ netinfo: "offline" }); if (_this.connection) { _this.sendActivityCheck(); } }); this.updateStrategy(); } ConnectionManager.prototype.connect = function () { if (this.connection || this.runner) { return; } if (!this.strategy.isSupported()) { this.updateState("failed"); return; } this.updateState("connecting"); this.startConnecting(); this.setUnavailableTimer(); }; ; ConnectionManager.prototype.send = function (data) { if (this.connection) { return this.connection.send(data); } else { return false; } }; ; ConnectionManager.prototype.send_event = function (name, data, channel) { if (this.connection) { return this.connection.send_event(name, data, channel); } else { return false; } }; ; ConnectionManager.prototype.disconnect = function () { this.disconnectInternally(); this.updateState("disconnected"); }; ; ConnectionManager.prototype.isEncrypted = function () { return this.encrypted; }; ; ConnectionManager.prototype.startConnecting = function () { var _this = this; var callback = function (error, handshake) { if (error) { _this.runner = _this.strategy.connect(0, callback); } else { if (handshake.action === "error") { _this.emit("error", { type: "HandshakeError", error: handshake.error }); _this.timeline.error({ handshakeError: handshake.error }); } else { _this.abortConnecting(); _this.handshakeCallbacks[handshake.action](handshake); } } }; this.runner = this.strategy.connect(0, callback); }; ; ConnectionManager.prototype.abortConnecting = function () { if (this.runner) { this.runner.abort(); this.runner = null; } }; ; ConnectionManager.prototype.disconnectInternally = function () { this.abortConnecting(); this.clearRetryTimer(); this.clearUnavailableTimer(); if (this.connection) { var connection = this.abandonConnection(); connection.close(); } }; ; ConnectionManager.prototype.updateStrategy = function () { this.strategy = this.options.getStrategy({ key: this.key, timeline: this.timeline, encrypted: this.encrypted }); }; ; ConnectionManager.prototype.retryIn = function (delay) { var _this = this; this.timeline.info({ action: "retry", delay: delay }); if (delay > 0) { this.emit("connecting_in", Math.round(delay / 1000)); } this.retryTimer = new timers_1.OneOffTimer(delay || 0, function () { _this.disconnectInternally(); _this.connect(); }); }; ; ConnectionManager.prototype.clearRetryTimer = function () { if (this.retryTimer) { this.retryTimer.ensureAborted(); this.retryTimer = null; } }; ; ConnectionManager.prototype.setUnavailableTimer = function () { var _this = this; this.unavailableTimer = new timers_1.OneOffTimer(this.options.unavailableTimeout, function () { _this.updateState("unavailable"); }); }; ; ConnectionManager.prototype.clearUnavailableTimer = function () { if (this.unavailableTimer) { this.unavailableTimer.ensureAborted(); } }; ; ConnectionManager.prototype.sendActivityCheck = function () { var _this = this; this.stopActivityCheck(); this.connection.ping(); this.activityTimer = new timers_1.OneOffTimer(this.options.pongTimeout, function () { _this.timeline.error({ pong_timed_out: _this.options.pongTimeout }); _this.retryIn(0); }); }; ; ConnectionManager.prototype.resetActivityCheck = function () { var _this = this; this.stopActivityCheck(); if (this.connection && !this.connection.handlesActivityChecks()) { this.activityTimer = new timers_1.OneOffTimer(this.activityTimeout, function () { _this.sendActivityCheck(); }); } }; ; ConnectionManager.prototype.stopActivityCheck = function () { if (this.activityTimer) { this.activityTimer.ensureAborted(); } }; ; ConnectionManager.prototype.buildConnectionCallbacks = function () { var _this = this; return { message: function (message) { _this.resetActivityCheck(); _this.emit('message', message); }, ping: function () { _this.send_event('pusher:pong', {}); }, activity: function () { _this.resetActivityCheck(); }, error: function (error) { _this.emit("error", { type: "WebSocketError", error: error }); }, closed: function () { _this.abandonConnection(); if (_this.shouldRetry()) { _this.retryIn(1000); } } }; }; ; ConnectionManager.prototype.buildHandshakeCallbacks = function (errorCallbacks) { var _this = this; return Collections.extend({}, errorCallbacks, { connected: function (handshake) { _this.activityTimeout = Math.min(_this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity); _this.clearUnavailableTimer(); _this.setConnection(handshake.connection); _this.socket_id = _this.connection.id; _this.updateState("connected", { socket_id: _this.socket_id }); } }); }; ; ConnectionManager.prototype.buildErrorCallbacks = function () { var _this = this; var withErrorEmitted = function (callback) { return function (result) { if (result.error) { _this.emit("error", { type: "WebSocketError", error: result.error }); } callback(result); }; }; return { ssl_only: withErrorEmitted(function () { _this.encrypted = true; _this.updateStrategy(); _this.retryIn(0); }), refused: withErrorEmitted(function () { _this.disconnect(); }), backoff: withErrorEmitted(function () { _this.retryIn(1000); }), retry: withErrorEmitted(function () { _this.retryIn(0); }) }; }; ; ConnectionManager.prototype.setConnection = function (connection) { this.connection = connection; for (var event in this.connectionCallbacks) { this.connection.bind(event, this.connectionCallbacks[event]); } this.resetActivityCheck(); }; ; ConnectionManager.prototype.abandonConnection = function () { if (!this.connection) { return; } this.stopActivityCheck(); for (var event in this.connectionCallbacks) { this.connection.unbind(event, this.connectionCallbacks[event]); } var connection = this.connection; this.connection = null; return connection; }; ConnectionManager.prototype.updateState = function (newState, data) { var previousState = this.state; this.state = newState; if (previousState !== newState) { var newStateDescription = newState; if (newStateDescription === "connected") { newStateDescription += " with new socket ID " + data.socket_id; } logger_1["default"].debug('State changed', previousState + ' -> ' + newStateDescription); this.timeline.info({ state: newState, params: data }); this.emit('state_change', { previous: previousState, current: newState }); this.emit(newState, data); } }; ConnectionManager.prototype.shouldRetry = function () { return this.state === "connecting" || this.state === "connected"; }; return ConnectionManager; }(dispatcher_1["default"])); exports.__esModule = true; exports["default"] = ConnectionManager; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var factory_1 = __webpack_require__(35); var Channels = (function () { function Channels() { this.channels = {}; } Channels.prototype.add = function (name, pusher) { if (!this.channels[name]) { this.channels[name] = createChannel(name, pusher); } return this.channels[name]; }; Channels.prototype.all = function () { return Collections.values(this.channels); }; Channels.prototype.find = function (name) { return this.channels[name]; }; Channels.prototype.remove = function (name) { var channel = this.channels[name]; delete this.channels[name]; return channel; }; Channels.prototype.disconnect = function () { Collections.objectApply(this.channels, function (channel) { channel.disconnect(); }); }; return Channels; }()); exports.__esModule = true; exports["default"] = Channels; function createChannel(name, pusher) { if (name.indexOf('private-') === 0) { return factory_1["default"].createPrivateChannel(name, pusher); } else if (name.indexOf('presence-') === 0) { return factory_1["default"].createPresenceChannel(name, pusher); } else { return factory_1["default"].createChannel(name, pusher); } } /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var factory_1 = __webpack_require__(35); var util_1 = __webpack_require__(6); var Errors = __webpack_require__(45); var Collections = __webpack_require__(4); var TransportStrategy = (function () { function TransportStrategy(name, priority, transport, options) { this.name = name; this.priority = priority; this.transport = transport; this.options = options || {}; } TransportStrategy.prototype.isSupported = function () { return this.transport.isSupported({ encrypted: this.options.encrypted }); }; TransportStrategy.prototype.connect = function (minPriority, callback) { var _this = this; if (!this.isSupported()) { return failAttempt(new Errors.UnsupportedStrategy(), callback); } else if (this.priority < minPriority) { return failAttempt(new Errors.TransportPriorityTooLow(), callback); } var connected = false; var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options); var handshake = null; var onInitialized = function () { transport.unbind("initialized", onInitialized); transport.connect(); }; var onOpen = function () { handshake = factory_1["default"].createHandshake(transport, function (result) { connected = true; unbindListeners(); callback(null, result); }); }; var onError = function (error) { unbindListeners(); callback(error); }; var onClosed = function () { unbindListeners(); var serializedTransport; serializedTransport = Collections.safeJSONStringify(transport); callback(new Errors.TransportClosed(serializedTransport)); }; var unbindListeners = function () { transport.unbind("initialized", onInitialized); transport.unbind("open", onOpen); transport.unbind("error", onError); transport.unbind("closed", onClosed); }; transport.bind("initialized", onInitialized); transport.bind("open", onOpen); transport.bind("error", onError); transport.bind("closed", onClosed); transport.initialize(); return { abort: function () { if (connected) { return; } unbindListeners(); if (handshake) { handshake.close(); } else { transport.close(); } }, forceMinPriority: function (p) { if (connected) { return; } if (_this.priority < p) { if (handshake) { handshake.close(); } else { transport.close(); } } } }; }; return TransportStrategy; }()); exports.__esModule = true; exports["default"] = TransportStrategy; function failAttempt(error, callback) { util_1["default"].defer(function () { callback(error); }); return { abort: function () { }, forceMinPriority: function () { } }; } /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var util_1 = __webpack_require__(6); var timers_1 = __webpack_require__(7); var SequentialStrategy = (function () { function SequentialStrategy(strategies, options) { this.strategies = strategies; this.loop = Boolean(options.loop); this.failFast = Boolean(options.failFast); this.timeout = options.timeout; this.timeoutLimit = options.timeoutLimit; } SequentialStrategy.prototype.isSupported = function () { return Collections.any(this.strategies, util_1["default"].method("isSupported")); }; SequentialStrategy.prototype.connect = function (minPriority, callback) { var _this = this; var strategies = this.strategies; var current = 0; var timeout = this.timeout; var runner = null; var tryNextStrategy = function (error, handshake) { if (handshake) { callback(null, handshake); } else { current = current + 1; if (_this.loop) { current = current % strategies.length; } if (current < strategies.length) { if (timeout) { timeout = timeout * 2; if (_this.timeoutLimit) { timeout = Math.min(timeout, _this.timeoutLimit); } } runner = _this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: _this.failFast }, tryNextStrategy); } else { callback(true); } } }; runner = this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: this.failFast }, tryNextStrategy); return { abort: function () { runner.abort(); }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; SequentialStrategy.prototype.tryStrategy = function (strategy, minPriority, options, callback) { var timer = null; var runner = null; if (options.timeout > 0) { timer = new timers_1.OneOffTimer(options.timeout, function () { runner.abort(); callback(true); }); } runner = strategy.connect(minPriority, function (error, handshake) { if (error && timer && timer.isRunning() && !options.failFast) { return; } if (timer) { timer.ensureAborted(); } callback(error, handshake); }); return { abort: function () { if (timer) { timer.ensureAborted(); } runner.abort(); }, forceMinPriority: function (p) { runner.forceMinPriority(p); } }; }; return SequentialStrategy; }()); exports.__esModule = true; exports["default"] = SequentialStrategy; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(4); var util_1 = __webpack_require__(6); var BestConnectedEverStrategy = (function () { function BestConnectedEverStrategy(strategies) { this.strategies = strategies; } BestConnectedEverStrategy.prototype.isSupported = function () { return Collections.any(this.strategies, util_1["default"].method("isSupported")); }; BestConnectedEverStrategy.prototype.connect = function (minPriority, callback) { return connect(this.strategies, minPriority, function (i, runners) { return function (error, handshake) { runners[i].error = error; if (error) { if (allRunnersFailed(runners)) { callback(true); } return; } Collections.apply(runners, function (runner) { runner.forceMinPriority(handshake.transport.priority); }); callback(null, handshake); }; }); }; return BestConnectedEverStrategy; }()); exports.__esModule = true; exports["default"] = BestConnectedEverStrategy; function connect(strategies, minPriority, callbackBuilder) { var runners = Collections.map(strategies, function (strategy, i, _, rs) { return strategy.connect(minPriority, callbackBuilder(i, rs)); }); return { abort: function () { Collections.apply(runners, abortRunner); }, forceMinPriority: function (p) { Collections.apply(runners, function (runner) { runner.forceMinPriority(p); }); } }; } function allRunnersFailed(runners) { return Collections.all(runners, function (runner) { return Boolean(runner.error); }); } function abortRunner(runner) { if (!runner.error && !runner.aborted) { runner.abort(); runner.aborted = true; } } /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util_1 = __webpack_require__(6); var runtime_1 = __webpack_require__(2); var sequential_strategy_1 = __webpack_require__(50); var Collections = __webpack_require__(4); var CachedStrategy = (function () { function CachedStrategy(strategy, transports, options) { this.strategy = strategy; this.transports = transports; this.ttl = options.ttl || 1800 * 1000; this.encrypted = options.encrypted; this.timeline = options.timeline; } CachedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; CachedStrategy.prototype.connect = function (minPriority, callback) { var encrypted = this.encrypted; var info = fetchTransportCache(encrypted); var strategies = [this.strategy]; if (info && info.timestamp + this.ttl >= util_1["default"].now()) { var transport = this.transports[info.transport]; if (transport) { this.timeline.info({ cached: true, transport: info.transport, latency: info.latency }); strategies.push(new sequential_strategy_1["default"]([transport], { timeout: info.latency * 2 + 1000, failFast: true })); } } var startTimestamp = util_1["default"].now(); var runner = strategies.pop().connect(minPriority, function cb(error, handshake) { if (error) { flushTransportCache(encrypted); if (strategies.length > 0) { startTimestamp = util_1["default"].now(); runner = strategies.pop().connect(minPriority, cb); } else { callback(error); } } else { storeTransportCache(encrypted, handshake.transport.name, util_1["default"].now() - startTimestamp); callback(null, handshake); } }); return { abort: function () { runner.abort(); }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; return CachedStrategy; }()); exports.__esModule = true; exports["default"] = CachedStrategy; function getTransportCacheKey(encrypted) { return "pusherTransport" + (encrypted ? "Encrypted" : "Unencrypted"); } function fetchTransportCache(encrypted) { var storage = runtime_1["default"].getLocalStorage(); if (storage) { try { var serializedCache = storage[getTransportCacheKey(encrypted)]; if (serializedCache) { return JSON.parse(serializedCache); } } catch (e) { flushTransportCache(encrypted); } } return null; } function storeTransportCache(encrypted, transport, latency) { var storage = runtime_1["default"].getLocalStorage(); if (storage) { try { storage[getTransportCacheKey(encrypted)] = Collections.safeJSONStringify({ timestamp: util_1["default"].now(), transport: transport, latency: latency }); } catch (e) { } } } function flushTransportCache(encrypted) { var storage = runtime_1["default"].getLocalStorage(); if (storage) { try { delete storage[getTransportCacheKey(encrypted)]; } catch (e) { } } } /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var timers_1 = __webpack_require__(7); var DelayedStrategy = (function () { function DelayedStrategy(strategy, _a) { var number = _a.delay; this.strategy = strategy; this.options = { delay: number }; } DelayedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; DelayedStrategy.prototype.connect = function (minPriority, callback) { var strategy = this.strategy; var runner; var timer = new timers_1.OneOffTimer(this.options.delay, function () { runner = strategy.connect(minPriority, callback); }); return { abort: function () { timer.ensureAborted(); if (runner) { runner.abort(); } }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; return DelayedStrategy; }()); exports.__esModule = true; exports["default"] = DelayedStrategy; /***/ }), /* 54 */ /***/ (function(module, exports) { "use strict"; var IfStrategy = (function () { function IfStrategy(test, trueBranch, falseBranch) { this.test = test; this.trueBranch = trueBranch; this.falseBranch = falseBranch; } IfStrategy.prototype.isSupported = function () { var branch = this.test() ? this.trueBranch : this.falseBranch; return branch.isSupported(); }; IfStrategy.prototype.connect = function (minPriority, callback) { var branch = this.test() ? this.trueBranch : this.falseBranch; return branch.connect(minPriority, callback); }; return IfStrategy; }()); exports.__esModule = true; exports["default"] = IfStrategy; /***/ }), /* 55 */ /***/ (function(module, exports) { "use strict"; var FirstConnectedStrategy = (function () { function FirstConnectedStrategy(strategy) { this.strategy = strategy; } FirstConnectedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; FirstConnectedStrategy.prototype.connect = function (minPriority, callback) { var runner = this.strategy.connect(minPriority, function (error, handshake) { if (handshake) { runner.abort(); } callback(error, handshake); }); return runner; }; return FirstConnectedStrategy; }()); exports.__esModule = true; exports["default"] = FirstConnectedStrategy; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var defaults_1 = __webpack_require__(11); exports.getGlobalConfig = function () { return { wsHost: defaults_1["default"].host, wsPort: defaults_1["default"].ws_port, wssPort: defaults_1["default"].wss_port, httpHost: defaults_1["default"].sockjs_host, httpPort: defaults_1["default"].sockjs_http_port, httpsPort: defaults_1["default"].sockjs_https_port, httpPath: defaults_1["default"].sockjs_path, statsHost: defaults_1["default"].stats_host, authEndpoint: defaults_1["default"].channel_auth_endpoint, authTransport: defaults_1["default"].channel_auth_transport, activity_timeout: defaults_1["default"].activity_timeout, pong_timeout: defaults_1["default"].pong_timeout, unavailable_timeout: defaults_1["default"].unavailable_timeout }; }; exports.getClusterConfig = function (clusterName) { return { wsHost: "ws-" + clusterName + ".pusher.com", httpHost: "sockjs-" + clusterName + ".pusher.com" }; }; /***/ }) /******/ ]);
src/Tabs.js
15lyfromsaturn/react-materialize
import React from 'react'; import cx from 'classnames'; import Row from './Row'; import Col from './Col'; class Tabs extends React.Component { componentDidMount() { if (typeof $ !== 'undefined') { $(this.tabsEl).tabs() } } _onSelect(idx, e) { if (this.props.hasOwnProperty('onChange')) { this.props.onChange(idx, e) } } render() { let {children, className, defaultValue, ...props} = this.props; return ( <Row> <Col s={12}> <ul className={cx('tabs', className)} ref={(ref) => this.tabsEl = ref}> { React.Children.map(children, (child, idx) => { let {title, tabWidth, className, active, disabled} = child.props; //if (!tabWidth) { // tabWidth = Math.floor(12 / count); //} let classes = { tab: true, disabled, col: true }; if (tabWidth) classes['s' + tabWidth] = true; let target = '#tab_' + idx; return ( <li className={cx(classes, className)} key={idx}> <a href={target} className={active || defaultValue === idx ? 'active' : ''} {...disabled ? {} : {onClick : this._onSelect.bind(this, idx)}}>{title}</a> </li> ); }) } </ul> </Col> { React.Children.map(children, (child, idx) => { return <Col id={'tab_' + idx} s={12} key={'tab' + idx}>{child.props.children}</Col>; }) } </Row> ); } } export default Tabs;
ajax/libs/abcjs/1.3/abcjs_plugin-min.js
seogi1004/cdnjs
/*! jQuery v1.7.2 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+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(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},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(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.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(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f .clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);/* * Raphael 1.4.3 - JavaScript Vector Library * * Copyright (c) 2010 Dmitry Baranovskiy (http://raphaeljs.com) * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license. */ Raphael=(function(){function aA(){if(aA.is(arguments[0],aV)){var d=arguments[0],e=B[bk](aA,d.splice(0,3+aA.is(d[0],ax))),S=e.set();for(var R=0,bp=d[o];R<bp;R++){var E=d[R]||{};a9.test(E.type)&&S[f](e[E.type]().attr(E))}return S}return B[bk](aA,arguments)}aA.version="1.4.3";var a=/[, ]+/,a9=/^(circle|rect|path|ellipse|text|image)$/,bm="prototype",ab="hasOwnProperty",V=document,aH=window,n={was:Object[bm][ab].call(aH,"Raphael"),is:aH.Raphael},bh=function(){},a5="appendChild",bk="apply",bf="concat",P="createTouch" in V,aG="",az=" ",F="split",M="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend"[F](az),ba={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},aN="join",o="length",bo=String[bm].toLowerCase,aj=Math,h=aj.max,a3=aj.min,ax="number",aa="string",aV="array",aP="toString",aS="fill",aK=Object[bm][aP],bc={},a6=aj.pow,f="push",bi=/^(?=[\da-f]$)/,c=/^url\(['"]?([^\)]+?)['"]?\)$/i,C=/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+\s*,\s*[\d\.]+\s*,\s*[\d\.]+(?:\s*,\s*[\d\.]+)?)\s*\)|rgba?\(\s*([\d\.]+%\s*,\s*[\d\.]+%\s*,\s*[\d\.]+%(?:\s*,\s*[\d\.]+%))\s*\)|hs[bl]\(\s*([\d\.]+\s*,\s*[\d\.]+\s*,\s*[\d\.]+)\s*\)|hs[bl]\(\s*([\d\.]+%\s*,\s*[\d\.]+%\s*,\s*[\d\.]+%)\s*\))\s*$/i,Y=aj.round,A="setAttribute",ae=parseFloat,N=parseInt,aT=" progid:DXImageTransform.Microsoft",a8=String[bm].toUpperCase,l={blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/",opacity:1,path:"M0,0",r:0,rotation:0,rx:0,ry:0,scale:"1 1",src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",translation:"0 0",width:0,x:0,y:0},ah={along:"along",blur:ax,"clip-rect":"csv",cx:ax,cy:ax,fill:"colour","fill-opacity":ax,"font-size":ax,height:ax,opacity:ax,path:"path",r:ax,rotation:"csv",rx:ax,ry:ax,scale:"csv",stroke:"colour","stroke-opacity":ax,"stroke-width":ax,translation:"csv",width:ax,x:ax,y:ax},bb="replace";aA.type=(aH.SVGAngle||V.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML");if(aA.type=="VML"){var ap=V.createElement("div");ap.innerHTML="<!--[if vml]><br><br><![endif]-->";if(ap.childNodes[o]!=2){return aA.type=null}ap=null}aA.svg=!(aA.vml=aA.type=="VML");bh[bm]=aA[bm];aA._id=0;aA._oid=0;aA.fn={};aA.is=function(e,d){d=bo.call(d);return(d=="object"&&e===Object(e))||(d=="undefined"&&typeof e==d)||(d=="null"&&e==null)||bo.call(aK.call(e).slice(8,-1))==d};aA.setWindow=function(d){aH=d;V=aH.document};var aW=function(e){if(aA.vml){var d=/^\s+|\s+$/g;aW=at(function(R){var S;R=(R+aG)[bb](d,aG);try{var bp=new aH.ActiveXObject("htmlfile");bp.write("<body>");bp.close();S=bp.body}catch(br){S=aH.createPopup().document.body}var i=S.createTextRange();try{S.style.color=R;var bq=i.queryCommandValue("ForeColor");bq=((bq&255)<<16)|(bq&65280)|((bq&16711680)>>>16);return"#"+("000000"+bq[aP](16)).slice(-6)}catch(br){return"none"}})}else{var E=V.createElement("i");E.title="Rapha\xebl Colour Picker";E.style.display="none";V.body[a5](E);aW=at(function(i){E.style.color=i;return V.defaultView.getComputedStyle(E,aG).getPropertyValue("color")})}return aW(e)};var au=function(){return"hsb("+[this.h,this.s,this.b]+")"},y=function(){return this.hex};aA.hsb2rgb=at(function(bs,bq,bw){if(aA.is(bs,"object")&&"h" in bs&&"s" in bs&&"b" in bs){bw=bs.b;bq=bs.s;bs=bs.h}var R,S,bx;if(bw==0){return{r:0,g:0,b:0,hex:"#000"}}if(bs>1||bq>1||bw>1){bs/=255;bq/=255;bw/=255}var bp=~~(bs*6),bt=(bs*6)-bp,E=bw*(1-bq),e=bw*(1-(bq*bt)),by=bw*(1-(bq*(1-bt)));R=[bw,e,E,E,by,bw,bw][bp];S=[by,bw,bw,e,E,E,by][bp];bx=[E,E,by,bw,bw,e,E][bp];R*=255;S*=255;bx*=255;var bu={r:R,g:S,b:bx,toString:y},d=(~~R)[aP](16),br=(~~S)[aP](16),bv=(~~bx)[aP](16);d=d[bb](bi,"0");br=br[bb](bi,"0");bv=bv[bb](bi,"0");bu.hex="#"+d+br+bv;return bu},aA);aA.rgb2hsb=at(function(d,e,bq){if(aA.is(d,"object")&&"r" in d&&"g" in d&&"b" in d){bq=d.b;e=d.g;d=d.r}if(aA.is(d,aa)){var bs=aA.getRGB(d);d=bs.r;e=bs.g;bq=bs.b}if(d>1||e>1||bq>1){d/=255;e/=255;bq/=255}var bp=h(d,e,bq),i=a3(d,e,bq),R,E,S=bp;if(i==bp){return{h:0,s:0,b:bp}}else{var br=(bp-i);E=br/bp;if(d==bp){R=(e-bq)/br}else{if(e==bp){R=2+((bq-d)/br)}else{R=4+((d-e)/br)}}R/=6;R<0&&R++;R>1&&R--}return{h:R,s:E,b:S,toString:au}},aA);var aX=/,?([achlmqrstvxz]),?/gi,aZ=/\s*,\s*/,j={hs:1,rg:1};aA._path2string=function(){return this.join(",")[bb](aX,"$1")};function at(E,e,d){function i(){var R=Array[bm].slice.call(arguments,0),bp=R[aN]("\u25ba"),S=i.cache=i.cache||{},bq=i.count=i.count||[];if(S[ab](bp)){return d?d(S[bp]):S[bp]}bq[o]>=1000&&delete S[bq.shift()];bq[f](bp);S[bp]=E[bk](e,R);return d?d(S[bp]):S[bp]}return i}aA.getRGB=at(function(e){if(!e||!!((e=e+aG).indexOf("-")+1)){return{r:-1,g:-1,b:-1,hex:"none",error:1}}if(e=="none"){return{r:-1,g:-1,b:-1,hex:"none"}}!(j[ab](e.substring(0,2))||e.charAt()=="#")&&(e=aW(e));var bp,i,E,bs,S,bt,bq=e.match(C);if(bq){if(bq[2]){bs=N(bq[2].substring(5),16);E=N(bq[2].substring(3,5),16);i=N(bq[2].substring(1,3),16)}if(bq[3]){bs=N((bt=bq[3].charAt(3))+bt,16);E=N((bt=bq[3].charAt(2))+bt,16);i=N((bt=bq[3].charAt(1))+bt,16)}if(bq[4]){bq=bq[4][F](aZ);i=ae(bq[0]);E=ae(bq[1]);bs=ae(bq[2]);S=ae(bq[3])}if(bq[5]){bq=bq[5][F](aZ);i=ae(bq[0])*2.55;E=ae(bq[1])*2.55;bs=ae(bq[2])*2.55;S=ae(bq[3])}if(bq[6]){bq=bq[6][F](aZ);i=ae(bq[0]);E=ae(bq[1]);bs=ae(bq[2]);return aA.hsb2rgb(i,E,bs)}if(bq[7]){bq=bq[7][F](aZ);i=ae(bq[0])*2.55;E=ae(bq[1])*2.55;bs=ae(bq[2])*2.55;return aA.hsb2rgb(i,E,bs)}bq={r:i,g:E,b:bs};var d=(~~i)[aP](16),R=(~~E)[aP](16),br=(~~bs)[aP](16);d=d[bb](bi,"0");R=R[bb](bi,"0");br=br[bb](bi,"0");bq.hex="#"+d+R+br;isFinite(ae(S))&&(bq.o=S);return bq}return{r:-1,g:-1,b:-1,hex:"none",error:1}},aA);aA.getColor=function(e){var i=this.getColor.start=this.getColor.start||{h:0,s:1,b:e||0.75},d=this.hsb2rgb(i.h,i.s,i.b);i.h+=0.075;if(i.h>1){i.h=0;i.s-=0.2;i.s<=0&&(this.getColor.start={h:0,s:1,b:i.b})}return d.hex};aA.getColor.reset=function(){delete this.start};var aI=/([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,ay=/(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig;aA.parsePathString=at(function(d){if(!d){return null}var i={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=[];if(aA.is(d,aV)&&aA.is(d[0],aV)){e=aJ(d)}if(!e[o]){(d+aG)[bb](aI,function(R,E,bq){var bp=[],S=bo.call(E);bq[bb](ay,function(bs,br){br&&bp[f](+br)});if(S=="m"&&bp[o]>2){e[f]([E][bf](bp.splice(0,2)));S="l";E=E=="m"?"l":"L"}while(bp[o]>=i[S]){e[f]([E][bf](bp.splice(0,i[S])));if(!i[S]){break}}})}e[aP]=aA._path2string;return e});aA.findDotsAtSegment=function(e,d,bD,bB,bp,R,br,bq,bx){var bv=1-bx,bu=a6(bv,3)*e+a6(bv,2)*3*bx*bD+bv*3*bx*bx*bp+a6(bx,3)*br,bs=a6(bv,3)*d+a6(bv,2)*3*bx*bB+bv*3*bx*bx*R+a6(bx,3)*bq,bz=e+2*bx*(bD-e)+bx*bx*(bp-2*bD+e),by=d+2*bx*(bB-d)+bx*bx*(R-2*bB+d),bC=bD+2*bx*(bp-bD)+bx*bx*(br-2*bp+bD),bA=bB+2*bx*(R-bB)+bx*bx*(bq-2*R+bB),bw=(1-bx)*e+bx*bD,bt=(1-bx)*d+bx*bB,E=(1-bx)*bp+bx*br,i=(1-bx)*R+bx*bq,S=(90-aj.atan((bz-bC)/(by-bA))*180/aj.PI); (bz>bC||by<bA)&&(S+=180);return{x:bu,y:bs,m:{x:bz,y:by},n:{x:bC,y:bA},start:{x:bw,y:bt},end:{x:E,y:i},alpha:S}};var ad=at(function(bu){if(!bu){return{x:0,y:0,width:0,height:0}}bu=O(bu);var br=0,bq=0,R=[],e=[],E;for(var S=0,bt=bu[o];S<bt;S++){E=bu[S];if(E[0]=="M"){br=E[1];bq=E[2];R[f](br);e[f](bq)}else{var bp=aU(br,bq,E[1],E[2],E[3],E[4],E[5],E[6]);R=R[bf](bp.min.x,bp.max.x);e=e[bf](bp.min.y,bp.max.y);br=E[5];bq=E[6]}}var d=a3[bk](0,R),bs=a3[bk](0,e);return{x:d,y:bs,width:h[bk](0,R)-d,height:h[bk](0,e)-bs}}),aJ=function(bp){var E=[];if(!aA.is(bp,aV)||!aA.is(bp&&bp[0],aV)){bp=aA.parsePathString(bp)}for(var e=0,R=bp[o];e<R;e++){E[e]=[];for(var d=0,S=bp[e][o];d<S;d++){E[e][d]=bp[e][d]}}E[aP]=aA._path2string;return E},am=at(function(R){if(!aA.is(R,aV)||!aA.is(R&&R[0],aV)){R=aA.parsePathString(R)}var bt=[],bv=0,bu=0,by=0,bx=0,E=0;if(R[0][0]=="M"){bv=R[0][1];bu=R[0][2];by=bv;bx=bu;E++;bt[f](["M",bv,bu])}for(var bq=E,bz=R[o];bq<bz;bq++){var d=bt[bq]=[],bw=R[bq];if(bw[0]!=bo.call(bw[0])){d[0]=bo.call(bw[0]);switch(d[0]){case"a":d[1]=bw[1];d[2]=bw[2];d[3]=bw[3];d[4]=bw[4];d[5]=bw[5];d[6]=+(bw[6]-bv).toFixed(3);d[7]=+(bw[7]-bu).toFixed(3);break;case"v":d[1]=+(bw[1]-bu).toFixed(3);break;case"m":by=bw[1];bx=bw[2];default:for(var bp=1,br=bw[o];bp<br;bp++){d[bp]=+(bw[bp]-((bp%2)?bv:bu)).toFixed(3)}}}else{d=bt[bq]=[];if(bw[0]=="m"){by=bw[1]+bv;bx=bw[2]+bu}for(var S=0,e=bw[o];S<e;S++){bt[bq][S]=bw[S]}}var bs=bt[bq][o];switch(bt[bq][0]){case"z":bv=by;bu=bx;break;case"h":bv+=+bt[bq][bs-1];break;case"v":bu+=+bt[bq][bs-1];break;default:bv+=+bt[bq][bs-2];bu+=+bt[bq][bs-1]}}bt[aP]=aA._path2string;return bt},0,aJ),v=at(function(R){if(!aA.is(R,aV)||!aA.is(R&&R[0],aV)){R=aA.parsePathString(R)}var bs=[],bu=0,bt=0,bx=0,bw=0,E=0;if(R[0][0]=="M"){bu=+R[0][1];bt=+R[0][2];bx=bu;bw=bt;E++;bs[0]=["M",bu,bt]}for(var bq=E,by=R[o];bq<by;bq++){var d=bs[bq]=[],bv=R[bq];if(bv[0]!=a8.call(bv[0])){d[0]=a8.call(bv[0]);switch(d[0]){case"A":d[1]=bv[1];d[2]=bv[2];d[3]=bv[3];d[4]=bv[4];d[5]=bv[5];d[6]=+(bv[6]+bu);d[7]=+(bv[7]+bt);break;case"V":d[1]=+bv[1]+bt;break;case"H":d[1]=+bv[1]+bu;break;case"M":bx=+bv[1]+bu;bw=+bv[2]+bt;default:for(var bp=1,br=bv[o];bp<br;bp++){d[bp]=+bv[bp]+((bp%2)?bu:bt)}}}else{for(var S=0,e=bv[o];S<e;S++){bs[bq][S]=bv[S]}}switch(d[0]){case"Z":bu=bx;bt=bw;break;case"H":bu=d[1];break;case"V":bt=d[1];break;default:bu=bs[bq][bs[bq][o]-2];bt=bs[bq][bs[bq][o]-1]}}bs[aP]=aA._path2string;return bs},null,aJ),bl=function(e,E,d,i){return[e,E,d,i,d,i]},a4=function(e,E,bp,R,d,i){var S=1/3,bq=2/3;return[S*e+bq*bp,S*E+bq*R,S*d+bq*bp,S*i+bq*R,d,i]},U=function(by,b3,bH,bF,bz,bt,S,bx,b2,bA){var R=aj.PI,bE=R*120/180,d=R/180*(+bz||0),bL=[],bI,bZ=at(function(b4,b7,i){var b6=b4*aj.cos(i)-b7*aj.sin(i),b5=b4*aj.sin(i)+b7*aj.cos(i);return{x:b6,y:b5}});if(!bA){bI=bZ(by,b3,-d);by=bI.x;b3=bI.y;bI=bZ(bx,b2,-d);bx=bI.x;b2=bI.y;var e=aj.cos(R/180*bz),bv=aj.sin(R/180*bz),bN=(by-bx)/2,bM=(b3-b2)/2;var bX=(bN*bN)/(bH*bH)+(bM*bM)/(bF*bF);if(bX>1){bX=aj.sqrt(bX);bH=bX*bH;bF=bX*bF}var E=bH*bH,bQ=bF*bF,bS=(bt==S?-1:1)*aj.sqrt(aj.abs((E*bQ-E*bM*bM-bQ*bN*bN)/(E*bM*bM+bQ*bN*bN))),bC=bS*bH*bM/bF+(by+bx)/2,bB=bS*-bF*bN/bH+(b3+b2)/2,bs=aj.asin(((b3-bB)/bF).toFixed(7)),br=aj.asin(((b2-bB)/bF).toFixed(7));bs=by<bC?R-bs:bs;br=bx<bC?R-br:br;bs<0&&(bs=R*2+bs);br<0&&(br=R*2+br);if(S&&bs>br){bs=bs-R*2}if(!S&&br>bs){br=br-R*2}}else{bs=bA[0];br=bA[1];bC=bA[2];bB=bA[3]}var bw=br-bs;if(aj.abs(bw)>bE){var bD=br,bG=bx,bu=b2;br=bs+bE*(S&&br>bs?1:-1);bx=bC+bH*aj.cos(br);b2=bB+bF*aj.sin(br);bL=U(bx,b2,bH,bF,bz,0,S,bG,bu,[br,bD,bC,bB])}bw=br-bs;var bq=aj.cos(bs),b1=aj.sin(bs),bp=aj.cos(br),b0=aj.sin(br),bO=aj.tan(bw/4),bR=4/3*bH*bO,bP=4/3*bF*bO,bY=[by,b3],bW=[by+bR*b1,b3-bP*bq],bV=[bx+bR*b0,b2-bP*bp],bT=[bx,b2];bW[0]=2*bY[0]-bW[0];bW[1]=2*bY[1]-bW[1];if(bA){return[bW,bV,bT][bf](bL)}else{bL=[bW,bV,bT][bf](bL)[aN]()[F](",");var bJ=[];for(var bU=0,bK=bL[o];bU<bK;bU++){bJ[bU]=bU%2?bZ(bL[bU-1],bL[bU],d).y:bZ(bL[bU],bL[bU+1],d).x}return bJ}},X=function(e,d,E,i,br,bq,bp,S,bs){var R=1-bs;return{x:a6(R,3)*e+a6(R,2)*3*bs*E+R*3*bs*bs*br+a6(bs,3)*bp,y:a6(R,3)*d+a6(R,2)*3*bs*i+R*3*bs*bs*bq+a6(bs,3)*S}},aU=at(function(i,d,R,E,by,bx,bu,br){var bw=(by-2*R+i)-(bu-2*by+R),bt=2*(R-i)-2*(by-R),bq=i-R,bp=(-bt+aj.sqrt(bt*bt-4*bw*bq))/2/bw,S=(-bt-aj.sqrt(bt*bt-4*bw*bq))/2/bw,bs=[d,br],bv=[i,bu],e;aj.abs(bp)>1000000000000&&(bp=0.5);aj.abs(S)>1000000000000&&(S=0.5);if(bp>0&&bp<1){e=X(i,d,R,E,by,bx,bu,br,bp);bv[f](e.x);bs[f](e.y)}if(S>0&&S<1){e=X(i,d,R,E,by,bx,bu,br,S);bv[f](e.x);bs[f](e.y)}bw=(bx-2*E+d)-(br-2*bx+E);bt=2*(E-d)-2*(bx-E);bq=d-E;bp=(-bt+aj.sqrt(bt*bt-4*bw*bq))/2/bw;S=(-bt-aj.sqrt(bt*bt-4*bw*bq))/2/bw;aj.abs(bp)>1000000000000&&(bp=0.5);aj.abs(S)>1000000000000&&(S=0.5);if(bp>0&&bp<1){e=X(i,d,R,E,by,bx,bu,br,bp);bv[f](e.x);bs[f](e.y)}if(S>0&&S<1){e=X(i,d,R,E,by,bx,bu,br,S);bv[f](e.x);bs[f](e.y)}return{min:{x:a3[bk](0,bv),y:a3[bk](0,bs)},max:{x:h[bk](0,bv),y:h[bk](0,bs)}}}),O=at(function(by,bt){var R=v(by),bu=bt&&v(bt),bv={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},d={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},bp=function(bz,bA){var i,bB;if(!bz){return["C",bA.x,bA.y,bA.x,bA.y,bA.x,bA.y]}!(bz[0] in {T:1,Q:1})&&(bA.qx=bA.qy=null);switch(bz[0]){case"M":bA.X=bz[1];bA.Y=bz[2];break;case"A":bz=["C"][bf](U[bk](0,[bA.x,bA.y][bf](bz.slice(1))));break;case"S":i=bA.x+(bA.x-(bA.bx||bA.x));bB=bA.y+(bA.y-(bA.by||bA.y));bz=["C",i,bB][bf](bz.slice(1));break;case"T":bA.qx=bA.x+(bA.x-(bA.qx||bA.x));bA.qy=bA.y+(bA.y-(bA.qy||bA.y));bz=["C"][bf](a4(bA.x,bA.y,bA.qx,bA.qy,bz[1],bz[2]));break;case"Q":bA.qx=bz[1];bA.qy=bz[2];bz=["C"][bf](a4(bA.x,bA.y,bz[1],bz[2],bz[3],bz[4]));break;case"L":bz=["C"][bf](bl(bA.x,bA.y,bz[1],bz[2]));break;case"H":bz=["C"][bf](bl(bA.x,bA.y,bz[1],bA.y));break;case"V":bz=["C"][bf](bl(bA.x,bA.y,bA.x,bz[1]));break;case"Z":bz=["C"][bf](bl(bA.x,bA.y,bA.X,bA.Y));break}return bz},e=function(bz,bA){if(bz[bA][o]>7){bz[bA].shift();var bB=bz[bA];while(bB[o]){bz.splice(bA++,0,["C"][bf](bB.splice(0,6)))}bz.splice(bA,1);bw=h(R[o],bu&&bu[o]||0)}},E=function(bD,bC,bA,bz,bB){if(bD&&bC&&bD[bB][0]=="M"&&bC[bB][0]!="M"){bC.splice(bB,0,["M",bz.x,bz.y]);bA.bx=0;bA.by=0;bA.x=bD[bB][1];bA.y=bD[bB][2];bw=h(R[o],bu&&bu[o]||0)}};for(var br=0,bw=h(R[o],bu&&bu[o]||0);br<bw;br++){R[br]=bp(R[br],bv);e(R,br);bu&&(bu[br]=bp(bu[br],d));bu&&e(bu,br);E(R,bu,bv,d,br);E(bu,R,d,bv,br);var bq=R[br],bx=bu&&bu[br],S=bq[o],bs=bu&&bx[o];bv.x=bq[S-2];bv.y=bq[S-1];bv.bx=ae(bq[S-4])||bv.x;bv.by=ae(bq[S-3])||bv.y;d.bx=bu&&(ae(bx[bs-4])||d.x);d.by=bu&&(ae(bx[bs-3])||d.y);d.x=bu&&bx[bs-2];d.y=bu&&bx[bs-1]}return bu?[R,bu]:R},null,aJ),t=at(function(bt){var bs=[];for(var bp=0,bu=bt[o];bp<bu;bp++){var e={},br=bt[bp].match(/^([^:]*):?([\d\.]*)/);e.color=aA.getRGB(br[1]);if(e.color.error){return null}e.color=e.color.hex;br[2]&&(e.offset=br[2]+"%");bs[f](e)}for(bp=1,bu=bs[o]-1;bp<bu;bp++){if(!bs[bp].offset){var E=ae(bs[bp-1].offset||0),R=0;for(var S=bp+1;S<bu;S++){if(bs[S].offset){R=bs[S].offset;break}}if(!R){R=100;S=bu}R=ae(R);var bq=(R-E)/(S-bp+1);for(;bp<S;bp++){E+=bq;bs[bp].offset=E+"%"}}}return bs}),aB=function(d,R,i,E){var e; if(aA.is(d,aa)||aA.is(d,"object")){e=aA.is(d,aa)?V.getElementById(d):d;if(e.tagName){if(R==null){return{container:e,width:e.style.pixelWidth||e.offsetWidth,height:e.style.pixelHeight||e.offsetHeight}}else{return{container:e,width:R,height:i}}}}else{return{container:1,x:d,y:R,width:i,height:E}}},a0=function(d,i){var e=this;for(var E in i){if(i[ab](E)&&!(E in d)){switch(typeof i[E]){case"function":(function(R){d[E]=d===e?R:function(){return R[bk](e,arguments)}})(i[E]);break;case"object":d[E]=d[E]||{};a0.call(this,d[E],i[E]);break;default:d[E]=i[E];break}}}},aw=function(d,e){d==e.top&&(e.top=d.prev);d==e.bottom&&(e.bottom=d.next);d.next&&(d.next.prev=d.prev);d.prev&&(d.prev.next=d.next)},ag=function(d,e){if(e.top===d){return}aw(d,e);d.next=null;d.prev=e.top;e.top.next=d;e.top=d},m=function(d,e){if(e.bottom===d){return}aw(d,e);d.next=e.bottom;d.prev=null;e.bottom.prev=d;e.bottom=d},G=function(e,d,i){aw(e,i);d==i.top&&(i.top=e);d.next&&(d.next.prev=e);e.next=d.next;e.prev=d;d.next=e},aD=function(e,d,i){aw(e,i);d==i.bottom&&(i.bottom=e);d.prev&&(d.prev.next=e);e.prev=d.prev;d.prev=e;e.next=d},w=function(d){return function(){throw new Error("Rapha\xebl: you are calling to method \u201c"+d+"\u201d of removed object")}},aF=/^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/;if(aA.svg){bh[bm].svgns="http://www.w3.org/2000/svg";bh[bm].xlink="http://www.w3.org/1999/xlink";Y=function(d){return +d+(~~d===d)*0.5};var a2=function(i,d){if(d){for(var e in d){if(d[ab](e)){i[A](e,d[e]+aG)}}}else{i=V.createElementNS(bh[bm].svgns,i);i.style.webkitTapHighlightColor="rgba(0,0,0,0)";return i}};aA[aP]=function(){return"Your browser supports SVG.\nYou are running Rapha\xebl "+this.version};var u=function(d,E){var e=a2("path");E.canvas&&E.canvas[a5](e);var i=new aL(e,E);i.type="path";ai(i,{fill:"none",stroke:"#000",path:d});return i};var b=function(R,bx,d){var bu="linear",br=0.5,bp=0.5,bz=R.style;bx=(bx+aG)[bb](aF,function(bB,i,bC){bu="radial";if(i&&bC){br=ae(i);bp=ae(bC);var bA=((bp>0.5)*2-1);a6(br-0.5,2)+a6(bp-0.5,2)>0.25&&(bp=aj.sqrt(0.25-a6(br-0.5,2))*bA+0.5)&&bp!=0.5&&(bp=bp.toFixed(5)-0.00001*bA)}return aG});bx=bx[F](/\s*\-\s*/);if(bu=="linear"){var bq=bx.shift();bq=-ae(bq);if(isNaN(bq)){return null}var S=[0,0,aj.cos(bq*aj.PI/180),aj.sin(bq*aj.PI/180)],bw=1/(h(aj.abs(S[2]),aj.abs(S[3]))||1);S[2]*=bw;S[3]*=bw;if(S[2]<0){S[0]=-S[2];S[2]=0}if(S[3]<0){S[1]=-S[3];S[3]=0}}var bt=t(bx);if(!bt){return null}var e=R.getAttribute(aS);e=e.match(/^url\(#(.*)\)$/);e&&d.defs.removeChild(V.getElementById(e[1]));var E=a2(bu+"Gradient");E.id="r"+(aA._id++)[aP](36);a2(E,bu=="radial"?{fx:br,fy:bp}:{x1:S[0],y1:S[1],x2:S[2],y2:S[3]});d.defs[a5](E);for(var bs=0,by=bt[o];bs<by;bs++){var bv=a2("stop");a2(bv,{offset:bt[bs].offset?bt[bs].offset:!bs?"0%":"100%","stop-color":bt[bs].color||"#fff"});E[a5](bv)}a2(R,{fill:"url(#"+E.id+")",opacity:1,"fill-opacity":1});bz.fill=aG;bz.opacity=1;bz.fillOpacity=1;return 1};var W=function(e){var d=e.getBBox();a2(e.pattern,{patternTransform:aA.format("translate({0},{1})",d.x,d.y)})};var ai=function(bw,bF){var bz={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},bB=bw.node,bx=bw.attrs,bt=bw.rotate(),bp=function(bM,bL){bL=bz[bo.call(bL)];if(bL){var bJ=bM.attrs["stroke-width"]||"1",bH={round:bJ,square:bJ,butt:0}[bM.attrs["stroke-linecap"]||bF["stroke-linecap"]]||0,bK=[];var bI=bL[o];while(bI--){bK[bI]=bL[bI]*bJ+((bI%2)?1:-1)*bH}a2(bB,{"stroke-dasharray":bK[aN](",")})}};bF[ab]("rotation")&&(bt=bF.rotation);var bs=(bt+aG)[F](a);if(!(bs.length-1)){bs=null}else{bs[1]=+bs[1];bs[2]=+bs[2]}ae(bt)&&bw.rotate(0,true);for(var bA in bF){if(bF[ab](bA)){if(!l[ab](bA)){continue}var by=bF[bA];bx[bA]=by;switch(bA){case"blur":bw.blur(by);break;case"rotation":bw.rotate(by,true);break;case"href":case"title":case"target":var bD=bB.parentNode;if(bo.call(bD.tagName)!="a"){var R=a2("a");bD.insertBefore(R,bB);R[a5](bB);bD=R}bD.setAttributeNS(bw.paper.xlink,bA,by);break;case"cursor":bB.style.cursor=by;break;case"clip-rect":var e=(by+aG)[F](a);if(e[o]==4){bw.clip&&bw.clip.parentNode.parentNode.removeChild(bw.clip.parentNode);var i=a2("clipPath"),bC=a2("rect");i.id="r"+(aA._id++)[aP](36);a2(bC,{x:e[0],y:e[1],width:e[2],height:e[3]});i[a5](bC);bw.paper.defs[a5](i);a2(bB,{"clip-path":"url(#"+i.id+")"});bw.clip=bC}if(!by){var bE=V.getElementById(bB.getAttribute("clip-path")[bb](/(^url\(#|\)$)/g,aG));bE&&bE.parentNode.removeChild(bE);a2(bB,{"clip-path":aG});delete bw.clip}break;case"path":if(bw.type=="path"){a2(bB,{d:by?bx.path=v(by):"M0,0"})}break;case"width":bB[A](bA,by);if(bx.fx){bA="x";by=bx.x}else{break}case"x":if(bx.fx){by=-bx.x-(bx.width||0)}case"rx":if(bA=="rx"&&bw.type=="rect"){break}case"cx":bs&&(bA=="x"||bA=="cx")&&(bs[1]+=by-bx[bA]);bB[A](bA,Y(by));bw.pattern&&W(bw);break;case"height":bB[A](bA,by);if(bx.fy){bA="y";by=bx.y}else{break}case"y":if(bx.fy){by=-bx.y-(bx.height||0)}case"ry":if(bA=="ry"&&bw.type=="rect"){break}case"cy":bs&&(bA=="y"||bA=="cy")&&(bs[2]+=by-bx[bA]);bB[A](bA,Y(by));bw.pattern&&W(bw);break;case"r":if(bw.type=="rect"){a2(bB,{rx:by,ry:by})}else{bB[A](bA,by)}break;case"src":if(bw.type=="image"){bB.setAttributeNS(bw.paper.xlink,"href",by)}break;case"stroke-width":bB.style.strokeWidth=by;bB[A](bA,by);if(bx["stroke-dasharray"]){bp(bw,bx["stroke-dasharray"])}break;case"stroke-dasharray":bp(bw,by);break;case"translation":var bq=(by+aG)[F](a);bq[0]=+bq[0]||0;bq[1]=+bq[1]||0;if(bs){bs[1]+=bq[0];bs[2]+=bq[1]}x.call(bw,bq[0],bq[1]);break;case"scale":bq=(by+aG)[F](a);bw.scale(+bq[0]||1,+bq[1]||+bq[0]||1,isNaN(ae(bq[2]))?null:+bq[2],isNaN(ae(bq[3]))?null:+bq[3]);break;case aS:var S=(by+aG).match(c);if(S){i=a2("pattern");var bv=a2("image");i.id="r"+(aA._id++)[aP](36);a2(i,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1});a2(bv,{x:0,y:0});bv.setAttributeNS(bw.paper.xlink,"href",S[1]);i[a5](bv);var bG=V.createElement("img");bG.style.cssText="position:absolute;left:-9999em;top-9999em";bG.onload=function(){a2(i,{width:this.offsetWidth,height:this.offsetHeight});a2(bv,{width:this.offsetWidth,height:this.offsetHeight});V.body.removeChild(this);bw.paper.safari()};V.body[a5](bG);bG.src=S[1];bw.paper.defs[a5](i);bB.style.fill="url(#"+i.id+")";a2(bB,{fill:"url(#"+i.id+")"});bw.pattern=i;bw.pattern&&W(bw);break}var E=aA.getRGB(by);if(!E.error){delete bF.gradient;delete bx.gradient;!aA.is(bx.opacity,"undefined")&&aA.is(bF.opacity,"undefined")&&a2(bB,{opacity:bx.opacity});!aA.is(bx["fill-opacity"],"undefined")&&aA.is(bF["fill-opacity"],"undefined")&&a2(bB,{"fill-opacity":bx["fill-opacity"]})}else{if((({circle:1,ellipse:1})[ab](bw.type)||(by+aG).charAt()!="r")&&b(bB,by,bw.paper)){bx.gradient=by;bx.fill="none";break}}E[ab]("o")&&a2(bB,{"fill-opacity":E.o/100});case"stroke":E=aA.getRGB(by);bB[A](bA,E.hex);bA=="stroke"&&E[ab]("o")&&a2(bB,{"stroke-opacity":E.o/100});break;case"gradient":(({circle:1,ellipse:1})[ab](bw.type)||(by+aG).charAt()!="r")&&b(bB,by,bw.paper);break;case"opacity":case"fill-opacity":if(bx.gradient){var d=V.getElementById(bB.getAttribute(aS)[bb](/^url\(#|\)$/g,aG)); if(d){var br=d.getElementsByTagName("stop");br[br[o]-1][A]("stop-opacity",by)}break}default:bA=="font-size"&&(by=N(by,10)+"px");var bu=bA[bb](/(\-.)/g,function(bH){return a8.call(bH.substring(1))});bB.style[bu]=by;bB[A](bA,by);break}}}L(bw,bF);if(bs){bw.rotate(bs.join(az))}else{ae(bt)&&bw.rotate(bt,true)}};var k=1.2,L=function(d,R){if(d.type!="text"||!(R[ab]("text")||R[ab]("font")||R[ab]("font-size")||R[ab]("x")||R[ab]("y"))){return}var bs=d.attrs,e=d.node,bu=e.firstChild?N(V.defaultView.getComputedStyle(e.firstChild,aG).getPropertyValue("font-size"),10):10;if(R[ab]("text")){bs.text=R.text;while(e.firstChild){e.removeChild(e.firstChild)}var E=(R.text+aG)[F]("\n");for(var S=0,bt=E[o];S<bt;S++){if(E[S]){var bq=a2("tspan");S&&a2(bq,{dy:bu*k,x:bs.x});bq[a5](V.createTextNode(E[S]));e[a5](bq)}}}else{E=e.getElementsByTagName("tspan");for(S=0,bt=E[o];S<bt;S++){S&&a2(E[S],{dy:bu*k,x:bs.x})}}a2(e,{y:bs.y});var bp=d.getBBox(),br=bs.y-(bp.y+bp.height/2);br&&isFinite(br)&&a2(e,{y:bs.y+br})},aL=function(e,d){var E=0,i=0;this[0]=e;this.id=aA._oid++;this.node=e;e.raphael=this;this.paper=d;this.attrs=this.attrs||{};this.transformations=[];this._={tx:0,ty:0,rt:{deg:0,cx:0,cy:0},sx:1,sy:1};!d.bottom&&(d.bottom=this);this.prev=d.top;d.top&&(d.top.next=this);d.top=this;this.next=null};aL[bm].rotate=function(e,d,E){if(this.removed){return this}if(e==null){if(this._.rt.cx){return[this._.rt.deg,this._.rt.cx,this._.rt.cy][aN](az)}return this._.rt.deg}var i=this.getBBox();e=(e+aG)[F](a);if(e[o]-1){d=ae(e[1]);E=ae(e[2])}e=ae(e[0]);if(d!=null){this._.rt.deg=e}else{this._.rt.deg+=e}(E==null)&&(d=null);this._.rt.cx=d;this._.rt.cy=E;d=d==null?i.x+i.width/2:d;E=E==null?i.y+i.height/2:E;if(this._.rt.deg){this.transformations[0]=aA.format("rotate({0} {1} {2})",this._.rt.deg,d,E);this.clip&&a2(this.clip,{transform:aA.format("rotate({0} {1} {2})",-this._.rt.deg,d,E)})}else{this.transformations[0]=aG;this.clip&&a2(this.clip,{transform:aG})}a2(this.node,{transform:this.transformations[aN](az)});return this};aL[bm].hide=function(){!this.removed&&(this.node.style.display="none");return this};aL[bm].show=function(){!this.removed&&(this.node.style.display="");return this};aL[bm].remove=function(){if(this.removed){return}aw(this,this.paper);this.node.parentNode.removeChild(this.node);for(var d in this){delete this[d]}this.removed=true};aL[bm].getBBox=function(){if(this.removed){return this}if(this.type=="path"){return ad(this.attrs.path)}if(this.node.style.display=="none"){this.show();var E=true}var bq={};try{bq=this.node.getBBox()}catch(S){}finally{bq=bq||{}}if(this.type=="text"){bq={x:bq.x,y:Infinity,width:0,height:0};for(var d=0,R=this.node.getNumberOfChars();d<R;d++){var bp=this.node.getExtentOfChar(d);(bp.y<bq.y)&&(bq.y=bp.y);(bp.y+bp.height-bq.y>bq.height)&&(bq.height=bp.y+bp.height-bq.y);(bp.x+bp.width-bq.x>bq.width)&&(bq.width=bp.x+bp.width-bq.x)}}E&&this.hide();return bq};aL[bm].attr=function(E,bq){if(this.removed){return this}if(E==null){var S={};for(var R in this.attrs){if(this.attrs[ab](R)){S[R]=this.attrs[R]}}this._.rt.deg&&(S.rotation=this.rotate());(this._.sx!=1||this._.sy!=1)&&(S.scale=this.scale());S.gradient&&S.fill=="none"&&(S.fill=S.gradient)&&delete S.gradient;return S}if(bq==null&&aA.is(E,aa)){if(E=="translation"){return x.call(this)}if(E=="rotation"){return this.rotate()}if(E=="scale"){return this.scale()}if(E==aS&&this.attrs.fill=="none"&&this.attrs.gradient){return this.attrs.gradient}return this.attrs[E]}if(bq==null&&aA.is(E,aV)){var d={};for(var e=0,bp=E.length;e<bp;e++){d[E[e]]=this.attr(E[e])}return d}if(bq!=null){var br={};br[E]=bq;ai(this,br)}else{if(E!=null&&aA.is(E,"object")){ai(this,E)}}return this};aL[bm].toFront=function(){if(this.removed){return this}this.node.parentNode[a5](this.node);var d=this.paper;d.top!=this&&ag(this,d);return this};aL[bm].toBack=function(){if(this.removed){return this}if(this.node.parentNode.firstChild!=this.node){this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild);m(this,this.paper);var d=this.paper}return this};aL[bm].insertAfter=function(d){if(this.removed){return this}var e=d.node;if(e.nextSibling){e.parentNode.insertBefore(this.node,e.nextSibling)}else{e.parentNode[a5](this.node)}G(this,d,this.paper);return this};aL[bm].insertBefore=function(d){if(this.removed){return this}var e=d.node;e.parentNode.insertBefore(this.node,e);aD(this,d,this.paper);return this};aL[bm].blur=function(e){var d=this;if(+e!==0){var i=a2("filter"),E=a2("feGaussianBlur");d.attrs.blur=e;i.id="r"+(aA._id++)[aP](36);a2(E,{stdDeviation:+e||1.5});i.appendChild(E);d.paper.defs.appendChild(i);d._blur=i;a2(d.node,{filter:"url(#"+i.id+")"})}else{if(d._blur){d._blur.parentNode.removeChild(d._blur);delete d._blur;delete d.attrs.blur}d.node.removeAttribute("filter")}};var Z=function(e,d,S,R){d=Y(d);S=Y(S);var E=a2("circle");e.canvas&&e.canvas[a5](E);var i=new aL(E,e);i.attrs={cx:d,cy:S,r:R,fill:"none",stroke:"#000"};i.type="circle";a2(E,i.attrs);return i};var aY=function(i,d,bq,e,S,bp){d=Y(d);bq=Y(bq);var R=a2("rect");i.canvas&&i.canvas[a5](R);var E=new aL(R,i);E.attrs={x:d,y:bq,width:e,height:S,r:bp||0,rx:bp||0,ry:bp||0,fill:"none",stroke:"#000"};E.type="rect";a2(R,E.attrs);return E};var ar=function(e,d,bp,S,R){d=Y(d);bp=Y(bp);var E=a2("ellipse");e.canvas&&e.canvas[a5](E);var i=new aL(E,e);i.attrs={cx:d,cy:bp,rx:S,ry:R,fill:"none",stroke:"#000"};i.type="ellipse";a2(E,i.attrs);return i};var s=function(i,bp,d,bq,e,S){var R=a2("image");a2(R,{x:d,y:bq,width:e,height:S,preserveAspectRatio:"none"});R.setAttributeNS(i.xlink,"href",bp);i.canvas&&i.canvas[a5](R);var E=new aL(R,i);E.attrs={x:d,y:bq,width:e,height:S,src:bp};E.type="image";return E};var af=function(e,d,S,R){var E=a2("text");a2(E,{x:d,y:S,"text-anchor":"middle"});e.canvas&&e.canvas[a5](E);var i=new aL(E,e);i.attrs={x:d,y:S,"text-anchor":"middle",text:R,font:l.font,stroke:"none",fill:"#000"};i.type="text";ai(i,i.attrs);return i};var bj=function(e,d){this.width=e||this.width;this.height=d||this.height;this.canvas[A]("width",this.width);this.canvas[A]("height",this.height);return this};var B=function(){var E=aB[bk](0,arguments),i=E&&E.container,e=E.x,bp=E.y,R=E.width,d=E.height;if(!i){throw new Error("SVG container not found.")}var S=a2("svg");e=e||0;bp=bp||0;R=R||512;d=d||342;a2(S,{xmlns:"http://www.w3.org/2000/svg",version:1.1,width:R,height:d});if(i==1){S.style.cssText="position:absolute;left:"+e+"px;top:"+bp+"px";V.body[a5](S)}else{if(i.firstChild){i.insertBefore(S,i.firstChild)}else{i[a5](S)}}i=new bh;i.width=R;i.height=d;i.canvas=S;a0.call(i,i,aA.fn);i.clear();return i};bh[bm].clear=function(){var d=this.canvas;while(d.firstChild){d.removeChild(d.firstChild)}this.bottom=this.top=null;(this.desc=a2("desc"))[a5](V.createTextNode("Created with Rapha\xebl"));d[a5](this.desc);d[a5](this.defs=a2("defs"))};bh[bm].remove=function(){this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var d in this){this[d]=w(d)}}}if(aA.vml){var J={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},aE=/([clmz]),?([^clmz]*)/gi,bn=/-?[^,\s-]+/g,aO=1000+az+1000,r=10,p={path:1,rect:1},a1=function(bu){var br=/[ahqstv]/ig,E=v; (bu+aG).match(br)&&(E=O);br=/[clmz]/g;if(E==v&&!(bu+aG).match(br)){var bq=(bu+aG)[bb](aE,function(bx,bz,bv){var by=[],i=bo.call(bz)=="m",bw=J[bz];bv[bb](bn,function(bA){if(i&&by[o]==2){bw+=by+J[bz=="m"?"l":"L"];by=[]}by[f](Y(bA*r))});return bw+by});return bq}var bs=E(bu),e,d;bq=[];for(var S=0,bt=bs[o];S<bt;S++){e=bs[S];d=bo.call(bs[S][0]);d=="z"&&(d="x");for(var R=1,bp=e[o];R<bp;R++){d+=Y(e[R]*r)+(R!=bp-1?",":aG)}bq[f](d)}return bq[aN](az)};aA[aP]=function(){return"Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl "+this.version};u=function(i,e){var S=aq("group");S.style.cssText="position:absolute;left:0;top:0;width:"+e.width+"px;height:"+e.height+"px";S.coordsize=e.coordsize;S.coordorigin=e.coordorigin;var R=aq("shape"),E=R.style;E.width=e.width+"px";E.height=e.height+"px";R.coordsize=aO;R.coordorigin=e.coordorigin;S[a5](R);var bp=new aL(R,S,e),d={fill:"none",stroke:"#000"};i&&(d.path=i);bp.isAbsolute=true;bp.type="path";bp.path=[];bp.Path=aG;ai(bp,d);e.canvas[a5](S);return bp};ai=function(bs,bz){bs.attrs=bs.attrs||{};var bw=bs.node,bA=bs.attrs,bp=bw.style,E,by=(bz.x!=bA.x||bz.y!=bA.y||bz.width!=bA.width||bz.height!=bA.height||bz.r!=bA.r)&&bs.type=="rect",bE=bs;for(var bq in bz){if(bz[ab](bq)){bA[bq]=bz[bq]}}if(by){bA.path=al(bA.x,bA.y,bA.width,bA.height,bA.r);bs.X=bA.x;bs.Y=bA.y;bs.W=bA.width;bs.H=bA.height}bz.href&&(bw.href=bz.href);bz.title&&(bw.title=bz.title);bz.target&&(bw.target=bz.target);bz.cursor&&(bp.cursor=bz.cursor);"blur" in bz&&bs.blur(bz.blur);if(bz.path&&bs.type=="path"||by){bw.path=a1(bA.path)}if(bz.rotation!=null){bs.rotate(bz.rotation,true)}if(bz.translation){E=(bz.translation+aG)[F](a);x.call(bs,E[0],E[1]);if(bs._.rt.cx!=null){bs._.rt.cx+=+E[0];bs._.rt.cy+=+E[1];bs.setBox(bs.attrs,E[0],E[1])}}if(bz.scale){E=(bz.scale+aG)[F](a);bs.scale(+E[0]||1,+E[1]||+E[0]||1,+E[2]||null,+E[3]||null)}if("clip-rect" in bz){var d=(bz["clip-rect"]+aG)[F](a);if(d[o]==4){d[2]=+d[2]+(+d[0]);d[3]=+d[3]+(+d[1]);var br=bw.clipRect||V.createElement("div"),bD=br.style,S=bw.parentNode;bD.clip=aA.format("rect({1}px {2}px {3}px {0}px)",d);if(!bw.clipRect){bD.position="absolute";bD.top=0;bD.left=0;bD.width=bs.paper.width+"px";bD.height=bs.paper.height+"px";S.parentNode.insertBefore(br,S);br[a5](S);bw.clipRect=br}}if(!bz["clip-rect"]){bw.clipRect&&(bw.clipRect.style.clip=aG)}}if(bs.type=="image"&&bz.src){bw.src=bz.src}if(bs.type=="image"&&bz.opacity){bw.filterOpacity=aT+".Alpha(opacity="+(bz.opacity*100)+")";bp.filter=(bw.filterMatrix||aG)+(bw.filterOpacity||aG)}bz.font&&(bp.font=bz.font);bz["font-family"]&&(bp.fontFamily='"'+bz["font-family"][F](",")[0][bb](/^['"]+|['"]+$/g,aG)+'"');bz["font-size"]&&(bp.fontSize=bz["font-size"]);bz["font-weight"]&&(bp.fontWeight=bz["font-weight"]);bz["font-style"]&&(bp.fontStyle=bz["font-style"]);if(bz.opacity!=null||bz["stroke-width"]!=null||bz.fill!=null||bz.stroke!=null||bz["stroke-width"]!=null||bz["stroke-opacity"]!=null||bz["fill-opacity"]!=null||bz["stroke-dasharray"]!=null||bz["stroke-miterlimit"]!=null||bz["stroke-linejoin"]!=null||bz["stroke-linecap"]!=null){bw=bs.shape||bw;var bx=(bw.getElementsByTagName(aS)&&bw.getElementsByTagName(aS)[0]),bB=false;!bx&&(bB=bx=aq(aS));if("fill-opacity" in bz||"opacity" in bz){var e=((+bA["fill-opacity"]+1||2)-1)*((+bA.opacity+1||2)-1)*((+aA.getRGB(bz.fill).o+1||2)-1);e<0&&(e=0);e>1&&(e=1);bx.opacity=e}bz.fill&&(bx.on=true);if(bx.on==null||bz.fill=="none"){bx.on=false}if(bx.on&&bz.fill){var i=bz.fill.match(c);if(i){bx.src=i[1];bx.type="tile"}else{bx.color=aA.getRGB(bz.fill).hex;bx.src=aG;bx.type="solid";if(aA.getRGB(bz.fill).error&&(bE.type in {circle:1,ellipse:1}||(bz.fill+aG).charAt()!="r")&&b(bE,bz.fill)){bA.fill="none";bA.gradient=bz.fill}}}bB&&bw[a5](bx);var R=(bw.getElementsByTagName("stroke")&&bw.getElementsByTagName("stroke")[0]),bC=false;!R&&(bC=R=aq("stroke"));if((bz.stroke&&bz.stroke!="none")||bz["stroke-width"]||bz["stroke-opacity"]!=null||bz["stroke-dasharray"]||bz["stroke-miterlimit"]||bz["stroke-linejoin"]||bz["stroke-linecap"]){R.on=true}(bz.stroke=="none"||R.on==null||bz.stroke==0||bz["stroke-width"]==0)&&(R.on=false);var bv=aA.getRGB(bz.stroke);R.on&&bz.stroke&&(R.color=bv.hex);e=((+bA["stroke-opacity"]+1||2)-1)*((+bA.opacity+1||2)-1)*((+bv.o+1||2)-1);var bt=(ae(bz["stroke-width"])||1)*0.75;e<0&&(e=0);e>1&&(e=1);bz["stroke-width"]==null&&(bt=bA["stroke-width"]);bz["stroke-width"]&&(R.weight=bt);bt&&bt<1&&(e*=bt)&&(R.weight=1);R.opacity=e;bz["stroke-linejoin"]&&(R.joinstyle=bz["stroke-linejoin"]||"miter");R.miterlimit=bz["stroke-miterlimit"]||8;bz["stroke-linecap"]&&(R.endcap=bz["stroke-linecap"]=="butt"?"flat":bz["stroke-linecap"]=="square"?"square":"round");if(bz["stroke-dasharray"]){var bu={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};R.dashstyle=bu[ab](bz["stroke-dasharray"])?bu[bz["stroke-dasharray"]]:aG}bC&&bw[a5](R)}if(bE.type=="text"){bp=bE.paper.span.style;bA.font&&(bp.font=bA.font);bA["font-family"]&&(bp.fontFamily=bA["font-family"]);bA["font-size"]&&(bp.fontSize=bA["font-size"]);bA["font-weight"]&&(bp.fontWeight=bA["font-weight"]);bA["font-style"]&&(bp.fontStyle=bA["font-style"]);bE.node.string&&(bE.paper.span.innerHTML=(bE.node.string+aG)[bb](/</g,"&#60;")[bb](/&/g,"&#38;")[bb](/\n/g,"<br>"));bE.W=bA.w=bE.paper.span.offsetWidth;bE.H=bA.h=bE.paper.span.offsetHeight;bE.X=bA.x;bE.Y=bA.y+Y(bE.H/2);switch(bA["text-anchor"]){case"start":bE.node.style["v-text-align"]="left";bE.bbx=Y(bE.W/2);break;case"end":bE.node.style["v-text-align"]="right";bE.bbx=-Y(bE.W/2);break;default:bE.node.style["v-text-align"]="center";break}}};b=function(d,bq){d.attrs=d.attrs||{};var br=d.attrs,bt,S="linear",bp=".5 .5";d.attrs.gradient=bq;bq=(bq+aG)[bb](aF,function(bv,bw,i){S="radial";if(bw&&i){bw=ae(bw);i=ae(i);a6(bw-0.5,2)+a6(i-0.5,2)>0.25&&(i=aj.sqrt(0.25-a6(bw-0.5,2))*((i>0.5)*2-1)+0.5);bp=bw+az+i}return aG});bq=bq[F](/\s*\-\s*/);if(S=="linear"){var e=bq.shift();e=-ae(e);if(isNaN(e)){return null}}var R=t(bq);if(!R){return null}d=d.shape||d.node;bt=d.getElementsByTagName(aS)[0]||aq(aS);!bt.parentNode&&d.appendChild(bt);if(R[o]){bt.on=true;bt.method="none";bt.color=R[0].color;bt.color2=R[R[o]-1].color;var bu=[];for(var E=0,bs=R[o];E<bs;E++){R[E].offset&&bu[f](R[E].offset+az+R[E].color)}bt.colors&&(bt.colors.value=bu[o]?bu[aN]():"0% "+bt.color);if(S=="radial"){bt.type="gradientradial";bt.focus="100%";bt.focussize=bp;bt.focusposition=bp}else{bt.type="gradient";bt.angle=(270-e)%360}}return 1};aL=function(R,bp,d){var S=0,i=0,e=0,E=1;this[0]=R;this.id=aA._oid++;this.node=R;R.raphael=this;this.X=0;this.Y=0;this.attrs={};this.Group=bp;this.paper=d;this._={tx:0,ty:0,rt:{deg:0},sx:1,sy:1};!d.bottom&&(d.bottom=this);this.prev=d.top;d.top&&(d.top.next=this);d.top=this;this.next=null};aL[bm].rotate=function(e,d,i){if(this.removed){return this}if(e==null){if(this._.rt.cx){return[this._.rt.deg,this._.rt.cx,this._.rt.cy][aN](az)}return this._.rt.deg }e=(e+aG)[F](a);if(e[o]-1){d=ae(e[1]);i=ae(e[2])}e=ae(e[0]);if(d!=null){this._.rt.deg=e}else{this._.rt.deg+=e}i==null&&(d=null);this._.rt.cx=d;this._.rt.cy=i;this.setBox(this.attrs,d,i);this.Group.style.rotation=this._.rt.deg;return this};aL[bm].setBox=function(R,S,E){if(this.removed){return this}var d=this.Group.style,bp=(this.shape&&this.shape.style)||this.node.style;R=R||{};for(var bq in R){if(R[ab](bq)){this.attrs[bq]=R[bq]}}S=S||this._.rt.cx;E=E||this._.rt.cy;var bt=this.attrs,bw,bv,bx,bs;switch(this.type){case"circle":bw=bt.cx-bt.r;bv=bt.cy-bt.r;bx=bs=bt.r*2;break;case"ellipse":bw=bt.cx-bt.rx;bv=bt.cy-bt.ry;bx=bt.rx*2;bs=bt.ry*2;break;case"image":bw=+bt.x;bv=+bt.y;bx=bt.width||0;bs=bt.height||0;break;case"text":this.textpath.v=["m",Y(bt.x),", ",Y(bt.y-2),"l",Y(bt.x)+1,", ",Y(bt.y-2)][aN](aG);bw=bt.x-Y(this.W/2);bv=bt.y-this.H/2;bx=this.W;bs=this.H;break;case"rect":case"path":if(!this.attrs.path){bw=0;bv=0;bx=this.paper.width;bs=this.paper.height}else{var br=ad(this.attrs.path);bw=br.x;bv=br.y;bx=br.width;bs=br.height}break;default:bw=0;bv=0;bx=this.paper.width;bs=this.paper.height;break}S=(S==null)?bw+bx/2:S;E=(E==null)?bv+bs/2:E;var e=S-this.paper.width/2,bu=E-this.paper.height/2,by;d.left!=(by=e+"px")&&(d.left=by);d.top!=(by=bu+"px")&&(d.top=by);this.X=p[ab](this.type)?-e:bw;this.Y=p[ab](this.type)?-bu:bv;this.W=bx;this.H=bs;if(p[ab](this.type)){bp.left!=(by=-e*r+"px")&&(bp.left=by);bp.top!=(by=-bu*r+"px")&&(bp.top=by)}else{if(this.type=="text"){bp.left!=(by=-e+"px")&&(bp.left=by);bp.top!=(by=-bu+"px")&&(bp.top=by)}else{d.width!=(by=this.paper.width+"px")&&(d.width=by);d.height!=(by=this.paper.height+"px")&&(d.height=by);bp.left!=(by=bw-e+"px")&&(bp.left=by);bp.top!=(by=bv-bu+"px")&&(bp.top=by);bp.width!=(by=bx+"px")&&(bp.width=by);bp.height!=(by=bs+"px")&&(bp.height=by)}}};aL[bm].hide=function(){!this.removed&&(this.Group.style.display="none");return this};aL[bm].show=function(){!this.removed&&(this.Group.style.display="block");return this};aL[bm].getBBox=function(){if(this.removed){return this}if(p[ab](this.type)){return ad(this.attrs.path)}return{x:this.X+(this.bbx||0),y:this.Y,width:this.W,height:this.H}};aL[bm].remove=function(){if(this.removed){return}aw(this,this.paper);this.node.parentNode.removeChild(this.node);this.Group.parentNode.removeChild(this.Group);this.shape&&this.shape.parentNode.removeChild(this.shape);for(var d in this){delete this[d]}this.removed=true};aL[bm].attr=function(e,bp){if(this.removed){return this}if(e==null){var R={};for(var E in this.attrs){if(this.attrs[ab](E)){R[E]=this.attrs[E]}}this._.rt.deg&&(R.rotation=this.rotate());(this._.sx!=1||this._.sy!=1)&&(R.scale=this.scale());R.gradient&&R.fill=="none"&&(R.fill=R.gradient)&&delete R.gradient;return R}if(bp==null&&aA.is(e,aa)){if(e=="translation"){return x.call(this)}if(e=="rotation"){return this.rotate()}if(e=="scale"){return this.scale()}if(e==aS&&this.attrs.fill=="none"&&this.attrs.gradient){return this.attrs.gradient}return this.attrs[e]}if(this.attrs&&bp==null&&aA.is(e,aV)){var S,d={};for(E=0,S=e[o];E<S;E++){d[e[E]]=this.attr(e[E])}return d}var bq;if(bp!=null){bq={};bq[e]=bp}bp==null&&aA.is(e,"object")&&(bq=e);if(bq){if(bq.text&&this.type=="text"){this.node.string=bq.text}ai(this,bq);if(bq.gradient&&(({circle:1,ellipse:1})[ab](this.type)||(bq.gradient+aG).charAt()!="r")){b(this,bq.gradient)}(!p[ab](this.type)||this._.rt.deg)&&this.setBox(this.attrs)}return this};aL[bm].toFront=function(){!this.removed&&this.Group.parentNode[a5](this.Group);this.paper.top!=this&&ag(this,this.paper);return this};aL[bm].toBack=function(){if(this.removed){return this}if(this.Group.parentNode.firstChild!=this.Group){this.Group.parentNode.insertBefore(this.Group,this.Group.parentNode.firstChild);m(this,this.paper)}return this};aL[bm].insertAfter=function(d){if(this.removed){return this}if(d.Group.nextSibling){d.Group.parentNode.insertBefore(this.Group,d.Group.nextSibling)}else{d.Group.parentNode[a5](this.Group)}G(this,d,this.paper);return this};aL[bm].insertBefore=function(d){if(this.removed){return this}d.Group.parentNode.insertBefore(this.Group,d.Group);aD(this,d,this.paper);return this};var bg=/ progid:\S+Blur\([^\)]+\)/g;aL[bm].blur=function(d){var e=this.node.style,i=e.filter;i=i.replace(bg,"");if(+d!==0){this.attrs.blur=d;e.filter=i+aT+".Blur(pixelradius="+(+d||1.5)+")";e.margin=Raphael.format("-{0}px 0 0 -{0}px",Math.round(+d||1.5))}else{e.filter=i;e.margin=0;delete this.attrs.blur}};Z=function(e,d,bq,S){var R=aq("group"),bp=aq("oval"),i=bp.style;R.style.cssText="position:absolute;left:0;top:0;width:"+e.width+"px;height:"+e.height+"px";R.coordsize=aO;R.coordorigin=e.coordorigin;R[a5](bp);var E=new aL(bp,R,e);E.type="circle";ai(E,{stroke:"#000",fill:"none"});E.attrs.cx=d;E.attrs.cy=bq;E.attrs.r=S;E.setBox({x:d-S,y:bq-S,width:S*2,height:S*2});e.canvas[a5](R);return E};function al(d,R,e,i,E){if(E){return aA.format("M{0},{1}l{2},0a{3},{3},0,0,1,{3},{3}l0,{5}a{3},{3},0,0,1,{4},{3}l{6},0a{3},{3},0,0,1,{4},{4}l0,{7}a{3},{3},0,0,1,{3},{4}z",d+E,R,e-E*2,E,-E,i-E*2,E*2-e,E*2-i)}else{return aA.format("M{0},{1}l{2},0,0,{3},{4},0z",d,R,e,i,-e)}}aY=function(e,bp,R,bq,i,d){var br=al(bp,R,bq,i,d),E=e.path(br),S=E.attrs;E.X=S.x=bp;E.Y=S.y=R;E.W=S.width=bq;E.H=S.height=i;S.r=d;S.path=br;E.type="rect";return E};ar=function(d,br,bq,i,e){var R=aq("group"),E=aq("oval"),bp=E.style;R.style.cssText="position:absolute;left:0;top:0;width:"+d.width+"px;height:"+d.height+"px";R.coordsize=aO;R.coordorigin=d.coordorigin;R[a5](E);var S=new aL(E,R,d);S.type="ellipse";ai(S,{stroke:"#000"});S.attrs.cx=br;S.attrs.cy=bq;S.attrs.rx=i;S.attrs.ry=e;S.setBox({x:br-i,y:bq-e,width:i*2,height:e*2});d.canvas[a5](R);return S};s=function(e,d,br,bq,bs,E){var R=aq("group"),i=aq("image"),bp=i.style;R.style.cssText="position:absolute;left:0;top:0;width:"+e.width+"px;height:"+e.height+"px";R.coordsize=aO;R.coordorigin=e.coordorigin;i.src=d;R[a5](i);var S=new aL(i,R,e);S.type="image";S.attrs.src=d;S.attrs.x=br;S.attrs.y=bq;S.attrs.w=bs;S.attrs.h=E;S.setBox({x:br,y:bq,width:bs,height:E});e.canvas[a5](R);return S};af=function(e,br,bq,bs){var R=aq("group"),E=aq("shape"),bp=E.style,bt=aq("path"),d=bt.style,i=aq("textpath");R.style.cssText="position:absolute;left:0;top:0;width:"+e.width+"px;height:"+e.height+"px";R.coordsize=aO;R.coordorigin=e.coordorigin;bt.v=aA.format("m{0},{1}l{2},{1}",Y(br*10),Y(bq*10),Y(br*10)+1);bt.textpathok=true;bp.width=e.width;bp.height=e.height;i.string=bs+aG;i.on=true;E[a5](i);E[a5](bt);R[a5](E);var S=new aL(i,R,e);S.shape=E;S.textpath=bt;S.type="text";S.attrs.text=bs;S.attrs.x=br;S.attrs.y=bq;S.attrs.w=1;S.attrs.h=1;ai(S,{font:l.font,stroke:"none",fill:"#000"});S.setBox();e.canvas[a5](R);return S};bj=function(i,d){var e=this.canvas.style;i==+i&&(i+="px");d==+d&&(d+="px");e.width=i;e.height=d;e.clip="rect(0 "+i+" "+d+" 0)";return this};var aq;V.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!V.namespaces.rvml&&V.namespaces.add("rvml","urn:schemas-microsoft-com:vml");aq=function(d){return V.createElement("<rvml:"+d+' class="rvml">') }}catch(ao){aq=function(d){return V.createElement("<"+d+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}B=function(){var i=aB[bk](0,arguments),d=i.container,br=i.height,bs,e=i.width,bq=i.x,bp=i.y;if(!d){throw new Error("VML container not found.")}var R=new bh,S=R.canvas=V.createElement("div"),E=S.style;bq=bq||0;bp=bp||0;e=e||512;br=br||342;e==+e&&(e+="px");br==+br&&(br+="px");R.width=1000;R.height=1000;R.coordsize=r*1000+az+r*1000;R.coordorigin="0 0";R.span=V.createElement("span");R.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";S[a5](R.span);E.cssText=aA.format("width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",e,br);if(d==1){V.body[a5](S);E.left=bq+"px";E.top=bp+"px";E.position="absolute"}else{if(d.firstChild){d.insertBefore(S,d.firstChild)}else{d[a5](S)}}a0.call(R,R,aA.fn);return R};bh[bm].clear=function(){this.canvas.innerHTML=aG;this.span=V.createElement("span");this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";this.canvas[a5](this.span);this.bottom=this.top=null};bh[bm].remove=function(){this.canvas.parentNode.removeChild(this.canvas);for(var d in this){this[d]=w(d)}return true}}if((/^Apple|^Google/).test(aH.navigator.vendor)&&(!(aH.navigator.userAgent.indexOf("Version/4.0")+1)||aH.navigator.platform.slice(0,2)=="iP")){bh[bm].safari=function(){var d=this.rect(-99,-99,this.width+99,this.height+99);aH.setTimeout(function(){d.remove()})}}else{bh[bm].safari=function(){}}var K=function(){this.returnValue=false},be=function(){return this.originalEvent.preventDefault()},aR=function(){this.cancelBubble=true},av=function(){return this.originalEvent.stopPropagation()},an=(function(){if(V.addEventListener){return function(S,E,i,e){var d=P&&ba[E]?ba[E]:E;var R=function(bs){if(P&&ba[ab](E)){for(var bq=0,br=bs.targetTouches&&bs.targetTouches.length;bq<br;bq++){if(bs.targetTouches[bq].target==S){var bp=bs;bs=bs.targetTouches[bq];bs.originalEvent=bp;bs.preventDefault=be;bs.stopPropagation=av;break}}}return i.call(e,bs)};S.addEventListener(d,R,false);return function(){S.removeEventListener(d,R,false);return true}}}else{if(V.attachEvent){return function(S,E,i,e){var R=function(bp){bp=bp||aH.event;bp.preventDefault=bp.preventDefault||K;bp.stopPropagation=bp.stopPropagation||aR;return i.call(e,bp)};S.attachEvent("on"+E,R);var d=function(){S.detachEvent("on"+E,R);return true};return d}}}})();for(var ak=M[o];ak--;){(function(d){aA[d]=aL[bm][d]=function(e){if(aA.is(e,"function")){this.events=this.events||[];this.events.push({name:d,f:e,unbind:an(this.shape||this.node||V,d,e,this)})}return this};aA["un"+d]=aL[bm]["un"+d]=function(E){var i=this.events,e=i[o];while(e--){if(i[e].name==d&&i[e].f==E){i[e].unbind();i.splice(e,1);!i.length&&delete this.events;return this}}return this}})(M[ak])}aL[bm].hover=function(e,d){return this.mouseover(e).mouseout(d)};aL[bm].unhover=function(e,d){return this.unmouseover(e).unmouseout(d)};aL[bm].drag=function(i,S,R){this._drag={};var E=this.mousedown(function(bp){(bp.originalEvent?bp.originalEvent:bp).preventDefault();this._drag.x=bp.clientX;this._drag.y=bp.clientY;this._drag.id=bp.identifier;S&&S.call(this,bp.clientX,bp.clientY);Raphael.mousemove(e).mouseup(d)}),e=function(br){var bp=br.clientX,bt=br.clientY;if(P){var bq=br.touches.length,bs;while(bq--){bs=br.touches[bq];if(bs.identifier==E._drag.id){bp=bs.clientX;bt=bs.clientY;(br.originalEvent?br.originalEvent:br).preventDefault();break}}}else{br.preventDefault()}i&&i.call(E,bp-E._drag.x,bt-E._drag.y,bp,bt)},d=function(){E._drag={};Raphael.unmousemove(e).unmouseup(d);R&&R.call(E)};return this};bh[bm].circle=function(d,i,e){return Z(this,d||0,i||0,e||0)};bh[bm].rect=function(d,R,e,i,E){return aY(this,d||0,R||0,e||0,i||0,E||0)};bh[bm].ellipse=function(d,E,i,e){return ar(this,d||0,E||0,i||0,e||0)};bh[bm].path=function(d){d&&!aA.is(d,aa)&&!aA.is(d[0],aV)&&(d+=aG);return u(aA.format[bk](aA,arguments),this)};bh[bm].image=function(E,d,R,e,i){return s(this,E||"about:blank",d||0,R||0,e||0,i||0)};bh[bm].text=function(d,i,e){return af(this,d||0,i||0,e||aG)};bh[bm].set=function(d){arguments[o]>1&&(d=Array[bm].splice.call(arguments,0,arguments[o]));return new ac(d)};bh[bm].setSize=bj;bh[bm].top=bh[bm].bottom=null;bh[bm].raphael=aA;function z(){return this.x+az+this.y}aL[bm].resetScale=function(){if(this.removed){return this}this._.sx=1;this._.sy=1;this.attrs.scale="1 1"};aL[bm].scale=function(bv,bu,E,e){if(this.removed){return this}if(bv==null&&bu==null){return{x:this._.sx,y:this._.sy,toString:z}}bu=bu||bv;!+bu&&(bu=bv);var bz,bx,by,bw,bL=this.attrs;if(bv!=0){var bt=this.getBBox(),bq=bt.x+bt.width/2,R=bt.y+bt.height/2,bK=bv/this._.sx,bJ=bu/this._.sy;E=(+E||E==0)?E:bq;e=(+e||e==0)?e:R;var bs=~~(bv/aj.abs(bv)),bp=~~(bu/aj.abs(bu)),bC=this.node.style,bN=E+(bq-E)*bK,bM=e+(R-e)*bJ;switch(this.type){case"rect":case"image":var br=bL.width*bs*bK,bB=bL.height*bp*bJ;this.attr({height:bB,r:bL.r*a3(bs*bK,bp*bJ),width:br,x:bN-br/2,y:bM-bB/2});break;case"circle":case"ellipse":this.attr({rx:bL.rx*bs*bK,ry:bL.ry*bp*bJ,r:bL.r*a3(bs*bK,bp*bJ),cx:bN,cy:bM});break;case"text":this.attr({x:bN,y:bM});break;case"path":var bE=am(bL.path),bF=true;for(var bH=0,bA=bE[o];bH<bA;bH++){var bD=bE[bH],S=a8.call(bD[0]);if(S=="M"&&bF){continue}else{bF=false}if(S=="A"){bD[bE[bH][o]-2]*=bK;bD[bE[bH][o]-1]*=bJ;bD[1]*=bs*bK;bD[2]*=bp*bJ;bD[5]=+!(bs+bp?!+bD[5]:+bD[5])}else{if(S=="H"){for(var bG=1,bI=bD[o];bG<bI;bG++){bD[bG]*=bK}}else{if(S=="V"){for(bG=1,bI=bD[o];bG<bI;bG++){bD[bG]*=bJ}}else{for(bG=1,bI=bD[o];bG<bI;bG++){bD[bG]*=(bG%2)?bK:bJ}}}}}var d=ad(bE);bz=bN-d.x-d.width/2;bx=bM-d.y-d.height/2;bE[0][1]+=bz;bE[0][2]+=bx;this.attr({path:bE});break}if(this.type in {text:1,image:1}&&(bs!=1||bp!=1)){if(this.transformations){this.transformations[2]="scale("[bf](bs,",",bp,")");this.node[A]("transform",this.transformations[aN](az));bz=(bs==-1)?-bL.x-(br||0):bL.x;bx=(bp==-1)?-bL.y-(bB||0):bL.y;this.attr({x:bz,y:bx});bL.fx=bs-1;bL.fy=bp-1}else{this.node.filterMatrix=aT+".Matrix(M11="[bf](bs,", M12=0, M21=0, M22=",bp,", Dx=0, Dy=0, sizingmethod='auto expand', filtertype='bilinear')");bC.filter=(this.node.filterMatrix||aG)+(this.node.filterOpacity||aG)}}else{if(this.transformations){this.transformations[2]=aG;this.node[A]("transform",this.transformations[aN](az));bL.fx=0;bL.fy=0}else{this.node.filterMatrix=aG;bC.filter=(this.node.filterMatrix||aG)+(this.node.filterOpacity||aG)}}bL.scale=[bv,bu,E,e][aN](az);this._.sx=bv;this._.sy=bu}return this};aL[bm].clone=function(){if(this.removed){return null}var d=this.attr();delete d.scale;delete d.translation;return this.paper[this.type]().attr(d)};var g=at(function(E,d,bq,bp,bw,bv,bu,bt,R){var bs=0,S;for(var br=0;br<1.001;br+=0.001){var e=aA.findDotsAtSegment(E,d,bq,bp,bw,bv,bu,bt,br);br&&(bs+=a6(a6(S.x-e.x,2)+a6(S.y-e.y,2),0.5));if(bs>=R){return e}S=e}}),aQ=function(d,e){return function(by,S,bp){by=O(by);var bu,bt,E,bq,R="",bx={},bv,bs=0; for(var br=0,bw=by.length;br<bw;br++){E=by[br];if(E[0]=="M"){bu=+E[1];bt=+E[2]}else{bq=q(bu,bt,E[1],E[2],E[3],E[4],E[5],E[6]);if(bs+bq>S){if(e&&!bx.start){bv=g(bu,bt,E[1],E[2],E[3],E[4],E[5],E[6],S-bs);R+=["C",bv.start.x,bv.start.y,bv.m.x,bv.m.y,bv.x,bv.y];if(bp){return R}bx.start=R;R=["M",bv.x,bv.y+"C",bv.n.x,bv.n.y,bv.end.x,bv.end.y,E[5],E[6]][aN]();bs+=bq;bu=+E[5];bt=+E[6];continue}if(!d&&!e){bv=g(bu,bt,E[1],E[2],E[3],E[4],E[5],E[6],S-bs);return{x:bv.x,y:bv.y,alpha:bv.alpha}}}bs+=bq;bu=+E[5];bt=+E[6]}R+=E}bx.end=R;bv=d?bs:e?bx:aA.findDotsAtSegment(bu,bt,E[1],E[2],E[3],E[4],E[5],E[6],1);bv.alpha&&(bv={x:bv.x,y:bv.y,alpha:bv.alpha});return bv}},q=at(function(E,d,bp,S,bv,bu,bt,bs){var R={x:0,y:0},br=0;for(var bq=0;bq<1.01;bq+=0.01){var e=X(E,d,bp,S,bv,bu,bt,bs,bq);bq&&(br+=a6(a6(R.x-e.x,2)+a6(R.y-e.y,2),0.5));R=e}return br});var aC=aQ(1),I=aQ(),T=aQ(0,1);aL[bm].getTotalLength=function(){if(this.type!="path"){return}if(this.node.getTotalLength){return this.node.getTotalLength()}return aC(this.attrs.path)};aL[bm].getPointAtLength=function(d){if(this.type!="path"){return}return I(this.attrs.path,d)};aL[bm].getSubpath=function(i,e){if(this.type!="path"){return}if(aj.abs(this.getTotalLength()-e)<0.000001){return T(this.attrs.path,i).end}var d=T(this.attrs.path,e,1);return i?T(d,i).end:d};aA.easing_formulas={linear:function(d){return d},"<":function(d){return a6(d,3)},">":function(d){return a6(d-1,3)+1},"<>":function(d){d=d*2;if(d<1){return a6(d,3)/2}d-=2;return(a6(d,3)+2)/2},backIn:function(e){var d=1.70158;return e*e*((d+1)*e-d)},backOut:function(e){e=e-1;var d=1.70158;return e*e*((d+1)*e+d)+1},elastic:function(i){if(i==0||i==1){return i}var e=0.3,d=e/4;return a6(2,-10*i)*aj.sin((i-d)*(2*aj.PI)/e)+1},bounce:function(E){var e=7.5625,i=2.75,d;if(E<(1/i)){d=e*E*E}else{if(E<(2/i)){E-=(1.5/i);d=e*E*E+0.75}else{if(E<(2.5/i)){E-=(2.25/i);d=e*E*E+0.9375}else{E-=(2.625/i);d=e*E*E+0.984375}}}return d}};var Q={length:0},bd=function(){var br=+new Date;for(var bD in Q){if(bD!="length"&&Q[ab](bD)){var bI=Q[bD];if(bI.stop||bI.el.removed){delete Q[bD];Q[o]--;continue}var bp=br-bI.start,bA=bI.ms,bz=bI.easing,bE=bI.from,bw=bI.diff,E=bI.to,bv=bI.t,by=bI.prev||0,bq=bI.el,R=bI.callback,bx={},d;if(bp<bA){var S=aA.easing_formulas[bz]?aA.easing_formulas[bz](bp/bA):bp/bA;for(var bB in bE){if(bE[ab](bB)){switch(ah[bB]){case"along":d=S*bA*bw[bB];E.back&&(d=E.len-d);var bC=I(E[bB],d);bq.translate(bw.sx-bw.x||0,bw.sy-bw.y||0);bw.x=bC.x;bw.y=bC.y;bq.translate(bC.x-bw.sx,bC.y-bw.sy);E.rot&&bq.rotate(bw.r+bC.alpha,bC.x,bC.y);break;case ax:d=+bE[bB]+S*bA*bw[bB];break;case"colour":d="rgb("+[H(Y(bE[bB].r+S*bA*bw[bB].r)),H(Y(bE[bB].g+S*bA*bw[bB].g)),H(Y(bE[bB].b+S*bA*bw[bB].b))][aN](",")+")";break;case"path":d=[];for(var bG=0,bu=bE[bB][o];bG<bu;bG++){d[bG]=[bE[bB][bG][0]];for(var bF=1,bH=bE[bB][bG][o];bF<bH;bF++){d[bG][bF]=+bE[bB][bG][bF]+S*bA*bw[bB][bG][bF]}d[bG]=d[bG][aN](az)}d=d[aN](az);break;case"csv":switch(bB){case"translation":var bt=bw[bB][0]*(bp-by),bs=bw[bB][1]*(bp-by);bv.x+=bt;bv.y+=bs;d=bt+az+bs;break;case"rotation":d=+bE[bB][0]+S*bA*bw[bB][0];bE[bB][1]&&(d+=","+bE[bB][1]+","+bE[bB][2]);break;case"scale":d=[+bE[bB][0]+S*bA*bw[bB][0],+bE[bB][1]+S*bA*bw[bB][1],(2 in E[bB]?E[bB][2]:aG),(3 in E[bB]?E[bB][3]:aG)][aN](az);break;case"clip-rect":d=[];bG=4;while(bG--){d[bG]=+bE[bB][bG]+S*bA*bw[bB][bG]}break}break}bx[bB]=d}}bq.attr(bx);bq._run&&bq._run.call(bq)}else{if(E.along){bC=I(E.along,E.len*!E.back);bq.translate(bw.sx-(bw.x||0)+bC.x-bw.sx,bw.sy-(bw.y||0)+bC.y-bw.sy);E.rot&&bq.rotate(bw.r+bC.alpha,bC.x,bC.y)}(bv.x||bv.y)&&bq.translate(-bv.x,-bv.y);E.scale&&(E.scale+=aG);bq.attr(E);delete Q[bD];Q[o]--;bq.in_animation=null;aA.is(R,"function")&&R.call(bq)}bI.prev=bp}}aA.svg&&bq&&bq.paper&&bq.paper.safari();Q[o]&&aH.setTimeout(bd)},H=function(d){return h(a3(d,255),0)},x=function(d,i){if(d==null){return{x:this._.tx,y:this._.ty,toString:z}}this._.tx+=+d;this._.ty+=+i;switch(this.type){case"circle":case"ellipse":this.attr({cx:+d+this.attrs.cx,cy:+i+this.attrs.cy});break;case"rect":case"image":case"text":this.attr({x:+d+this.attrs.x,y:+i+this.attrs.y});break;case"path":var e=am(this.attrs.path);e[0][1]+=+d;e[0][2]+=+i;this.attr({path:e});break}return this};aL[bm].animateWith=function(e,i,d,R,E){Q[e.id]&&(i.start=Q[e.id].start);return this.animate(i,d,R,E)};aL[bm].animateAlong=aM();aL[bm].animateAlongBack=aM(1);function aM(d){return function(E,i,e,S){var R={back:d};aA.is(e,"function")?(S=e):(R.rot=e);E&&E.constructor==aL&&(E=E.attrs.path);E&&(R.along=E);return this.animate(R,i,S)}}aL[bm].onAnimation=function(d){this._run=d||0;return this};aL[bm].animate=function(bD,bu,bt,E){if(aA.is(bt,"function")||!bt){E=bt||null}var by={},e={},br={};for(var bv in bD){if(bD[ab](bv)){if(ah[ab](bv)){by[bv]=this.attr(bv);(by[bv]==null)&&(by[bv]=l[bv]);e[bv]=bD[bv];switch(ah[bv]){case"along":var bB=aC(bD[bv]),bw=I(bD[bv],bB*!!bD.back),R=this.getBBox();br[bv]=bB/bu;br.tx=R.x;br.ty=R.y;br.sx=bw.x;br.sy=bw.y;e.rot=bD.rot;e.back=bD.back;e.len=bB;bD.rot&&(br.r=ae(this.rotate())||0);break;case ax:br[bv]=(e[bv]-by[bv])/bu;break;case"colour":by[bv]=aA.getRGB(by[bv]);var bx=aA.getRGB(e[bv]);br[bv]={r:(bx.r-by[bv].r)/bu,g:(bx.g-by[bv].g)/bu,b:(bx.b-by[bv].b)/bu};break;case"path":var S=O(by[bv],e[bv]);by[bv]=S[0];var bs=S[1];br[bv]=[];for(var bA=0,bq=by[bv][o];bA<bq;bA++){br[bv][bA]=[0];for(var bz=1,bC=by[bv][bA][o];bz<bC;bz++){br[bv][bA][bz]=(bs[bA][bz]-by[bv][bA][bz])/bu}}break;case"csv":var d=(bD[bv]+aG)[F](a),bp=(by[bv]+aG)[F](a);switch(bv){case"translation":by[bv]=[0,0];br[bv]=[d[0]/bu,d[1]/bu];break;case"rotation":by[bv]=(bp[1]==d[1]&&bp[2]==d[2])?bp:[0,d[1],d[2]];br[bv]=[(d[0]-by[bv][0])/bu,0,0];break;case"scale":bD[bv]=d;by[bv]=(by[bv]+aG)[F](a);br[bv]=[(d[0]-by[bv][0])/bu,(d[1]-by[bv][1])/bu,0,0];break;case"clip-rect":by[bv]=(by[bv]+aG)[F](a);br[bv]=[];bA=4;while(bA--){br[bv][bA]=(d[bA]-by[bv][bA])/bu}break}e[bv]=d}}}}this.stop();this.in_animation=1;Q[this.id]={start:bD.start||+new Date,ms:bu,easing:bt,from:by,diff:br,to:e,el:this,callback:E,t:{x:0,y:0}};++Q[o]==1&&bd();return this};aL[bm].stop=function(){Q[this.id]&&Q[o]--;delete Q[this.id];return this};aL[bm].translate=function(d,e){return this.attr({translation:d+" "+e})};aL[bm][aP]=function(){return"Rapha\xebl\u2019s object"};aA.ae=Q;var ac=function(d){this.items=[];this[o]=0;this.type="set";if(d){for(var e=0,E=d[o];e<E;e++){if(d[e]&&(d[e].constructor==aL||d[e].constructor==ac)){this[this.items[o]]=this.items[this.items[o]]=d[e];this[o]++}}}};ac[bm][f]=function(){var R,d;for(var e=0,E=arguments[o];e<E;e++){R=arguments[e];if(R&&(R.constructor==aL||R.constructor==ac)){d=this.items[o];this[d]=this.items[d]=R;this[o]++}}return this};ac[bm].pop=function(){delete this[this[o]--];return this.items.pop()};for(var D in aL[bm]){if(aL[bm][ab](D)){ac[bm][D]=(function(d){return function(){for(var e=0,E=this.items[o];e<E;e++){this.items[e][d][bk](this.items[e],arguments)}return this}})(D)}}ac[bm].attr=function(e,bp){if(e&&aA.is(e,aV)&&aA.is(e[0],"object")){for(var d=0,S=e[o];d<S;d++){this.items[d].attr(e[d]) }}else{for(var E=0,R=this.items[o];E<R;E++){this.items[E].attr(e,bp)}}return this};ac[bm].animate=function(e,d,bp,br){(aA.is(bp,"function")||!bp)&&(br=bp||null);var S=this.items[o],E=S,bs,bq=this,R;br&&(R=function(){!--S&&br.call(bq)});bp=aA.is(bp,aa)?bp:R;bs=this.items[--E].animate(e,d,bp,R);while(E--){this.items[E].animateWith(bs,e,d,bp,R)}return this};ac[bm].insertAfter=function(e){var d=this.items[o];while(d--){this.items[d].insertAfter(e)}return this};ac[bm].getBBox=function(){var d=[],bp=[],e=[],R=[];for(var E=this.items[o];E--;){var S=this.items[E].getBBox();d[f](S.x);bp[f](S.y);e[f](S.x+S.width);R[f](S.y+S.height)}d=a3[bk](0,d);bp=a3[bk](0,bp);return{x:d,y:bp,width:h[bk](0,e)-d,height:h[bk](0,R)-bp}};ac[bm].clone=function(E){E=new ac;for(var d=0,e=this.items[o];d<e;d++){E[f](this.items[d].clone())}return E};aA.registerFont=function(e){if(!e.face){return e}this.fonts=this.fonts||{};var E={w:e.w,face:{},glyphs:{}},i=e.face["font-family"];for(var bp in e.face){if(e.face[ab](bp)){E.face[bp]=e.face[bp]}}if(this.fonts[i]){this.fonts[i][f](E)}else{this.fonts[i]=[E]}if(!e.svg){E.face["units-per-em"]=N(e.face["units-per-em"],10);for(var R in e.glyphs){if(e.glyphs[ab](R)){var S=e.glyphs[R];E.glyphs[R]={w:S.w,k:{},d:S.d&&"M"+S.d[bb](/[mlcxtrv]/g,function(bq){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[bq]||"M"})+"z"};if(S.k){for(var d in S.k){if(S[ab](d)){E.glyphs[R].k[d]=S.k[d]}}}}}}return e};bh[bm].getFont=function(br,bs,e,R){R=R||"normal";e=e||"normal";bs=+bs||{normal:400,bold:700,lighter:300,bolder:800}[bs]||400;if(!aA.fonts){return}var S=aA.fonts[br];if(!S){var E=new RegExp("(^|\\s)"+br[bb](/[^\w\d\s+!~.:_-]/g,aG)+"(\\s|$)","i");for(var d in aA.fonts){if(aA.fonts[ab](d)){if(E.test(d)){S=aA.fonts[d];break}}}}var bp;if(S){for(var bq=0,bt=S[o];bq<bt;bq++){bp=S[bq];if(bp.face["font-weight"]==bs&&(bp.face["font-style"]==e||!bp.face["font-style"])&&bp.face["font-stretch"]==R){break}}}return bp};bh[bm].print=function(R,E,d,bq,br,bA){bA=bA||"middle";var bw=this.set(),bz=(d+aG)[F](aG),bx=0,bt=aG,bB;aA.is(bq,d)&&(bq=this.getFont(bq));if(bq){bB=(br||16)/bq.face["units-per-em"];var e=bq.face.bbox.split(a),bp=+e[0],bs=+e[1]+(bA=="baseline"?e[3]-e[1]+(+bq.face.descent):(e[3]-e[1])/2);for(var bv=0,S=bz[o];bv<S;bv++){var bu=bv&&bq.glyphs[bz[bv-1]]||{},by=bq.glyphs[bz[bv]];bx+=bv?(bu.w||bq.w)+(bu.k&&bu.k[bz[bv]]||0):0;by&&by.d&&bw[f](this.path(by.d).attr({fill:"#000",stroke:"none",translation:[bx,0]}))}bw.scale(bB,bB,bp,bs).translate(R-bp,E-bs)}return bw};var a7=/\{(\d+)\}/g;aA.format=function(e,i){var d=aA.is(i,aV)?[0][bf](i):arguments;e&&aA.is(e,aa)&&d[o]-1&&(e=e[bb](a7,function(R,E){return d[++E]==null?aG:d[E]}));return e||aG};aA.ninja=function(){n.was?(Raphael=n.is):delete Raphael;return aA};aA.el=aL[bm];return aA})();if(!window.ABCJS){window.ABCJS={}}(function(){ABCJS.numberOfTunes=function(d){var b=d.split("\nX:");var c=b.length;if(c===0){c=1}return c};ABCJS.TuneBook=function(d){var h=this;var g="";d=window.ABCJS.parse.strip(d);var b=d.split("\nX:");for(var f=1;f<b.length;f++){b[f]="X:"+b[f]}var j=0;h.tunes=[];window.ABCJS.parse.each(b,function(i){h.tunes.push({abc:i,startPos:j});j+=i.length});if(h.tunes.length>1&&!window.ABCJS.parse.startsWith(h.tunes[0].abc,"X:")){var c=h.tunes.shift();var e=c.abc.split("\n");window.ABCJS.parse.each(e,function(i){if(window.ABCJS.parse.startsWith(i,"%%")){g+=i+"\n"}})}h.header=g;window.ABCJS.parse.each(h.tunes,function(k){var i=k.abc.indexOf("\n\n");if(i>0){k.abc=k.abc.substring(0,i)}k.pure=k.abc;k.abc=g+k.abc;var l=k.pure.split("T:");l=l[1].split("\n");k.title=l[0].replace(/^\s+|\s+$/g,"");var m=k.pure.substring(2,k.pure.indexOf("\n"));k.id=m.replace(/^\s+|\s+$/g,"")})};ABCJS.TuneBook.prototype.getTuneById=function(c){for(var b=0;b<this.tunes.length;b++){if(this.tunes[b].id===c){return this.tunes[b]}}return null};ABCJS.TuneBook.prototype.getTuneByTitle=function(c){for(var b=0;b<this.tunes.length;b++){if(this.tunes[b].title===c){return this.tunes[b]}}return null};function a(n,e,m,l,d){var k=function(i){return i&&!(i.propertyIsEnumerable("length"))&&typeof i==="object"&&typeof i.length==="number"};if(e===undefined||m===undefined){return}if(!k(e)){e=[e]}if(l===undefined){l={}}if(d===undefined){d={}}var g=d.startingTune?d.startingTune:0;var f=new ABCJS.TuneBook(m);var c=new window.ABCJS.parse.Parse();for(var h=0;h<e.length;h++){var b=e[h];if(typeof(b)==="string"){b=document.getElementById(b)}if(b){b.innerHTML="";if(g<f.tunes.length){c.parse(f.tunes[g].abc,l);var j=c.getTune();n(b,j)}}g++}}ABCJS.renderAbc=function(c,e,b,d,f){function g(l,j){var h=f?f.width?f.width:800:800;var k=Raphael(l,h,400);if(d===undefined){d={}}var i=new ABCJS.write.Printer(k,d);i.printABC(j)}a(g,c,e,b,f)};ABCJS.renderMidi=function(c,d,b,f,e){function g(j,h){if(f===undefined){f={}}var i=new ABCJS.midi.MidiWriter(j,f);i.writeABC(h)}a(g,c,d,b,e)}})();if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.data){window.ABCJS.data={}}window.ABCJS.data.Tune=function(){this.reset=function(){this.version="1.0.1";this.media="screen";this.metaText={};this.formatting={};this.lines=[];this.staffNum=0;this.voiceNum=0;this.lineNum=0};this.cleanUp=function(f,p,y,q){this.closeLine();var b=false;var x,o,k;for(x=0;x<this.lines.length;x++){if(this.lines[x].staff!==undefined){var m=false;for(o=0;o<this.lines[x].staff.length;o++){if(this.lines[x].staff[o]===undefined){b=true;this.lines[x].staff[o]=null}else{for(k=0;k<this.lines[x].staff[o].voices.length;k++){if(this.lines[x].staff[o].voices[k]===undefined){this.lines[x].staff[o].voices[k]=[]}else{if(this.containsNotes(this.lines[x].staff[o].voices[k])){m=true}}}}}if(!m){this.lines[x]=null;b=true}}}if(b){this.lines=window.ABCJS.parse.compact(this.lines);window.ABCJS.parse.each(this.lines,function(i){if(i.staff){i.staff=window.ABCJS.parse.compact(i.staff)}})}if(y){for(x=0;x<this.lines.length;x++){if(this.lines[x].staff!==undefined){for(o=0;o<this.lines[x].staff.length;o++){for(k=0;k<this.lines[x].staff[o].voices.length;k++){var d=0;for(var t=0;t<this.lines[x].staff[o].voices[k].length;t++){if(this.lines[x].staff[o].voices[k][t].el_type==="bar"){d++;if(d>=y){if(t<this.lines[x].staff[o].voices[k].length-1){if(x===this.lines.length-1){var g=JSON.parse(JSON.stringify(this.lines[x]));this.lines.push(window.ABCJS.parse.clone(g));for(var u=0;u<this.lines[x+1].staff.length;u++){for(var r=0;r<this.lines[x+1].staff[u].voices.length;r++){this.lines[x+1].staff[u].voices[r]=[]}}}var a=t+1;var h=this.lines[x].staff[o].voices[k].slice(a);this.lines[x].staff[o].voices[k]=this.lines[x].staff[o].voices[k].slice(0,a);this.lines[x+1].staff[o].voices[k]=h.concat(this.lines[x+1].staff[o].voices[k])}}}}}}}}}if(y){b=false;for(x=0;x<this.lines.length;x++){if(this.lines[x].staff!==undefined){for(o=0;o<this.lines[x].staff.length;o++){var c=false;for(k=0;k<this.lines[x].staff[o].voices.length;k++){if(this.containsNotesStrict(this.lines[x].staff[o].voices[k])){c=true}}if(!c){b=true;this.lines[x].staff[o]=null}}}}if(b){window.ABCJS.parse.each(this.lines,function(i){if(i.staff){i.staff=window.ABCJS.parse.compact(i.staff) }})}}for(x=0;x<this.lines.length;x++){if(this.lines[x].staff){for(o=0;o<this.lines[x].staff.length;o++){delete this.lines[x].staff[o].workingClef}}}function l(K){var J=[];var H;var I=function(N,j,P){if(J[P]===undefined){for(H=0;H<J.length;H++){if(J[H]!==undefined){P=H;break}}if(J[P]===undefined){var O=P*100;window.ABCJS.parse.each(N.endSlur,function(i){if(O===i){--O}});J[P]=[O]}}var M;for(var L=0;L<j;L++){M=J[P].pop();N.endSlur.push(M)}if(J[P].length===0){delete J[P]}return M};var C=function(N,j,O,M){N.startSlur=[];if(J[O]===undefined){J[O]=[]}var P=O*100+1;for(var L=0;L<j;L++){if(M){window.ABCJS.parse.each(M,function(i){if(P===i){++P}});window.ABCJS.parse.each(M,function(i){if(P===i){++P}});window.ABCJS.parse.each(M,function(i){if(P===i){++P}})}window.ABCJS.parse.each(J[O],function(i){if(P===i){++P}});window.ABCJS.parse.each(J[O],function(i){if(P===i){++P}});J[O].push(P);N.startSlur.push({label:P});P++}};for(var D=0;D<K.length;D++){var v=K[D];if(v.el_type==="note"){if(v.gracenotes){for(var E=0;E<v.gracenotes.length;E++){if(v.gracenotes[E].endSlur){var F=v.gracenotes[E].endSlur;v.gracenotes[E].endSlur=[];for(var n=0;n<F;n++){I(v.gracenotes[E],1,20)}}if(v.gracenotes[E].startSlur){H=v.gracenotes[E].startSlur;C(v.gracenotes[E],H,20)}}}if(v.endSlur){H=v.endSlur;v.endSlur=[];I(v,H,0)}if(v.startSlur){H=v.startSlur;C(v,H,0)}if(v.pitches){var G=[];for(var s=0;s<v.pitches.length;s++){if(v.pitches[s].endSlur){var A=v.pitches[s].endSlur;v.pitches[s].endSlur=[];for(var B=0;B<A;B++){var z=I(v.pitches[s],1,s+1);G.push(z)}}}for(s=0;s<v.pitches.length;s++){if(v.pitches[s].startSlur){H=v.pitches[s].startSlur;C(v.pitches[s],H,s+1,G)}}if(v.gracenotes&&v.pitches[0].endSlur&&v.pitches[0].endSlur[0]===100&&v.pitches[0].startSlur){if(v.gracenotes[0].endSlur){v.gracenotes[0].endSlur.push(v.pitches[0].startSlur[0].label)}else{v.gracenotes[0].endSlur=[v.pitches[0].startSlur[0].label]}if(v.pitches[0].endSlur.length===1){delete v.pitches[0].endSlur}else{if(v.pitches[0].endSlur[0]===100){v.pitches[0].endSlur.shift()}else{if(v.pitches[0].endSlur[v.pitches[0].endSlur.length-1]===100){v.pitches[0].endSlur.pop()}}}if(J[1].length===1){delete J[1]}else{J[1].pop()}}}}}}function e(n){var j=-2;var i=5;switch(n.type){case"treble+8":case"treble-8":break;case"bass":case"bass+8":case"bass-8":n.verticalPos=20+n.verticalPos;j+=6;i+=6;break;case"tenor":case"tenor+8":case"tenor-8":n.verticalPos=-n.verticalPos;j=-40;i=40;break;case"alto":case"alto+8":case"alto-8":n.verticalPos=-n.verticalPos;j=-40;i=40;break}if(n.verticalPos<j){while(n.verticalPos<j){n.verticalPos+=7}}else{if(n.verticalPos>i){while(n.verticalPos>i){n.verticalPos-=7}}}}for(this.lineNum=0;this.lineNum<this.lines.length;this.lineNum++){if(this.lines[this.lineNum].staff){for(this.staffNum=0;this.staffNum<this.lines[this.lineNum].staff.length;this.staffNum++){if(this.lines[this.lineNum].staff[this.staffNum].clef){e(this.lines[this.lineNum].staff[this.staffNum].clef)}for(this.voiceNum=0;this.voiceNum<this.lines[this.lineNum].staff[this.staffNum].voices.length;this.voiceNum++){l(this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]);for(var w=0;w<this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum].length;w++){if(this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum][w].el_type==="clef"){e(this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum][w])}}}}}}if(!this.formatting.pagewidth){this.formatting.pagewidth=f}if(!this.formatting.pageheight){this.formatting.pageheight=p}delete this.staffNum;delete this.voiceNum;delete this.lineNum;delete this.potentialStartBeam;delete this.potentialEndBeam;delete this.vskipPending};this.reset();this.getLastNote=function(){if(this.lines[this.lineNum]&&this.lines[this.lineNum].staff&&this.lines[this.lineNum].staff[this.staffNum]&&this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]){for(var a=this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum].length-1;a>=0;a--){var b=this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum][a];if(b.el_type==="note"){return b}}}return null};this.addTieToLastNote=function(){var a=this.getLastNote();if(a&&a.pitches&&a.pitches.length>0){a.pitches[0].startTie={};return true}return false};this.getDuration=function(a){if(a.duration){return a.duration}return 0};this.closeLine=function(){if(this.potentialStartBeam&&this.potentialEndBeam){this.potentialStartBeam.startBeam=true;this.potentialEndBeam.endBeam=true}delete this.potentialStartBeam;delete this.potentialEndBeam};this.appendElement=function(h,i,e,a){var c=this;var g=function(l){if(l.pitches!==undefined){var j=c.lines[c.lineNum].staff[c.staffNum].workingClef.verticalPos;window.ABCJS.parse.each(l.pitches,function(m){m.verticalPos=m.pitch-j})}if(l.gracenotes!==undefined){var k=c.lines[c.lineNum].staff[c.staffNum].workingClef.verticalPos;window.ABCJS.parse.each(l.gracenotes,function(m){m.verticalPos=m.pitch-k})}c.lines[c.lineNum].staff[c.staffNum].voices[c.voiceNum].push(l)};a.el_type=h;if(i!==null){a.startChar=i}if(e!==null){a.endChar=e}var d=function(){c.potentialStartBeam.startBeam=true;a.endBeam=true;delete c.potentialStartBeam;delete c.potentialEndBeam};var f=function(){if(c.potentialStartBeam!==undefined&&c.potentialEndBeam!==undefined){c.potentialStartBeam.startBeam=true;c.potentialEndBeam.endBeam=true}delete c.potentialStartBeam;delete c.potentialEndBeam};if(h==="note"){var b=c.getDuration(a);if(b>=0.25){f()}else{if(a.force_end_beam_last&&c.potentialStartBeam!==undefined){f()}else{if(a.end_beam&&c.potentialStartBeam!==undefined){if(a.rest===undefined){d()}else{f()}}else{if(a.rest===undefined){if(c.potentialStartBeam===undefined){if(!a.end_beam){c.potentialStartBeam=a;delete c.potentialEndBeam}}else{c.potentialEndBeam=a}}}}}}else{f()}delete a.end_beam;delete a.force_end_beam_last;g(a)};this.appendStartingElement=function(f,a,h,c){this.closeLine();var e;if(f==="key"){e=c.impliedNaturals;delete c.impliedNaturals}var b=window.ABCJS.parse.clone(c);if(f==="clef"){this.lines[this.lineNum].staff[this.staffNum].workingClef=b}var g=this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum];for(var d=0;d<g.length;d++){if(g[d].el_type==="note"||g[d].el_type==="bar"){b.el_type=f;b.startChar=a;b.endChar=h;if(e){b.accidentals=e.concat(b.accidentals)}g.push(b);return}if(g[d].el_type===f){b.el_type=f;b.startChar=a;b.endChar=h;if(e){b.accidentals=e.concat(b.accidentals)}g[d]=b;return}}this.lines[this.lineNum].staff[this.staffNum][f]=c};this.getNumLines=function(){return this.lines.length};this.pushLine=function(a){if(this.vskipPending){a.vskip=this.vskipPending;delete this.vskipPending}this.lines.push(a)};this.addSubtitle=function(a){this.pushLine({subtitle:a})};this.addSpacing=function(a){this.vskipPending=a};this.addNewPage=function(a){this.pushLine({newpage:a})};this.addSeparator=function(c,b,a){this.pushLine({separator:{spaceAbove:c,spaceBelow:b,lineLength:a}})};this.addText=function(a){this.pushLine({text:a})};this.addCentered=function(a){this.pushLine({text:[{text:a,center:true}]}) };this.containsNotes=function(b){for(var a=0;a<b.length;a++){if(b[a].el_type==="note"||b[a].el_type==="bar"){return true}}return false};this.containsNotesStrict=function(b){for(var a=0;a<b.length;a++){if(b[a].el_type==="note"&&b[a].rest===undefined){return true}}return false};this.startNewLine=function(e){var d=this;this.closeLine();var c=function(j){d.lines[d.lineNum].staff[d.staffNum].voices[d.voiceNum]=[];if(d.isFirstLine(d.lineNum)){if(j.name){if(!d.lines[d.lineNum].staff[d.staffNum].title){d.lines[d.lineNum].staff[d.staffNum].title=[]}d.lines[d.lineNum].staff[d.staffNum].title[d.voiceNum]=j.name}}else{if(j.subname){if(!d.lines[d.lineNum].staff[d.staffNum].title){d.lines[d.lineNum].staff[d.staffNum].title=[]}d.lines[d.lineNum].staff[d.staffNum].title[d.voiceNum]=j.subname}}if(j.style){d.appendElement("style",null,null,{head:j.style})}if(j.stem){d.appendElement("stem",null,null,{direction:j.stem})}else{if(d.voiceNum>0){if(d.lines[d.lineNum].staff[d.staffNum].voices[0]!==undefined){var g=false;for(var f=0;f<d.lines[d.lineNum].staff[d.staffNum].voices[0].length;f++){if(d.lines[d.lineNum].staff[d.staffNum].voices[0].el_type==="stem"){g=true}}if(!g){var h={el_type:"stem",direction:"up"};d.lines[d.lineNum].staff[d.staffNum].voices[0].splice(0,0,h)}}d.appendElement("stem",null,null,{direction:"down"})}}if(j.scale){d.appendElement("scale",null,null,{size:j.scale})}};var a=function(f){d.lines[d.lineNum].staff[d.staffNum]={voices:[],clef:f.clef,key:f.key,workingClef:f.clef};if(f.vocalfont){d.lines[d.lineNum].staff[d.staffNum].vocalfont=f.vocalfont}if(f.bracket){d.lines[d.lineNum].staff[d.staffNum].bracket=f.bracket}if(f.brace){d.lines[d.lineNum].staff[d.staffNum].brace=f.brace}if(f.connectBarLines){d.lines[d.lineNum].staff[d.staffNum].connectBarLines=f.connectBarLines}c(f);if(f.part){d.appendElement("part",f.startChar,f.endChar,{title:f.part})}if(f.meter!==undefined){d.lines[d.lineNum].staff[d.staffNum].meter=f.meter}};var b=function(f){d.lines[d.lineNum]={staff:[]};a(f)};if(this.lines[this.lineNum]===undefined){b(e)}else{if(this.lines[this.lineNum].staff===undefined){this.lineNum++;this.startNewLine(e)}else{if(this.lines[this.lineNum].staff[this.staffNum]===undefined){a(e)}else{if(this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]===undefined){c(e)}else{if(!this.containsNotes(this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum])){return}else{this.lineNum++;this.startNewLine(e)}}}}}};this.hasBeginMusic=function(){return this.lines.length>0};this.isFirstLine=function(a){for(var b=a-1;b>=0;b--){if(this.lines[b].staff!==undefined){return false}}return true};this.getCurrentVoice=function(){if(this.lines[this.lineNum]!==undefined&&this.lines[this.lineNum].staff[this.staffNum]!==undefined&&this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]!==undefined){return this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]}else{return null}};this.setCurrentVoice=function(c,b){this.staffNum=c;this.voiceNum=b;for(var a=0;a<this.lines.length;a++){if(this.lines[a].staff){if(this.lines[a].staff[c]===undefined||this.lines[a].staff[c].voices[b]===undefined||!this.containsNotes(this.lines[a].staff[c].voices[b])){this.lineNum=a;return}}}this.lineNum=a};this.addMetaText=function(a,b){if(this.metaText[a]===undefined){this.metaText[a]=b}else{this.metaText[a]+="\n"+b}};this.addMetaTextArray=function(a,b){if(this.metaText[a]===undefined){this.metaText[a]=[b]}else{this.metaText[a].push(b)}};this.addMetaTextObj=function(a,b){this.metaText[a]=b}};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.midi){window.ABCJS.midi={}}(function(){function a(j,i){for(var h in i){if(i.hasOwnProperty(h)){j.setAttribute(h,i[h])}}return j}function g(h,i){this.javamidi=h;this.qtmidi=i}g.prototype.setTempo=function(h){this.javamidi.setTempo(h);this.qtmidi.setTempo(h)};g.prototype.startTrack=function(){this.javamidi.startTrack();this.qtmidi.startTrack()};g.prototype.endTrack=function(){this.javamidi.endTrack();this.qtmidi.endTrack()};g.prototype.setInstrument=function(h){this.javamidi.setInstrument(h);this.qtmidi.setInstrument(h)};g.prototype.startNote=function(j,h,i){this.javamidi.startNote(j,h,i);this.qtmidi.startNote(j,h,i)};g.prototype.endNote=function(i,h){this.javamidi.endNote(i,h);this.qtmidi.endNote(i,h)};g.prototype.addRest=function(h){this.javamidi.addRest(h);this.qtmidi.addRest(h)};g.prototype.embed=function(h){this.javamidi.embed(h);this.qtmidi.embed(h,true)};function b(h){this.playlist=[];this.trackcount=0;this.timecount=0;this.tempo=60;this.midiapi=MIDIPlugin;this.midiwriter=h;this.noteOnAndChannel="%90"}b.prototype.setTempo=function(h){this.tempo=h};b.prototype.startTrack=function(){this.silencelength=0;this.trackcount++;this.timecount=0;this.playlistpos=0;this.first=true;if(this.instrument){this.setInstrument(this.instrument)}if(this.channel){this.setChannel(this.channel)}};b.prototype.endTrack=function(){};b.prototype.setInstrument=function(h){this.instrument=h;this.midiapi.setInstrument(h)};b.prototype.setChannel=function(h){this.channel=h;this.midiapi.setChannel(h)};b.prototype.updatePos=function(){while(this.playlist[this.playlistpos]&&this.playlist[this.playlistpos].time<this.timecount){this.playlistpos++}};b.prototype.startNote=function(k,i,j){this.timecount+=this.silencelength;this.silencelength=0;if(this.first){}this.updatePos();var h=this;this.playlist.splice(this.playlistpos,0,{time:this.timecount,funct:function(){h.midiapi.playNote(k);h.midiwriter.notifySelect(j)}})};b.prototype.endNote=function(j,i){this.timecount+=i;this.updatePos();var h=this;this.playlist.splice(this.playlistpos,0,{time:this.timecount,funct:function(){h.midiapi.stopNote(j)}})};b.prototype.addRest=function(h){this.silencelength+=h};b.prototype.embed=function(i){this.playlink=a(document.createElement("a"),{style:"border:1px solid black; margin:3px;"});this.playlink.innerHTML="play";var h=this;this.playlink.onmousedown=function(){if(h.playing){this.innerHTML="play";h.pausePlay()}else{this.innerHTML="pause";h.startPlay()}};i.appendChild(this.playlink);var j=a(document.createElement("a"),{style:"border:1px solid black; margin:3px;"});j.innerHTML="stop";j.onmousedown=function(){h.stopPlay()};i.appendChild(j);this.i=0;this.currenttime=0;this.playing=false};b.prototype.stopPlay=function(){this.i=0;this.currenttime=0;this.pausePlay();this.playlink.innerHTML="play"};b.prototype.startPlay=function(){this.playing=true;var h=this;this.ticksperinterval=480/4;this.doPlay();this.playinterval=window.setInterval(function(){h.doPlay()},(60000/(this.tempo*4)))};b.prototype.pausePlay=function(){this.playing=false;window.clearInterval(this.playinterval);this.midiapi.stopAllNotes()};b.prototype.doPlay=function(){while(this.playlist[this.i]&&this.playlist[this.i].time<=this.currenttime){this.playlist[this.i].funct();this.i++}if(this.playlist[this.i]){this.currenttime+=this.ticksperinterval}else{this.stopPlay()}};function d(){this.trackstrings="";this.trackcount=0;this.noteOnAndChannel="%90"}d.prototype.setTempo=function(h){if(this.trackcount===0){this.startTrack(); this.track+="%00%FF%51%03"+c(Math.round(60000000/h),6);this.endTrack()}};d.prototype.startTrack=function(){this.track="";this.silencelength=0;this.trackcount++;this.first=true;if(this.instrument){this.setInstrument(this.instrument)}};d.prototype.endTrack=function(){var h=c(this.track.length/3+4,8);this.track="MTrk"+h+this.track+"%00%FF%2F%00";this.trackstrings+=this.track};d.prototype.setInstrument=function(h){if(this.track){this.track="%00%C0"+c(h,2)+this.track}else{this.track="%00%C0"+c(h,2)}this.instrument=h};d.prototype.setChannel=function(h){this.channel=h-1;this.noteOnAndChannel="%9"+this.channel.toString(16)};d.prototype.startNote=function(i,h){this.track+=e(this.silencelength);this.silencelength=0;if(this.first){this.first=false;this.track+=this.noteOnAndChannel}this.track+="%"+i.toString(16)+"%"+h};d.prototype.endNote=function(i,h){this.track+=e(h);this.track+="%"+i.toString(16)+"%00"};d.prototype.addRest=function(h){this.silencelength+=h};d.prototype.embed=function(i,h){var k="data:audio/midi,MThd%00%00%00%06%00%01"+c(this.trackcount,4)+"%01%e0"+this.trackstrings;var j=a(document.createElement("a"),{href:k});j.innerHTML="download midi";i.insertBefore(j,i.firstChild);if(h){return}var l=a(document.createElement("embed"),{src:k,type:"video/quicktime",controller:"true",autoplay:"false",loop:"false",enablejavascript:"true",style:"display:block; height: 20px;"});i.insertBefore(l,i.firstChild)};function f(k){var h="";for(var j=0;j<k.length;j+=2){h+="%";h+=k.substr(j,2)}return h}function c(j,i){var h=j.toString(16);while(h.length<i){h="0"+h}return f(h)}function e(o){var k=0;var h=[];while(o!==0){h.push(o&127);o=o>>7}for(var j=h.length-1;j>=0;j--){k=k<<8;var l=h[j];if(j!==0){l=l|128}k=k|l}var m=k.toString(16).length;m+=m%2;return c(k,m)}ABCJS.midi.MidiWriter=function(i,h){h=h||{};this.parent=i;this.scale=[0,2,4,5,7,9,11];this.restart={line:0,staff:0,voice:0,pos:0};this.visited={};this.multiplier=1;this.next=null;this.qpm=h.qpm||180;this.program=h.program||2;this.noteOnAndChannel="%90";this.javamidi=h.type==="java"||false;this.listeners=[];this.transpose=0;if(this.javamidi){MIDIPlugin=document.MIDIPlugin;setTimeout(function(){try{MIDIPlugin.openPlugin()}catch(k){var j=document.createElement("a");j.href="http://java.sun.com/products/java-media/sound/soundbanks.html";j.target="_blank";j.appendChild(document.createTextNode("Download Soundbank"));i.appendChild(j)}},0)}};ABCJS.midi.MidiWriter.prototype.addListener=function(h){this.listeners.push(h)};ABCJS.midi.MidiWriter.prototype.notifySelect=function(j){for(var h=0;h<this.listeners.length;h++){this.listeners[h].notifySelect(j.abselem)}};ABCJS.midi.MidiWriter.prototype.getMark=function(){return{line:this.line,staff:this.staff,voice:this.voice,pos:this.pos}};ABCJS.midi.MidiWriter.prototype.getMarkString=function(h){h=h||this;return"line"+h.line+"staff"+h.staff+"voice"+h.voice+"pos"+h.pos};ABCJS.midi.MidiWriter.prototype.goToMark=function(h){this.line=h.line;this.staff=h.staff;this.voice=h.voice;this.pos=h.pos};ABCJS.midi.MidiWriter.prototype.markVisited=function(){this.lastmark=this.getMarkString();this.visited[this.lastmark]=true};ABCJS.midi.MidiWriter.prototype.isVisited=function(){if(this.visited[this.getMarkString()]){return true}return false};ABCJS.midi.MidiWriter.prototype.setJumpMark=function(h){this.visited[this.lastmark]=h};ABCJS.midi.MidiWriter.prototype.getJumpMark=function(){return this.visited[this.getMarkString()]};ABCJS.midi.MidiWriter.prototype.getLine=function(){return this.abctune.lines[this.line]};ABCJS.midi.MidiWriter.prototype.getStaff=function(){try{return this.getLine().staff[this.staff]}catch(h){}};ABCJS.midi.MidiWriter.prototype.getVoice=function(){return this.getStaff().voices[this.voice]};ABCJS.midi.MidiWriter.prototype.getElem=function(){return this.getVoice()[this.pos]};ABCJS.midi.MidiWriter.prototype.writeABC=function(l){try{this.midi=(this.javamidi)?new g(new b(this),new d()):new d();this.baraccidentals=[];this.abctune=l;this.baseduration=480*4;if(l.formatting.midi&&l.formatting.midi.transpose){this.transpose=l.formatting.midi.transpose}if(l.formatting.midi&&l.formatting.midi.program&&l.formatting.midi.program.program){this.midi.setInstrument(l.formatting.midi.program.program)}else{this.midi.setInstrument(this.program)}if(l.formatting.midi&&l.formatting.midi.channel){this.midi.setChannel(l.formatting.midi.channel)}if(l.metaText.tempo){var k=1/4;if(l.metaText.tempo.duration){k=l.metaText.tempo.duration[0]}var j=60;if(l.metaText.tempo.bpm){j=l.metaText.tempo.bpm}this.qpm=j*k*4}this.midi.setTempo(this.qpm);this.staffcount=1;for(this.staff=0;this.staff<this.staffcount;this.staff++){this.voicecount=1;for(this.voice=0;this.voice<this.voicecount;this.voice++){this.midi.startTrack();this.restart={line:0,staff:this.staff,voice:this.voice,pos:0};this.next=null;for(this.line=0;this.line<l.lines.length;this.line++){var h=l.lines[this.line];if(this.getLine().staff){this.writeABCLine()}}this.midi.endTrack()}}this.midi.embed(this.parent)}catch(i){this.parent.innerHTML="Couldn't write midi: "+i}};ABCJS.midi.MidiWriter.prototype.writeABCLine=function(){this.staffcount=this.getLine().staff.length;this.voicecount=this.getStaff().voices.length;this.setKeySignature(this.getStaff().key);this.writeABCVoiceLine()};ABCJS.midi.MidiWriter.prototype.writeABCVoiceLine=function(){this.pos=0;while(this.pos<this.getVoice().length){this.writeABCElement(this.getElem());if(this.next){this.goToMark(this.next);this.next=null;if(!this.getLine().staff){return}}else{this.pos++}}};ABCJS.midi.MidiWriter.prototype.writeABCElement=function(h){var i;switch(h.el_type){case"note":this.writeNote(h);break;case"key":this.setKeySignature(h);break;case"bar":this.handleBar(h);break;case"meter":case"clef":break;default:}};ABCJS.midi.MidiWriter.prototype.writeNote=function(m){if(m.startTriplet){this.multiplier=2/3}var h=m.duration*this.baseduration*this.multiplier;if(m.pitches){var l=[];for(var j=0;j<m.pitches.length;j++){var k=m.pitches[j];var n=k.pitch;if(k.accidental){switch(k.accidental){case"sharp":this.baraccidentals[n]=1;break;case"flat":this.baraccidentals[n]=-1;break;case"natural":this.baraccidentals[n]=0;break;case"dblsharp":this.baraccidentals[n]=2;break;case"dblflat":this.baraccidentals[n]=-2;break}}l[j]=60+12*this.extractOctave(n)+this.scale[this.extractNote(n)];if(this.baraccidentals[n]!==undefined){l[j]+=this.baraccidentals[n]}else{l[j]+=this.accidentals[this.extractNote(n)]}l[j]+=this.transpose;this.midi.startNote(l[j],64,m);if(k.startTie){this.tieduration=h}}for(j=0;j<m.pitches.length;j++){var k=m.pitches[j];var n=k.pitch+this.transpose;if(k.startTie){continue}if(k.endTie){this.midi.endNote(l[j],h+this.tieduration)}else{this.midi.endNote(l[j],h)}h=0;this.tieduration=0}}else{if(m.rest&&m.rest.type!=="spacer"){this.midi.addRest(h)}}if(m.endTriplet){this.multiplier=1}};ABCJS.midi.MidiWriter.prototype.handleBar=function(l){this.baraccidentals=[];var m=(l.type==="bar_right_repeat"||l.type==="bar_dbl_repeat");var k=(l.startEnding)?true:false; var h=(m||k);var j=(l.type==="bar_left_repeat"||l.type==="bar_dbl_repeat"||l.type==="bar_thick_thin"||l.type==="bar_thin_thick"||l.type==="bar_thin_thin"||l.type==="bar_right_repeat");var i=null;if(this.isVisited()){i=this.getJumpMark()}else{if(k||m){if(this.visited[this.lastmark]===true){this.setJumpMark(this.getMark())}}if(h){this.markVisited()}if(m){i=this.restart;this.setJumpMark(this.getMark())}}if(j){this.restart=this.getMark()}if(i&&this.getMarkString(i)!==this.getMarkString()){this.next=i}};ABCJS.midi.MidiWriter.prototype.setKeySignature=function(h){this.accidentals=[0,0,0,0,0,0,0];if(this.abctune.formatting.bagpipes){h.accidentals=[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}]}if(!h.accidentals){return}window.ABCJS.parse.each(h.accidentals,function(k){var l=(k.acc==="sharp")?1:(k.acc==="natural")?0:-1;var j=k.note.toLowerCase();var i=this.extractNote(j.charCodeAt(0)-"c".charCodeAt(0));this.accidentals[i]+=l},this)};ABCJS.midi.MidiWriter.prototype.extractNote=function(h){h=h%7;if(h<0){h+=7}return h};ABCJS.midi.MidiWriter.prototype.extractOctave=function(h){return Math.floor(h/7)}})();if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.parse){window.ABCJS.parse={}}window.ABCJS.parse.clone=function(c){var a={};for(var b in c){if(c.hasOwnProperty(b)){a[b]=c[b]}}return a};window.ABCJS.parse.gsub=function(c,b,a){return c.split(b).join(a)};window.ABCJS.parse.strip=function(a){return a.replace(/^\s+/,"").replace(/\s+$/,"")};window.ABCJS.parse.startsWith=function(b,a){return b.indexOf(a)===0};window.ABCJS.parse.endsWith=function(c,a){var b=c.length-a.length;return b>=0&&c.lastIndexOf(a)===b};window.ABCJS.parse.each=function(a,d,c){for(var b=0,e=a.length;b<e;b++){d.apply(c,[a[b],b])}};window.ABCJS.parse.last=function(a){if(a.length===0){return null}return a[a.length-1]};window.ABCJS.parse.compact=function(a){var b=[];for(var c=0;c<a.length;c++){if(a[c]){b.push(a[c])}}return b};window.ABCJS.parse.detect=function(a,c){for(var b=0;b<a.length;b++){if(c(a[b])){return true}}return false};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.parse){window.ABCJS.parse={}}window.ABCJS.parse.Parse=function(){var f=new window.ABCJS.data.Tune();var n=new window.ABCJS.parse.tokenizer();this.getTune=function(){return f};var y={reset:function(){for(var A in this){if(this.hasOwnProperty(A)&&typeof this[A]!=="function"){delete this[A]}}this.iChar=0;this.key={accidentals:[],root:"none",acc:"",mode:""};this.meter={type:"specified",value:[{num:"4",den:"4"}]};this.origMeter={type:"specified",value:[{num:"4",den:"4"}]};this.hasMainTitle=false;this.default_length=0.125;this.clef={type:"treble",verticalPos:0};this.next_note_duration=0;this.start_new_line=true;this.is_in_header=true;this.is_in_history=false;this.partForNextLine="";this.havent_set_length=true;this.voices={};this.staves=[];this.macros={};this.currBarNumber=1;this.inTextBlock=false;this.inPsBlock=false;this.ignoredDecorations=[];this.textBlock="";this.score_is_present=false;this.inEnding=false;this.inTie=false;this.inTieChord={}}};var z=function(A){if(!y.warnings){y.warnings=[]}y.warnings.push(A)};var c=function(B){var A=window.ABCJS.parse.gsub(B,"\x12"," ");A=window.ABCJS.parse.gsub(A,"&","&amp;");A=window.ABCJS.parse.gsub(A,"<","&lt;");return window.ABCJS.parse.gsub(A,">","&gt;")};var x=function(E,A,D){var C=A.charAt(D);if(C===" "){C="SPACE"}var B=c(A.substring(0,D))+'<span style="text-decoration:underline;font-size:1.3em;font-weight:bold;">'+C+"</span>"+c(A.substring(D+1));z("Music Line:"+f.getNumLines()+":"+(D+1)+": "+E+": "+B)};var u=new window.ABCJS.parse.ParseHeader(n,x,y,f);this.getWarnings=function(){return y.warnings};var t=function(C,D){if(C.charAt(D)==='"'){var E=n.getBrackettedSubstring(C,D,5);if(!E[2]){x("Missing the closing quote while parsing the chord symbol",C,D)}if(E[0]>0&&E[1].length>0&&E[1].charAt(0)==="^"){E[1]=E[1].substring(1);E[2]="above"}else{if(E[0]>0&&E[1].length>0&&E[1].charAt(0)==="_"){E[1]=E[1].substring(1);E[2]="below"}else{if(E[0]>0&&E[1].length>0&&E[1].charAt(0)==="<"){E[1]=E[1].substring(1);E[2]="left"}else{if(E[0]>0&&E[1].length>0&&E[1].charAt(0)===">"){E[1]=E[1].substring(1);E[2]="right"}else{if(E[0]>0&&E[1].length>0&&E[1].charAt(0)==="@"){E[1]=E[1].substring(1);var A=n.getFloat(E[1]);if(A.digits===0){x("Missing first position in absolutely positioned annotation.",C,D)}E[1]=E[1].substring(A.digits);if(E[1][0]!==","){x("Missing comma absolutely positioned annotation.",C,D)}E[1]=E[1].substring(1);var F=n.getFloat(E[1]);if(F.digits===0){x("Missing second position in absolutely positioned annotation.",C,D)}E[1]=E[1].substring(F.digits);var B=n.skipWhiteSpace(E[1]);E[1]=E[1].substring(B);E[2]=null;E[3]={x:A.value,y:F.value}}else{E[1]=E[1].replace(/([ABCDEFG])b/g,"$1♭");E[1]=E[1].replace(/([ABCDEFG])#/g,"$1♯");E[2]="default"}}}}}return E}return[0,""]};var p=["trill","lowermordent","uppermordent","mordent","pralltriller","accent","fermata","invertedfermata","tenuto","0","1","2","3","4","5","+","wedge","open","thumb","snap","turn","roll","breath","shortphrase","mediumphrase","longphrase","segno","coda","D.S.","D.C.","fine","crescendo(","crescendo)","diminuendo(","diminuendo)","p","pp","f","ff","mf","mp","ppp","pppp","fff","ffff","sfz","repeatbar","repeatbar2","slide","upbow","downbow","/","//","///","////","trem1","trem2","trem3","trem4","turnx","invertedturn","invertedturnx","trill(","trill)","arpeggio","xstem","mark","style=normal","style=harmonic","style=rhythm","style=x"];var s=[["<","accent"],[">","accent"],["tr","trill"],["<(","crescendo("],["<)","crescendo)"],[">(","diminuendo("],[">)","diminuendo)"],["plus","+"],["emphasis","accent"]];var h=function(A,C){var D=y.macros[A.charAt(C)];if(D!==undefined){if(D.charAt(0)==="!"||D.charAt(0)==="+"){D=D.substring(1)}if(D.charAt(D.length-1)==="!"||D.charAt(D.length-1)==="+"){D=D.substring(0,D.length-1)}if(window.ABCJS.parse.detect(p,function(E){return(D===E)})){return[1,D]}else{if(!window.ABCJS.parse.detect(y.ignoredDecorations,function(E){return(D===E)})){x("Unknown macro: "+D,A,C)}return[1,""]}}switch(A.charAt(C)){case".":return[1,"staccato"];case"u":return[1,"upbow"];case"v":return[1,"downbow"];case"~":return[1,"irishroll"];case"!":case"+":var B=n.getBrackettedSubstring(A,C,5);if(B[1].length>0&&(B[1].charAt(0)==="^"||B[1].charAt(0)==="_")){B[1]=B[1].substring(1)}if(window.ABCJS.parse.detect(p,function(E){return(B[1]===E)})){return B}if(window.ABCJS.parse.detect(s,function(E){if(B[1]===E[0]){B[1]=E[1];return true}else{return false}})){return B}if(A.charAt(C)==="!"&&(B[0]===1||A.charAt(C+B[0]-1)!=="!")){return[1,null]}x("Unknown decoration: "+B[1],A,C);B[1]="";return B;case"H":return[1,"fermata"];case"J":return[1,"slide"];case"L":return[1,"accent"];case"M":return[1,"mordent"];case"O":return[1,"coda"];case"P":return[1,"pralltriller"];case"R":return[1,"roll"];case"S":return[1,"segno"];case"T":return[1,"trill"]}return[0,0]};var e=function(A,B){var C=B;while(n.isWhiteSpace(A.charAt(B))){B++}return[B-C]};var r=function(C,F){var D=n.getBarLine(C,F); if(D.len===0){return[0,""]}if(D.warn){x(D.warn,C,F);return[D.len,""]}for(var B=0;B<C.length;B++){if(C.charAt(F+D.len+B)!==" "){break}}var G=D.len;if(C.charAt(F+D.len+B)==="["){D.len+=B+1}if(C.charAt(F+D.len)==='"'&&C.charAt(F+D.len-1)==="["){var A=n.getBrackettedSubstring(C,F+D.len,5);return[D.len+A[0],D.token,A[1]]}var E=n.getTokenOf(C.substring(F+D.len),"1234567890-,");if(E.len===0||E.token[0]==="-"){return[G,D.token]}return[D.len+E.len,D.token,E.token]};var o=function(A,C){var B={};var D=C;while(A.charAt(C)==="("||n.isWhiteSpace(A.charAt(C))){if(A.charAt(C)==="("){if(C+1<A.length&&(A.charAt(C+1)>="2"&&A.charAt(C+1)<="9")){if(B.triplet!==undefined){x("Can't nest triplets",A,C)}else{B.triplet=A.charAt(C+1)-"0";if(C+2<A.length&&A.charAt(C+2)===":"){if(C+3<A.length&&A.charAt(C+3)===":"){if(C+4<A.length&&(A.charAt(C+4)>="1"&&A.charAt(C+4)<="9")){B.num_notes=A.charAt(C+4)-"0";C+=3}else{x("expected number after the two colons after the triplet to mark the duration",A,C)}}else{if(C+3<A.length&&(A.charAt(C+3)>="1"&&A.charAt(C+3)<="9")){if(C+4<A.length&&A.charAt(C+4)===":"){if(C+5<A.length&&(A.charAt(C+5)>="1"&&A.charAt(C+5)<="9")){B.num_notes=A.charAt(C+5)-"0";C+=4}}else{B.num_notes=B.triplet;C+=3}}else{x("expected number after the triplet to mark the duration",A,C)}}}}C++}else{if(B.startSlur===undefined){B.startSlur=1}else{B.startSlur++}}}C++}B.consumed=C-D;return B};var m=function(B,H){if(!B){x("Can't add words before the first line of mulsic",B,0);return}H=window.ABCJS.parse.strip(H);if(H.charAt(H.length-1)!=="-"){H=H+" "}var G=[];var F=0;var D=false;var A=function(I){var J=window.ABCJS.parse.strip(H.substring(F,I));F=I+1;if(J.length>0){if(D){J=window.ABCJS.parse.gsub(J,"~"," ")}var K=H.charAt(I);if(K!=="_"&&K!=="-"){K=" "}G.push({syllable:n.translateString(J),divider:K});D=false;return true}return false};for(var C=0;C<H.length;C++){switch(H.charAt(C)){case" ":case"\x12":A(C);break;case"-":if(!A(C)&&G.length>0){window.ABCJS.parse.last(G).divider="-";G.push({skip:true,to:"next"})}break;case"_":A(C);G.push({skip:true,to:"slur"});break;case"*":A(C);G.push({skip:true,to:"next"});break;case"|":A(C);G.push({skip:true,to:"bar"});break;case"~":D=true;break}}var E=false;window.ABCJS.parse.each(B,function(J){if(G.length!==0){if(G[0].skip){switch(G[0].to){case"next":if(J.el_type==="note"&&J.pitches!==null&&!E){G.shift()}break;case"slur":if(J.el_type==="note"&&J.pitches!==null){G.shift()}break;case"bar":if(J.el_type==="bar"){G.shift()}break}}else{if(J.el_type==="note"&&J.rest===undefined&&!E){var I=G.shift();if(J.lyric===undefined){J.lyric=[I]}else{J.lyric.push(I)}}}}})};var d=function(B,H){if(!B){x("Can't add symbols before the first line of mulsic",B,0);return}H=window.ABCJS.parse.strip(H);if(H.charAt(H.length-1)!=="-"){H=H+" "}var G=[];var F=0;var D=false;var A=function(I){var J=window.ABCJS.parse.strip(H.substring(F,I));F=I+1;if(J.length>0){if(D){J=window.ABCJS.parse.gsub(J,"~"," ")}var K=H.charAt(I);if(K!=="_"&&K!=="-"){K=" "}G.push({syllable:n.translateString(J),divider:K});D=false;return true}return false};for(var C=0;C<H.length;C++){switch(H.charAt(C)){case" ":case"\x12":A(C);break;case"-":if(!A(C)&&G.length>0){window.ABCJS.parse.last(G).divider="-";G.push({skip:true,to:"next"})}break;case"_":A(C);G.push({skip:true,to:"slur"});break;case"*":A(C);G.push({skip:true,to:"next"});break;case"|":A(C);G.push({skip:true,to:"bar"});break;case"~":D=true;break}}var E=false;window.ABCJS.parse.each(B,function(J){if(G.length!==0){if(G[0].skip){switch(G[0].to){case"next":if(J.el_type==="note"&&J.pitches!==null&&!E){G.shift()}break;case"slur":if(J.el_type==="note"&&J.pitches!==null){G.shift()}break;case"bar":if(J.el_type==="bar"){G.shift()}break}}else{if(J.el_type==="note"&&J.rest===undefined&&!E){var I=G.shift();if(J.lyric===undefined){J.lyric=[I]}else{J.lyric.push(I)}}}}})};var b=function(A,B){switch(A.charAt(B)){case">":if(B<A.length-1&&A.charAt(B+1)===">"){return[2,1.75,0.25]}else{return[1,1.5,0.5]}break;case"<":if(B<A.length-1&&A.charAt(B+1)==="<"){return[2,0.25,1.75]}else{return[1,0.5,1.5]}break}return null};var g=function(A){if(A.duration!==undefined&&A.duration<0.25){A.end_beam=true}return A};var j={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11};var a={x:"invisible",y:"spacer",z:"rest",Z:"multimeasure"};var i=function(J,G,C,A){var H=function(K){return(K==="octave"||K==="duration"||K==="Zduration"||K==="broken_rhythm"||K==="end_slur")};var B="startSlur";var D=false;while(1){switch(J.charAt(G)){case"(":if(B==="startSlur"){if(C.startSlur===undefined){C.startSlur=1}else{C.startSlur++}}else{if(H(B)){C.endChar=G;return C}else{return null}}break;case")":if(H(B)){if(C.endSlur===undefined){C.endSlur=1}else{C.endSlur++}}else{return null}break;case"^":if(B==="startSlur"){C.accidental="sharp";B="sharp2"}else{if(B==="sharp2"){C.accidental="dblsharp";B="pitch"}else{if(H(B)){C.endChar=G;return C}else{return null}}}break;case"_":if(B==="startSlur"){C.accidental="flat";B="flat2"}else{if(B==="flat2"){C.accidental="dblflat";B="pitch"}else{if(H(B)){C.endChar=G;return C}else{return null}}}break;case"=":if(B==="startSlur"){C.accidental="natural";B="pitch"}else{if(H(B)){C.endChar=G;return C}else{return null}}break;case"A":case"B":case"C":case"D":case"E":case"F":case"G":case"a":case"b":case"c":case"d":case"e":case"f":case"g":if(B==="startSlur"||B==="sharp2"||B==="flat2"||B==="pitch"){C.pitch=j[J.charAt(G)];B="octave";if(A&&y.next_note_duration!==0){C.duration=y.next_note_duration;y.next_note_duration=0;D=true}else{C.duration=y.default_length}}else{if(H(B)){C.endChar=G;return C}else{return null}}break;case",":if(B==="octave"){C.pitch-=7}else{if(H(B)){C.endChar=G;return C}else{return null}}break;case"'":if(B==="octave"){C.pitch+=7}else{if(H(B)){C.endChar=G;return C}else{return null}}break;case"x":case"y":case"z":case"Z":if(B==="startSlur"){C.rest={type:a[J.charAt(G)]};delete C.accidental;delete C.startSlur;delete C.startTie;delete C.endSlur;delete C.endTie;delete C.end_beam;delete C.grace_notes;if(C.rest.type==="multimeasure"){C.duration=1;B="Zduration"}else{if(A&&y.next_note_duration!==0){C.duration=y.next_note_duration;y.next_note_duration=0;D=true}else{C.duration=y.default_length}B="duration"}}else{if(H(B)){C.endChar=G;return C}else{return null}}break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"0":case"/":if(B==="octave"||B==="duration"){var I=n.getFraction(J,G);if(!D){C.duration=C.duration*I.value}C.endChar=I.index;while(I.index<J.length&&(n.isWhiteSpace(J.charAt(I.index))||J.charAt(I.index)==="-")){if(J.charAt(I.index)==="-"){C.startTie={}}else{C=g(C)}I.index++}G=I.index-1;B="broken_rhythm"}else{if(B==="sharp2"){C.accidental="quartersharp";B="pitch"}else{if(B==="flat2"){C.accidental="quarterflat";B="pitch"}else{if(B==="Zduration"){var F=n.getNumber(J,G);C.duration=F.num;C.endChar=F.index;return C}else{return null}}}}break;case"-":if(B==="startSlur"){f.addTieToLastNote();C.endTie=true}else{if(B==="octave"||B==="duration"||B==="end_slur"){C.startTie={};if(!D&&A){B="broken_rhythm" }else{if(n.isWhiteSpace(J.charAt(G+1))){g(C)}C.endChar=G+1;return C}}else{if(B==="broken_rhythm"){C.endChar=G;return C}else{return null}}}break;case" ":case"\t":if(H(B)){C.end_beam=true;do{if(J.charAt(G)==="-"){C.startTie={}}G++}while(G<J.length&&(n.isWhiteSpace(J.charAt(G))||J.charAt(G)==="-"));C.endChar=G;if(!D&&A&&(J.charAt(G)==="<"||J.charAt(G)===">")){G--;B="broken_rhythm"}else{return C}}else{return null}break;case">":case"<":if(H(B)){if(A){var E=b(J,G);G+=E[0]-1;y.next_note_duration=E[2]*C.duration;C.duration=E[1]*C.duration;B="end_slur"}else{C.endChar=G;return C}}else{return null}break;default:if(H(B)){C.endChar=G;return C}return null}G++;if(G===J.length){if(H(B)){C.endChar=G;return C}else{return null}}}return null};function v(){var B={startChar:-1,endChar:-1};if(y.partForNextLine.length){B.part=y.partForNextLine}B.clef=y.currentVoice&&y.staves[y.currentVoice.staffNum].clef!==undefined?window.ABCJS.parse.clone(y.staves[y.currentVoice.staffNum].clef):window.ABCJS.parse.clone(y.clef);B.key=window.ABCJS.parse.parseKeyVoice.deepCopyKey(y.key);window.ABCJS.parse.parseKeyVoice.addPosToKey(B.clef,B.key);if(y.meter!==null){if(y.currentVoice){window.ABCJS.parse.each(y.staves,function(C){C.meter=y.meter});B.meter=y.staves[y.currentVoice.staffNum].meter;y.staves[y.currentVoice.staffNum].meter=null}else{B.meter=y.meter}y.meter=null}else{if(y.currentVoice&&y.staves[y.currentVoice.staffNum].meter){B.meter=y.staves[y.currentVoice.staffNum].meter;y.staves[y.currentVoice.staffNum].meter=null}}if(y.currentVoice&&y.currentVoice.name){B.name=y.currentVoice.name}if(y.vocalfont){B.vocalfont=y.vocalfont}if(y.style){B.style=y.style}if(y.currentVoice){var A=y.staves[y.currentVoice.staffNum];if(A.brace){B.brace=A.brace}if(A.bracket){B.bracket=A.bracket}if(A.connectBarLines){B.connectBarLines=A.connectBarLines}if(A.name){B.name=A.name[y.currentVoice.index]}if(A.subname){B.subname=A.subname[y.currentVoice.index]}if(y.currentVoice.stem){B.stem=y.currentVoice.stem}if(y.currentVoice.scale){B.scale=y.currentVoice.scale}if(y.currentVoice.style){B.style=y.currentVoice.style}}f.startNewLine(B);y.partForNextLine="";if(y.currentVoice===undefined||(y.currentVoice.staffNum===y.staves.length-1&&y.staves[y.currentVoice.staffNum].numVoices-1===y.currentVoice.index)){if(y.barNumbers===0){y.barNumOnNextNote=y.currBarNumber}}}var w=function(B,D){if(B.charAt(D)==="{"){var C=n.getBrackettedSubstring(B,D,1,"}");if(!C[2]){x("Missing the closing '}' while parsing grace note",B,D)}if(B[D+C[0]]===")"){C[0]++;C[1]+=")"}var A=[];var F=0;var G=false;while(F<C[1].length){var H=false;if(C[1].charAt(F)==="/"){H=true;F++}var E=i(C[1],F,{},false);if(E!==null){if(H){E.acciaccatura=true}A.push(E);if(G){E.endTie=true;G=false}if(E.startTie){G=true}F=E.endChar;delete E.endChar}else{if(C[1].charAt(F)===" "){if(A.length>0){A[A.length-1].end_beam=true}}else{x("Unknown character '"+C[1].charAt(F)+"' while parsing grace note",B,D)}F++}}if(A.length){return[C[0],A]}}return[0]};var q="ABCDEFGabcdefgxyzZ[]|^_{";var l=function(K){u.resolveTempo();y.is_in_header=false;var R=0;var Q=y.iChar;while(n.isWhiteSpace(K.charAt(R))&&R<K.length){R++}if(R===K.length||K.charAt(R)==="%"){return}var U=y.start_new_line;if(y.continueall===undefined){y.start_new_line=true}else{y.start_new_line=false}var H=0;var N=u.letter_to_body_header(K,R);if(N[0]>0){R+=N[0]}var C={};while(R<K.length){var D=R;if(K.charAt(R)==="%"){break}var B=u.letter_to_inline_header(K,R);if(B[0]>0){R+=B[0]}else{if(U){v();U=false}var W;while(1){W=n.eatWhiteSpace(K,R);if(W>0){R+=W}if(R>0&&K.charAt(R-1)==="\x12"){W=u.letter_to_body_header(K,R);if(W[0]>0){R=W[0];y.start_new_line=false}}W=e(K,R);if(W[0]>0){R+=W[0]}W=t(K,R);if(W[0]>0){if(!C.chord){C.chord=[]}var G=n.translateString(W[1]);G=G.replace(/;/g,"\n");var F=false;for(var L=0;L<C.chord.length;L++){if(C.chord[L].position===W[2]){F=true;C.chord[L].name+="\n"+G}}if(F===false){if(W[2]===null&&W[3]){C.chord.push({name:G,rel_position:W[3]})}else{C.chord.push({name:G,position:W[2]})}}R+=W[0];var M=n.skipWhiteSpace(K.substring(R));if(M>0){C.force_end_beam_last=true}R+=M}else{if(q.indexOf(K.charAt(R))===-1){W=h(K,R)}else{W=[0]}if(W[0]>0){if(W[1]===null){if(R+1<K.length){v()}}else{if(W[1].length>0){if(C.decoration===undefined){C.decoration=[]}C.decoration.push(W[1])}}R+=W[0]}else{W=w(K,R);if(W[0]>0){C.gracenotes=W[1];R+=W[0]}else{break}}}}W=r(K,R);if(W[0]>0){if(C.gracenotes!==undefined){C.rest={type:"spacer"};C.duration=0.125;f.appendElement("note",Q+R,Q+R+W[0],C);y.measureNotEmpty=true;C={}}var T={type:W[1]};if(T.type.length===0){x("Unknown bar type",K,R)}else{if(y.inEnding&&T.type!=="bar_thin"){T.endEnding=true;y.inEnding=false}if(W[2]){T.startEnding=W[2];if(y.inEnding){T.endEnding=true}y.inEnding=true}if(C.decoration!==undefined){T.decoration=C.decoration}if(C.chord!==undefined){T.chord=C.chord}if(T.startEnding&&y.barFirstEndingNum===undefined){y.barFirstEndingNum=y.currBarNumber}else{if(T.startEnding&&T.endEnding&&y.barFirstEndingNum){y.currBarNumber=y.barFirstEndingNum}else{if(T.endEnding){y.barFirstEndingNum=undefined}}}if(T.type!=="bar_invisible"&&y.measureNotEmpty){y.currBarNumber++;if(y.barNumbers&&y.currBarNumber%y.barNumbers===0){y.barNumOnNextNote=y.currBarNumber}}f.appendElement("bar",Q+R,Q+R+W[0],T);y.measureNotEmpty=false;C={}}R+=W[0]}else{if(K[R]==="&"){x("Overlay not yet supported",K,R);R++}else{W=o(K,R);if(W.consumed>0){if(W.startSlur!==undefined){C.startSlur=W.startSlur}if(W.triplet!==undefined){if(H>0){x("Can't nest triplets",K,R)}else{C.startTriplet=W.triplet;H=W.num_notes===undefined?W.triplet:W.num_notes}}R+=W.consumed}if(K.charAt(R)==="["){R++;var A=null;var P=false;while(!P){var J=i(K,R,{},false);if(J!==null){if(J.end_beam){C.end_beam=true;delete J.end_beam}if(C.pitches===undefined){C.duration=J.duration;C.pitches=[J]}else{C.pitches.push(J)}delete J.duration;if(y.inTieChord[C.pitches.length]){J.endTie=true;y.inTieChord[C.pitches.length]=undefined}if(J.startTie){y.inTieChord[C.pitches.length]=true}R=J.endChar;delete J.endChar}else{if(K.charAt(R)===" "){x("Spaces are not allowed in chords",K,R);R++}else{if(R<K.length&&K.charAt(R)==="]"){R++;if(y.next_note_duration!==0){C.duration=C.duration*y.next_note_duration;y.next_note_duration=0}if(y.inTie){window.ABCJS.parse.each(C.pitches,function(X){X.endTie=true});y.inTie=false}if(H>0){H--;if(H===0){C.endTriplet=true}}var I=false;while(R<K.length&&!I){switch(K.charAt(R)){case" ":case"\t":g(C);break;case")":if(C.endSlur===undefined){C.endSlur=1}else{C.endSlur++}break;case"-":window.ABCJS.parse.each(C.pitches,function(X){X.startTie={}});y.inTie=true;break;case">":case"<":var V=b(K,R);R+=V[0]-1;y.next_note_duration=V[2];A=V[1];break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"/":var E=n.getFraction(K,R);A=E.value;R=E.index;I=true;break;default:I=true;break}if(!I){R++}}}else{x("Expected ']' to end the chords",K,R)}if(C.pitches!==undefined){if(A!==null){C.duration=C.duration*A}if(y.barNumOnNextNote){C.barNumber=y.barNumOnNextNote;y.barNumOnNextNote=null }f.appendElement("note",Q+R,Q+R,C);y.measureNotEmpty=true;C={}}P=true}}}}else{var O={};var S=i(K,R,O,true);if(O.endTie!==undefined){y.inTie=true}if(S!==null){if(S.pitch!==undefined){C.pitches=[{}];if(S.accidental!==undefined){C.pitches[0].accidental=S.accidental}C.pitches[0].pitch=S.pitch;if(S.endSlur!==undefined){C.pitches[0].endSlur=S.endSlur}if(S.endTie!==undefined){C.pitches[0].endTie=S.endTie}if(S.startSlur!==undefined){C.pitches[0].startSlur=S.startSlur}if(C.startSlur!==undefined){C.pitches[0].startSlur=C.startSlur}if(S.startTie!==undefined){C.pitches[0].startTie=S.startTie}if(C.startTie!==undefined){C.pitches[0].startTie=C.startTie}}else{C.rest=S.rest;if(S.endSlur!==undefined){C.endSlur=S.endSlur}if(S.endTie!==undefined){C.rest.endTie=S.endTie}if(S.startSlur!==undefined){C.startSlur=S.startSlur}if(S.startTie!==undefined){C.rest.startTie=S.startTie}if(C.startTie!==undefined){C.rest.startTie=C.startTie}}if(S.chord!==undefined){C.chord=S.chord}if(S.duration!==undefined){C.duration=S.duration}if(S.decoration!==undefined){C.decoration=S.decoration}if(S.graceNotes!==undefined){C.graceNotes=S.graceNotes}delete C.startSlur;if(y.inTie){if(C.pitches!==undefined){C.pitches[0].endTie=true}else{C.rest.endTie=true}y.inTie=false}if(S.startTie||C.startTie){y.inTie=true}R=S.endChar;if(H>0){H--;if(H===0){C.endTriplet=true}}if(S.end_beam){g(C)}if(y.barNumOnNextNote){C.barNumber=y.barNumOnNextNote;y.barNumOnNextNote=null}f.appendElement("note",Q+D,Q+R,C);y.measureNotEmpty=true;C={}}}if(R===D){if(K.charAt(R)!==" "&&K.charAt(R)!=="`"){x("Unknown character ignored",K,R)}R++}}}}}};var k=function(A){var B=u.parseHeader(A);if(B.regular){l(B.str)}if(B.newline&&y.continueall===undefined){v()}if(B.words){m(f.getCurrentVoice(),A.substring(2))}if(B.symbols){d(f.getCurrentVoice(),A.substring(2))}if(B.recurse){k(B.str)}};this.parse=function(G,E){f.reset();if(E&&E.print){f.media="print"}y.reset();G=window.ABCJS.parse.gsub(G,"\r\n","\n");G=window.ABCJS.parse.gsub(G,"\r","\n");G+="\n";G=G.replace(/\n\\.*\n/g,"\n");var C=function(J,L,M){var I=" ";var K=M?I.substring(0,M.length):"";return L+" \x12"+K};G=G.replace(/\\([ \t]*)(%.*)*\n/g,C);var B=G.split("\n");if(window.ABCJS.parse.last(B).length===0){B.pop()}try{window.ABCJS.parse.each(B,function(I){if(E){if(E.header_only&&y.is_in_header===false){throw"normal_abort"}if(E.stop_on_warning&&y.warnings){throw"normal_abort"}}if(y.is_in_history){if(I.charAt(1)===":"){y.is_in_history=false;k(I)}else{f.addMetaText("history",n.translateString(n.stripComment(I)))}}else{if(y.inTextBlock){if(window.ABCJS.parse.startsWith(I,"%%endtext")){f.addText(y.textBlock);y.inTextBlock=false}else{if(window.ABCJS.parse.startsWith(I,"%%")){y.textBlock+=" "+I.substring(2)}else{y.textBlock+=" "+I}}}else{if(y.inPsBlock){if(window.ABCJS.parse.startsWith(I,"%%endps")){y.inPsBlock=false}else{y.textBlock+=" "+I}}else{k(I)}}}y.iChar+=I.length+1});var H=11*72;var D=8.5*72;switch(y.papersize){case"legal":H=14*72;D=8.5*72;break;case"A4":H=11.7*72;D=8.3*72;break}if(y.landscape){var A=H;H=D;D=A}f.cleanUp(D,H,y.barsperstaff,y.staffnonote)}catch(F){if(F!=="normal_abort"){throw F}}}};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.parse){window.ABCJS.parse={}}window.ABCJS.parse.parseDirective={};(function(){var b;var d;var a;var c;window.ABCJS.parse.parseDirective.initialize=function(h,f,g,e){b=h;d=f;a=g;c=e};window.ABCJS.parse.parseDirective.parseFontChangeLine=function(g){var e=g.split("$");if(e.length>1&&a.setfont){var h=[{text:e[0]}];for(var f=1;f<e.length;f++){if(e[f].charAt(0)==="0"){h.push({text:e[f].substring(1)})}else{if(e[f].charAt(0)==="1"&&a.setfont[1]){h.push({font:a.setfont[1],text:e[f].substring(1)})}else{if(e[f].charAt(0)==="2"&&a.setfont[2]){h.push({font:a.setfont[2],text:e[f].substring(1)})}else{if(e[f].charAt(0)==="3"&&a.setfont[3]){h.push({font:a.setfont[3],text:e[f].substring(1)})}else{if(e[f].charAt(0)==="4"&&a.setfont[4]){h.push({font:a.setfont[4],text:e[f].substring(1)})}else{h[h.length-1].text+="$"+e[f]}}}}}}if(h.length>1){return h}}return g};window.ABCJS.parse.parseDirective.addDirective=function(M){var V=function(t,ag){var p=b.getMeasurement(ag);if(p.used===0||ag.length!==0){return{error:'Directive "'+t+'" requires a measurement as a parameter.'}}return p.value};var R=function(t,ag){var p=b.getMeasurement(ag);if(p.used===0||ag.length!==0){return'Directive "'+t+'" requires a measurement as a parameter.'}c.formatting[t]=p.value;return null};var B=function(ah){var p={};var t=window.ABCJS.parse.last(ah);if(t.type==="number"){p.size=parseInt(t.token);ah.pop()}if(ah.length>0){var ag="";window.ABCJS.parse.each(ah,function(ai){if(ai.token!=="-"){if(ag.length>0){ag+=" "}ag+=ai.token}});p.font=ag}return p};var k=function(p,t){if(t.length===0){return'Directive "'+p+'" requires a font as a parameter.'}a[p]=B(t);return null};var q=function(p,t){if(t.length===0){return'Directive "'+p+'" requires a font as a parameter.'}c.formatting[p]=B(t);return null};var g=function(ah,ai,aj,ag,p){if(aj.length!==1||aj[0].type!=="number"){return'Directive "'+ai+'" requires a number as a parameter.'}var t=aj[0].intt;if(ag!==undefined&&t<ag){return'Directive "'+ai+'" requires a number greater than or equal to '+ag+" as a parameter."}if(p!==undefined&&t>p){return'Directive "'+ai+'" requires a number less than or equal to '+p+" as a parameter."}a[ah]=t;return null};var E=function(p,t,ag){var ah=g(p,t,ag,0,1);if(ah!==null){return ah}a[p]=(a[p]===1);return null};var K=b.tokenize(M,0,M.length);if(K.length===0||K[0].type!=="alpha"){return null}var f=M.substring(M.indexOf(K[0].token)+K[0].token.length);f=b.stripComment(f);var Z=K.shift().token.toLowerCase();var ac;var j="";switch(Z){case"bagpipes":c.formatting.bagpipes=true;break;case"landscape":a.landscape=true;break;case"papersize":a.papersize=f;break;case"slurgraces":c.formatting.slurgraces=true;break;case"stretchlast":c.formatting.stretchlast=true;break;case"titlecaps":a.titlecaps=true;break;case"titleleft":c.formatting.titleleft=true;break;case"measurebox":c.formatting.measurebox=true;break;case"botmargin":case"botspace":case"composerspace":case"indent":case"leftmargin":case"linesep":case"musicspace":case"partsspace":case"pageheight":case"pagewidth":case"rightmargin":case"staffsep":case"staffwidth":case"subtitlespace":case"sysstaffsep":case"systemsep":case"textspace":case"titlespace":case"topmargin":case"topspace":case"vocalspace":case"wordsspace":return R(Z,K);case"vskip":var i=V(Z,K);if(i.error){return i.error}c.addSpacing(i);return null;case"scale":j="";window.ABCJS.parse.each(K,function(p){j+=p.token});ac=parseFloat(j);if(isNaN(ac)||ac===0){return'Directive "'+Z+'" requires a number as a parameter.'}c.formatting.scale=ac;break;case"sep":if(K.length===0){c.addSeparator()}else{var Q=b.getMeasurement(K);if(Q.used===0){return'Directive "'+Z+'" requires 3 numbers: space above, space below, length of line' }var J=Q.value;Q=b.getMeasurement(K);if(Q.used===0){return'Directive "'+Z+'" requires 3 numbers: space above, space below, length of line'}var af=Q.value;Q=b.getMeasurement(K);if(Q.used===0||K.length!==0){return'Directive "'+Z+'" requires 3 numbers: space above, space below, length of line'}var A=Q.value;c.addSeparator(J,af,A)}break;case"barsperstaff":j=g("barsperstaff",Z,K);if(j!==null){return j}break;case"staffnonote":j=E("staffnonote",Z,K);if(j!==null){return j}break;case"printtempo":j=E("printTempo",Z,K);if(j!==null){return j}break;case"measurenb":case"barnumbers":j=g("barNumbers",Z,K);if(j!==null){return j}break;case"begintext":a.inTextBlock=true;break;case"continueall":a.continueall=true;break;case"beginps":a.inPsBlock=true;d("Postscript ignored",M,0);break;case"deco":if(f.length>0){a.ignoredDecorations.push(f.substring(0,f.indexOf(" ")))}d("Decoration redefinition ignored",M,0);break;case"text":var W=b.translateString(f);c.addText(window.ABCJS.parse.parseDirective.parseFontChangeLine(W));break;case"center":var e=b.translateString(f);c.addCentered(window.ABCJS.parse.parseDirective.parseFontChangeLine(e));break;case"font":break;case"setfont":var y=b.tokenize(f,0,f.length);var G=false;if(y.length>=4){if(y[0].token==="-"&&y[1].type==="number"){var h=parseInt(y[1].token);if(h>=1&&h<=4){if(!a.setfont){a.setfont=[]}var D=y.pop();if(D.type==="number"){D=parseInt(D.token);var u="";for(var w=2;w<y.length;w++){u+=y[w].token}a.setfont[h]={font:u,size:D};G=true}}}}if(!G){return"Bad parameters: "+Z}break;case"gchordfont":case"partsfont":case"vocalfont":case"textfont":return k(Z,K);case"barlabelfont":case"barnumberfont":case"composerfont":case"subtitlefont":case"tempofont":case"titlefont":case"voicefont":return q(Z,K);case"barnumfont":return q("barnumberfont",K);case"staves":case"score":a.score_is_present=true;var ae=function(aj,ag,ai,ah,t){if(ag||a.staves.length===0){a.staves.push({index:a.staves.length,numVoices:0})}var p=window.ABCJS.parse.last(a.staves);if(ai!==undefined){p.bracket=ai}if(ah!==undefined){p.brace=ah}if(t){p.connectBarLines="end"}if(a.voices[aj]===undefined){a.voices[aj]={staffNum:p.index,index:p.numVoices};p.numVoices++}};var O=false;var Y=false;var n=false;var P=false;var l=false;var o=false;var m=false;var s;var ad=function(){m=true;if(s){var p="start";if(s.staffNum>0){if(a.staves[s.staffNum-1].connectBarLines==="start"||a.staves[s.staffNum-1].connectBarLines==="continue"){p="continue"}}a.staves[s.staffNum].connectBarLines=p}};while(K.length){var T=K.shift();switch(T.token){case"(":if(O){d("Can't nest parenthesis in %%score",M,T.start)}else{O=true;P=true}break;case")":if(!O||P){d("Unexpected close parenthesis in %%score",M,T.start)}else{O=false}break;case"[":if(Y){d("Can't nest brackets in %%score",M,T.start)}else{Y=true;l=true}break;case"]":if(!Y||l){d("Unexpected close bracket in %%score",M,T.start)}else{Y=false;a.staves[s.staffNum].bracket="end"}break;case"{":if(n){d("Can't nest braces in %%score",M,T.start)}else{n=true;o=true}break;case"}":if(!n||o){d("Unexpected close brace in %%score",M,T.start)}else{n=false;a.staves[s.staffNum].brace="end"}break;case"|":ad();break;default:var C="";while(T.type==="alpha"||T.type==="number"){C+=T.token;if(T.continueId){T=K.shift()}else{break}}var I=!O||P;var L=l?"start":Y?"continue":undefined;var z=o?"start":n?"continue":undefined;ae(C,I,L,z,m);P=false;l=false;o=false;m=false;s=a.voices[C];if(Z==="staves"){ad()}break}}break;case"newpage":var v=b.getInt(f);c.addNewPage(v.digits===0?-1:v.value);break;case"abc-copyright":case"abc-creator":case"abc-version":case"abc-charset":case"abc-edited-by":c.addMetaText(Z,f);break;case"header":case"footer":var S=b.getMeat(f,0,f.length);S=f.substring(S.start,S.end);if(S.charAt(0)==='"'&&S.charAt(S.length-1)==='"'){S=S.substring(1,S.length-2)}var F=S.split("\t");var r={};if(F.length===1){r={left:"",center:F[0],right:""}}else{if(F.length===2){r={left:F[0],center:F[1],right:""}}else{r={left:F[0],center:F[1],right:F[2]}}}if(F.length>3){d("Too many tabs in "+Z+": "+F.length+" found.",f,0)}c.addMetaTextObj(Z,r);break;case"midi":var X=b.tokenize(f,0,f.length);if(X.length>0&&X[0].token==="="){X.shift()}if(X.length===0){d("Expected midi command",f,0)}else{var x=function(ag){if(ag.length>0){var ah=ag.shift();var ai=ah.token;if(ah.type==="number"){ai=ah.intt}return ai}else{return null}};if(c.formatting[Z]===undefined){c.formatting[Z]={}}var H=X.shift().token;var N=true;if(H==="program"){var ab=x(X);if(ab){var aa=x(X);if(aa){N={channel:ab,program:aa}}else{N={program:ab}}}}else{var U=x(X);if(U!==null){N=U}}c.formatting[Z][H]=N}break;case"playtempo":case"auquality":case"continuous":case"nobarcheck":c.formatting[Z]=f;break;default:return"Unknown directive: "+Z}return null}})();if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.parse){window.ABCJS.parse={}}window.ABCJS.parse.ParseHeader=function(c,e,a,d){window.ABCJS.parse.parseKeyVoice.initialize(c,e,a,d);window.ABCJS.parse.parseDirective.initialize(c,e,a,d);this.setTitle=function(f){if(a.hasMainTitle){d.addSubtitle(c.translateString(c.stripComment(f)))}else{d.addMetaText("title",c.translateString(c.theReverser(c.stripComment(f))));a.hasMainTitle=true}};this.setMeter=function(n){n=c.stripComment(n);if(n==="C"){if(a.havent_set_length===true){a.default_length=0.125}return{type:"common_time"}}else{if(n==="C|"){if(a.havent_set_length===true){a.default_length=0.125}return{type:"cut_time"}}else{if(n==="o"){if(a.havent_set_length===true){a.default_length=0.125}return{type:"tempus_perfectum"}}else{if(n==="c"){if(a.havent_set_length===true){a.default_length=0.125}return{type:"tempus_imperfectum"}}else{if(n==="o."){if(a.havent_set_length===true){a.default_length=0.125}return{type:"tempus_perfectum_prolatio"}}else{if(n==="c."){if(a.havent_set_length===true){a.default_length=0.125}return{type:"tempus_imperfectum_prolatio"}}else{if(n.length===0||n.toLowerCase()==="none"){if(a.havent_set_length===true){a.default_length=0.125}return null}else{var k=c.tokenize(n,0,n.length);try{var j=function(){var p={value:0,num:""};var o=k.shift();if(o.token==="("){o=k.shift()}while(1){if(o.type!=="number"){throw"Expected top number of meter"}p.value+=parseInt(o.token);p.num+=o.token;if(k.length===0||k[0].token==="/"){return p}o=k.shift();if(o.token===")"){if(k.length===0||k[0].token==="/"){return p}throw"Unexpected paren in meter"}if(o.token!=="."&&o.token!=="+"){throw"Expected top number of meter"}p.num+=o.token;if(k.length===0){throw"Expected top number of meter"}o=k.shift()}return p};var f=function(){var p=j();if(k.length===0){return p}var o=k.shift();if(o.token!=="/"){throw"Expected slash in meter"}o=k.shift();if(o.type!=="number"){throw"Expected bottom number of meter"}p.den=o.token;p.value=p.value/parseInt(p.den);return p};if(k.length===0){throw"Expected meter definition in M: line"}var g={type:"specified",value:[]};var l=0;while(1){var i=f();l+=i.value;var m={num:i.num};if(i.den!==undefined){m.den=i.den}g.value.push(m);if(k.length===0){break}}if(a.havent_set_length===true){a.default_length=l<0.75?0.0625:0.125 }return g}catch(h){e(h,n,0)}}}}}}}}return null};this.calcTempo=function(f){var h=1/4;if(a.meter&&a.meter.type==="specified"){h=1/parseInt(a.meter.value[0].den)}else{if(a.origMeter&&a.origMeter.type==="specified"){h=1/parseInt(a.origMeter.value[0].den)}}for(var g=0;g<f.duration;g++){f.duration[g]=h*f.duration[g]}return f};this.resolveTempo=function(){if(a.tempo){this.calcTempo(a.tempo);d.metaText.tempo=a.tempo;delete a.tempo}};this.addUserDefinition=function(g,l,f){var h=g.indexOf("=",l);if(h===-1){e("Need an = in a macro definition",g,l);return}var j=window.ABCJS.parse.strip(g.substring(l,h));var k=window.ABCJS.parse.strip(g.substring(h+1));if(j.length!==1){e("Macro definitions can only be one character",g,l);return}var i="HIJKLMNOPQRSTUVWXYhijklmnopqrstuvw~";if(i.indexOf(j)===-1){e("Macro definitions must be H-Y, h-w, or tilde",g,l);return}if(k.length===0){e("Missing macro definition",g,l);return}if(a.macros===undefined){a.macros={}}a.macros[j]=k};this.setDefaultLength=function(h,l,g){var f=window.ABCJS.parse.gsub(h.substring(l,g)," ","");var k=f.split("/");if(k.length===2){var j=parseInt(k[0]);var i=parseInt(k[1]);if(i>0){a.default_length=j/i;a.havent_set_length=false}}};this.setTempo=function(o,f,i){try{var l=c.tokenize(o,f,i);if(l.length===0){throw"Missing parameter in Q: field"}var j={};var n=true;var h=l.shift();if(h.type==="quote"){j.preString=h.token;h=l.shift();if(l.length===0){return{type:"immediate",tempo:j}}}if(h.type==="alpha"&&h.token==="C"){if(l.length===0){throw"Missing tempo after C in Q: field"}h=l.shift();if(h.type==="punct"&&h.token==="="){if(l.length===0){throw"Missing tempo after = in Q: field"}h=l.shift();if(h.type!=="number"){throw"Expected number after = in Q: field"}j.duration=[1];j.bpm=parseInt(h.token)}else{if(h.type==="number"){j.duration=[parseInt(h.token)];if(l.length===0){throw"Missing = after duration in Q: field"}h=l.shift();if(h.type!=="punct"||h.token!=="="){throw"Expected = after duration in Q: field"}if(l.length===0){throw"Missing tempo after = in Q: field"}h=l.shift();if(h.type!=="number"){throw"Expected number after = in Q: field"}j.bpm=parseInt(h.token)}else{throw"Expected number or equal after C in Q: field"}}}else{if(h.type==="number"){var k=parseInt(h.token);if(l.length===0||l[0].type==="quote"){j.duration=[1];j.bpm=k}else{n=false;h=l.shift();if(h.type!=="punct"&&h.token!=="/"){throw"Expected fraction in Q: field"}h=l.shift();if(h.type!=="number"){throw"Expected fraction in Q: field"}var m=parseInt(h.token);j.duration=[k/m];while(l.length>0&&l[0].token!=="="&&l[0].type!=="quote"){h=l.shift();if(h.type!=="number"){throw"Expected fraction in Q: field"}k=parseInt(h.token);h=l.shift();if(h.type!=="punct"&&h.token!=="/"){throw"Expected fraction in Q: field"}h=l.shift();if(h.type!=="number"){throw"Expected fraction in Q: field"}m=parseInt(h.token);j.duration.push(k/m)}h=l.shift();if(h.type!=="punct"&&h.token!=="="){throw"Expected = in Q: field"}h=l.shift();if(h.type!=="number"){throw"Expected tempo in Q: field"}j.bpm=parseInt(h.token)}}else{throw"Unknown value in Q: field"}}if(l.length!==0){h=l.shift();if(h.type==="quote"){j.postString=h.token;h=l.shift()}if(l.length!==0){throw"Unexpected string at end of Q: field"}}if(a.printTempo===false){j.suppress=true}return{type:n?"delaySet":"immediate",tempo:j}}catch(g){e(g,o,f);return{type:"none"}}};this.letter_to_inline_header=function(h,k){var g=c.eatWhiteSpace(h,k);k+=g;if(h.length>=k+5&&h.charAt(k)==="["&&h.charAt(k+2)===":"){var n=h.indexOf("]",k);switch(h.substring(k,k+3)){case"[I:":var l=window.ABCJS.parse.parseDirective.addDirective(h.substring(k+3,n));if(l){e(l,h,k)}return[n-k+1+g];case"[M:":var m=this.setMeter(h.substring(k+3,n));if(d.hasBeginMusic()&&m){d.appendStartingElement("meter",-1,-1,m)}else{a.meter=m}return[n-k+1+g];case"[K:":var f=window.ABCJS.parse.parseKeyVoice.parseKey(h.substring(k+3,n));if(f.foundClef&&d.hasBeginMusic()){d.appendStartingElement("clef",-1,-1,a.clef)}if(f.foundKey&&d.hasBeginMusic()){d.appendStartingElement("key",-1,-1,window.ABCJS.parse.parseKeyVoice.fixKey(a.clef,a.key))}return[n-k+1+g];case"[P:":d.appendElement("part",-1,-1,{title:h.substring(k+3,n)});return[n-k+1+g];case"[L:":this.setDefaultLength(h,k+3,n);return[n-k+1+g];case"[Q:":if(n>0){var j=this.setTempo(h,k+3,n);if(j.type==="delaySet"){d.appendElement("tempo",-1,-1,this.calcTempo(j.tempo))}else{if(j.type==="immediate"){d.appendElement("tempo",-1,-1,j.tempo)}}return[n-k+1+g,h.charAt(k+1),h.substring(k+3,n)]}break;case"[V:":if(n>0){window.ABCJS.parse.parseKeyVoice.parseVoice(h,k+3,n);return[n-k+1+g,h.charAt(k+1),h.substring(k+3,n)]}break;default:}}return[0]};this.letter_to_body_header=function(g,j){if(g.length>=j+3){switch(g.substring(j,j+2)){case"I:":var k=window.ABCJS.parse.parseDirective.addDirective(g.substring(j+2));if(k){e(k,g,j)}return[g.length];case"M:":var l=this.setMeter(g.substring(j+2));if(d.hasBeginMusic()&&l){d.appendStartingElement("meter",-1,-1,l)}return[g.length];case"K:":var f=window.ABCJS.parse.parseKeyVoice.parseKey(g.substring(j+2));if(f.foundClef&&d.hasBeginMusic()){d.appendStartingElement("clef",-1,-1,a.clef)}if(f.foundKey&&d.hasBeginMusic()){d.appendStartingElement("key",-1,-1,window.ABCJS.parse.parseKeyVoice.fixKey(a.clef,a.key))}return[g.length];case"P:":if(d.hasBeginMusic()){d.appendElement("part",-1,-1,{title:g.substring(j+2)})}return[g.length];case"L:":this.setDefaultLength(g,j+2,g.length);return[g.length];case"Q:":var m=g.indexOf("\x12",j+2);if(m===-1){m=g.length}var h=this.setTempo(g,j+2,m);if(h.type==="delaySet"){d.appendElement("tempo",-1,-1,this.calcTempo(h.tempo))}else{if(h.type==="immediate"){d.appendElement("tempo",-1,-1,h.tempo)}}return[m,g.charAt(j),window.ABCJS.parse.strip(g.substring(j+2))];case"V:":window.ABCJS.parse.parseKeyVoice.parseVoice(g,2,g.length);return[g.length,g.charAt(j),window.ABCJS.parse(g.substring(j+2))];default:}}return[0]};var b={A:"author",B:"book",C:"composer",D:"discography",F:"url",G:"group",I:"instruction",N:"notes",O:"origin",R:"rhythm",S:"source",W:"unalignedWords",Z:"transcription"};this.parseHeader=function(g){if(window.ABCJS.parse.startsWith(g,"%%")){var j=window.ABCJS.parse.parseDirective.addDirective(g.substring(2));if(j){e(j,g,2)}return{}}g=c.stripComment(g);if(g.length===0){return{}}if(g.length>=2){if(g.charAt(1)===":"){var i="";if(g.indexOf("\x12")>=0&&g.charAt(0)!=="w"){i=g.substring(g.indexOf("\x12")+1);g=g.substring(0,g.indexOf("\x12"))}var k=b[g.charAt(0)];if(k!==undefined){if(k==="unalignedWords"){d.addMetaTextArray(k,window.ABCJS.parse.parseDirective.parseFontChangeLine(c.translateString(c.stripComment(g.substring(2)))))}else{d.addMetaText(k,c.translateString(c.stripComment(g.substring(2))))}return{}}else{switch(g.charAt(0)){case"H":d.addMetaText("history",c.translateString(c.stripComment(g.substring(2))));a.is_in_history=true;break;case"K":this.resolveTempo();var f=window.ABCJS.parse.parseKeyVoice.parseKey(g.substring(2));if(!a.is_in_header&&d.hasBeginMusic()){if(f.foundClef){d.appendStartingElement("clef",-1,-1,a.clef) }if(f.foundKey){d.appendStartingElement("key",-1,-1,window.ABCJS.parse.parseKeyVoice.fixKey(a.clef,a.key))}}a.is_in_header=false;break;case"L":this.setDefaultLength(g,2,g.length);break;case"M":a.origMeter=a.meter=this.setMeter(g.substring(2));break;case"P":if(a.is_in_header){d.addMetaText("partOrder",c.translateString(c.stripComment(g.substring(2))))}else{a.partForNextLine=c.translateString(c.stripComment(g.substring(2)))}break;case"Q":var h=this.setTempo(g,2,g.length);if(h.type==="delaySet"){a.tempo=h.tempo}else{if(h.type==="immediate"){d.metaText.tempo=h.tempo}}break;case"T":this.setTitle(g.substring(2));break;case"U":this.addUserDefinition(g,2,g.length);break;case"V":window.ABCJS.parse.parseKeyVoice.parseVoice(g,2,g.length);if(!a.is_in_header){return{newline:true}}break;case"s":return{symbols:true};case"w":return{words:true};case"X":break;case"E":case"m":e("Ignored header",g,0);break;default:if(i.length){i="\x12"+i}return{regular:true,str:g+i}}}if(i.length>0){return{recurse:true,str:i}}return{}}}return{regular:true,str:g}}};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.parse){window.ABCJS.parse={}}window.ABCJS.parse.parseKeyVoice={};(function(){var h;var e;var b;var d;window.ABCJS.parse.parseKeyVoice.initialize=function(m,k,l,j){h=m;e=k;b=l;d=j};window.ABCJS.parse.parseKeyVoice.standardKey=function(w){var m={acc:"sharp",note:"f"};var r={acc:"sharp",note:"c"};var v={acc:"sharp",note:"g"};var k={acc:"sharp",note:"d"};var p={acc:"sharp",note:"A"};var u={acc:"sharp",note:"e"};var y={acc:"sharp",note:"B"};var t={acc:"flat",note:"B"};var s={acc:"flat",note:"e"};var q={acc:"flat",note:"A"};var o={acc:"flat",note:"d"};var n={acc:"flat",note:"G"};var l={acc:"flat",note:"c"};var j={acc:"flat",note:"F"};var x={"C#":[m,r,v,k,p,u,y],"A#m":[m,r,v,k,p,u,y],"G#Mix":[m,r,v,k,p,u,y],"D#Dor":[m,r,v,k,p,u,y],"E#Phr":[m,r,v,k,p,u,y],"F#Lyd":[m,r,v,k,p,u,y],"B#Loc":[m,r,v,k,p,u,y],"F#":[m,r,v,k,p,u],"D#m":[m,r,v,k,p,u],"C#Mix":[m,r,v,k,p,u],"G#Dor":[m,r,v,k,p,u],"A#Phr":[m,r,v,k,p,u],BLyd:[m,r,v,k,p,u],"E#Loc":[m,r,v,k,p,u],B:[m,r,v,k,p],"G#m":[m,r,v,k,p],"F#Mix":[m,r,v,k,p],"C#Dor":[m,r,v,k,p],"D#Phr":[m,r,v,k,p],ELyd:[m,r,v,k,p],"A#Loc":[m,r,v,k,p],E:[m,r,v,k],"C#m":[m,r,v,k],BMix:[m,r,v,k],"F#Dor":[m,r,v,k],"G#Phr":[m,r,v,k],ALyd:[m,r,v,k],"D#Loc":[m,r,v,k],A:[m,r,v],"F#m":[m,r,v],EMix:[m,r,v],BDor:[m,r,v],"C#Phr":[m,r,v],DLyd:[m,r,v],"G#Loc":[m,r,v],D:[m,r],Bm:[m,r],AMix:[m,r],EDor:[m,r],"F#Phr":[m,r],GLyd:[m,r],"C#Loc":[m,r],G:[m],Em:[m],DMix:[m],ADor:[m],BPhr:[m],CLyd:[m],"F#Loc":[m],C:[],Am:[],GMix:[],DDor:[],EPhr:[],FLyd:[],BLoc:[],F:[t],Dm:[t],CMix:[t],GDor:[t],APhr:[t],BbLyd:[t],ELoc:[t],Bb:[t,s],Gm:[t,s],FMix:[t,s],CDor:[t,s],DPhr:[t,s],EbLyd:[t,s],ALoc:[t,s],Eb:[t,s,q],Cm:[t,s,q],BbMix:[t,s,q],FDor:[t,s,q],GPhr:[t,s,q],AbLyd:[t,s,q],DLoc:[t,s,q],Ab:[t,s,q,o],Fm:[t,s,q,o],EbMix:[t,s,q,o],BbDor:[t,s,q,o],CPhr:[t,s,q,o],DbLyd:[t,s,q,o],GLoc:[t,s,q,o],Db:[t,s,q,o,n],Bbm:[t,s,q,o,n],AbMix:[t,s,q,o,n],EbDor:[t,s,q,o,n],FPhr:[t,s,q,o,n],GbLyd:[t,s,q,o,n],CLoc:[t,s,q,o,n],Gb:[t,s,q,o,n,l],Ebm:[t,s,q,o,n,l],DbMix:[t,s,q,o,n,l],AbDor:[t,s,q,o,n,l],BbPhr:[t,s,q,o,n,l],CbLyd:[t,s,q,o,n,l],FLoc:[t,s,q,o,n,l],Cb:[t,s,q,o,n,l,j],Abm:[t,s,q,o,n,l,j],GbMix:[t,s,q,o,n,l,j],DbDor:[t,s,q,o,n,l,j],EbPhr:[t,s,q,o,n,l,j],FbLyd:[t,s,q,o,n,l,j],BbLoc:[t,s,q,o,n,l,j],"A#":[t,s],"B#":[],"D#":[t,s,q],"E#":[t],"G#":[t,s,q,o],Gbm:[m,r,v,k,p,u,y]};return x[w]};var i=function(l,j){var k=0;switch(l){case"treble":case"perc":case"none":case"treble+8":case"treble-8":break;case"bass3":case"bass":case"bass+8":case"bass-8":case"bass+16":case"bass-16":k=-12;break;case"tenor":k=-8;break;case"alto2":case"alto1":case"alto":case"alto+8":case"alto-8":k=-6;break}return k+j};window.ABCJS.parse.parseKeyVoice.deepCopyKey=function(k){var j={accidentals:[],root:k.root,acc:k.acc,mode:k.mode};window.ABCJS.parse.each(k.accidentals,function(l){j.accidentals.push(window.ABCJS.parse.clone(l))});return j};var c={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11};window.ABCJS.parse.parseKeyVoice.addPosToKey=function(l,k){var j=l.verticalPos;window.ABCJS.parse.each(k.accidentals,function(m){var n=c[m.note];n=n-j;m.verticalPos=n});if(k.impliedNaturals){window.ABCJS.parse.each(k.impliedNaturals,function(m){var n=c[m.note];n=n-j;m.verticalPos=n})}if(j<-10){window.ABCJS.parse.each(k.accidentals,function(m){m.verticalPos-=7;if(m.verticalPos>=11||(m.verticalPos===10&&m.acc==="flat")){m.verticalPos-=7}if(m.note==="A"&&m.acc==="sharp"){m.verticalPos-=7}if((m.note==="G"||m.note==="F")&&m.acc==="flat"){m.verticalPos-=7}});if(k.impliedNaturals){window.ABCJS.parse.each(k.impliedNaturals,function(m){m.verticalPos-=7;if(m.verticalPos>=11||(m.verticalPos===10&&m.acc==="flat")){m.verticalPos-=7}if(m.note==="A"&&m.acc==="sharp"){m.verticalPos-=7}if((m.note==="G"||m.note==="F")&&m.acc==="flat"){m.verticalPos-=7}})}}else{if(j<-4){window.ABCJS.parse.each(k.accidentals,function(m){m.verticalPos-=7;if(j===-8&&(m.note==="f"||m.note==="g")&&m.acc==="sharp"){m.verticalPos-=7}});if(k.impliedNaturals){window.ABCJS.parse.each(k.impliedNaturals,function(m){m.verticalPos-=7;if(j===-8&&(m.note==="f"||m.note==="g")&&m.acc==="sharp"){m.verticalPos-=7}})}}else{if(j>=7){window.ABCJS.parse.each(k.accidentals,function(m){m.verticalPos+=7});if(k.impliedNaturals){window.ABCJS.parse.each(k.impliedNaturals,function(m){m.verticalPos+=7})}}}}};window.ABCJS.parse.parseKeyVoice.fixKey=function(l,j){var k=window.ABCJS.parse.clone(j);window.ABCJS.parse.parseKeyVoice.addPosToKey(l,k);return k};var a=function(l){var j=c[l.charAt(0)];for(var k=1;k<l.length;k++){if(l.charAt(k)===","){j-=7}else{if(l.charAt(k)===","){j+=7}else{break}}}return{mid:j-6,str:l.substring(k)}};var g=function(j){for(var k=0;k<j.length;k++){if(j[k].note==="b"){j[k].note="B"}else{if(j[k].note==="a"){j[k].note="A"}else{if(j[k].note==="F"){j[k].note="f"}else{if(j[k].note==="E"){j[k].note="e"}else{if(j[k].note==="D"){j[k].note="d"}else{if(j[k].note==="C"){j[k].note="c"}else{if(j[k].note==="G"&&j[k].acc==="sharp"){j[k].note="g"}else{if(j[k].note==="g"&&j[k].acc==="flat"){j[k].note="G"}}}}}}}}}};window.ABCJS.parse.parseKeyVoice.parseKey=function(x){if(x.length===0){x="none"}var w=h.tokenize(x,0,x.length);var D={};switch(w[0].token){case"HP":window.ABCJS.parse.parseDirective.addDirective("bagpipes");b.key={root:"HP",accidentals:[],acc:"",mode:""};D.foundKey=true;w.shift();break;case"Hp":window.ABCJS.parse.parseDirective.addDirective("bagpipes");b.key={root:"Hp",accidentals:[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}],acc:"",mode:""};D.foundKey=true;w.shift();break;case"none":b.key={root:"none",accidentals:[],acc:"",mode:""};D.foundKey=true;w.shift();break;default:var p=h.getKeyPitch(w[0].token);if(p.len>0){D.foundKey=true;var n="";var v="";if(w[0].token.length>1){w[0].token=w[0].token.substring(1)}else{w.shift()}var E=p.token;if(w.length>0){var l=h.getSharpFlat(w[0].token);if(l.len>0){if(w[0].token.length>1){w[0].token=w[0].token.substring(1)}else{w.shift()}E+=l.token;n=l.token }if(w.length>0){var C=h.getMode(w[0].token);if(C.len>0){w.shift();E+=C.token;v=C.token}}}var s=window.ABCJS.parse.parseKeyVoice.deepCopyKey(b.key);b.key=window.ABCJS.parse.parseKeyVoice.deepCopyKey({accidentals:window.ABCJS.parse.parseKeyVoice.standardKey(E)});b.key.root=p.token;b.key.acc=n;b.key.mode=v;if(s){var m;for(var z=0;z<b.key.accidentals.length;z++){for(m=0;m<s.accidentals.length;m++){if(s.accidentals[m].note&&b.key.accidentals[z].note.toLowerCase()===s.accidentals[m].note.toLowerCase()){s.accidentals[m].note=null}}}for(m=0;m<s.accidentals.length;m++){if(s.accidentals[m].note){if(!b.key.impliedNaturals){b.key.impliedNaturals=[]}b.key.impliedNaturals.push({acc:"natural",note:s.accidentals[m].note})}}}}break}if(w.length===0){return D}if(w[0].token==="exp"){w.shift()}if(w.length===0){return D}if(w[0].token==="oct"){w.shift()}if(w.length===0){return D}var t=h.getKeyAccidentals2(w);if(t.warn){e(t.warn,x,0)}if(t.accs){if(!D.foundKey){D.foundKey=true;b.key={root:"none",acc:"",mode:"",accidentals:[]}}g(t.accs);for(var B=0;B<t.accs.length;B++){var u=false;for(var A=0;A<b.key.accidentals.length&&!u;A++){if(b.key.accidentals[A].note===t.accs[B].note){u=true;b.key.accidentals[A].acc=t.accs[B].acc}}if(!u){b.key.accidentals.push(t.accs[B]);if(b.key.impliedNaturals){for(var q=0;q<b.key.impliedNaturals.length;q++){if(b.key.impliedNaturals[q].note===t.accs[B].note){b.key.impliedNaturals.splice(q,1)}}}}}}var o;while(w.length>0){switch(w[0].token){case"m":case"middle":w.shift();if(w.length===0){e("Expected = after middle",x,0);return D}o=w.shift();if(o.token!=="="){e("Expected = after middle",x,o.start);break}if(w.length===0){e("Expected parameter after middle=",x,0);return D}var r=h.getPitchFromTokens(w);if(r.warn){e(r.warn,x,0)}if(r.position){b.clef.verticalPos=r.position-6}break;case"transpose":w.shift();if(w.length===0){e("Expected = after transpose",x,0);return D}o=w.shift();if(o.token!=="="){e("Expected = after transpose",x,o.start);break}if(w.length===0){e("Expected parameter after transpose=",x,0);return D}if(w[0].type!=="number"){e("Expected number after transpose",x,w[0].start);break}b.clef.transpose=w[0].intt;w.shift();break;case"stafflines":w.shift();if(w.length===0){e("Expected = after stafflines",x,0);return D}o=w.shift();if(o.token!=="="){e("Expected = after stafflines",x,o.start);break}if(w.length===0){e("Expected parameter after stafflines=",x,0);return D}if(w[0].type!=="number"){e("Expected number after stafflines",x,w[0].start);break}b.clef.stafflines=w[0].intt;w.shift();break;case"staffscale":w.shift();if(w.length===0){e("Expected = after staffscale",x,0);return D}o=w.shift();if(o.token!=="="){e("Expected = after staffscale",x,o.start);break}if(w.length===0){e("Expected parameter after staffscale=",x,0);return D}if(w[0].type!=="number"){e("Expected number after staffscale",x,w[0].start);break}b.clef.staffscale=w[0].floatt;w.shift();break;case"style":w.shift();if(w.length===0){e("Expected = after style",x,0);return D}o=w.shift();if(o.token!=="="){e("Expected = after style",x,o.start);break}if(w.length===0){e("Expected parameter after style=",x,0);return D}switch(w[0].token){case"normal":case"harmonic":case"rhythm":case"x":b.style=w[0].token;w.shift();break;default:e("error parsing style element: "+w[0].token,x,w[0].start);break}break;case"clef":w.shift();if(w.length===0){e("Expected = after clef",x,0);return D}o=w.shift();if(o.token!=="="){e("Expected = after clef",x,o.start);break}if(w.length===0){e("Expected parameter after clef=",x,0);return D}case"treble":case"bass":case"alto":case"tenor":case"perc":var y=w.shift();switch(y.token){case"treble":case"tenor":case"alto":case"bass":case"perc":case"none":break;case"C":y.token="alto";break;case"F":y.token="bass";break;case"G":y.token="treble";break;case"c":y.token="alto";break;case"f":y.token="bass";break;case"g":y.token="treble";break;default:e("Expected clef name. Found "+y.token,x,y.start);break}if(w.length>0&&w[0].type==="number"){y.token+=w[0].token;w.shift()}if(w.length>1&&(w[0].token==="-"||w[0].token==="+")&&w[1].token==="8"){y.token+=w[0].token+w[1].token;w.shift();w.shift()}b.clef={type:y.token,verticalPos:i(y.token,0)};D.foundClef=true;break;default:e("Unknown parameter: "+w[0].token,x,w[0].start);w.shift()}}return D};var f=function(j){b.currentVoice=b.voices[j];d.setCurrentVoice(b.currentVoice.staffNum,b.currentVoice.index)};window.ABCJS.parse.parseKeyVoice.parseVoice=function(m,w,x){var B=h.getMeat(m,w,x);var k=B.start;var j=B.end;var q=h.getToken(m,k,j);if(q.length===0){e("Expected a voice id",m,k);return}var z=false;if(b.voices[q]===undefined){b.voices[q]={};z=true;if(b.score_is_present){e("Can't have an unknown V: id when the %score directive is present",m,k)}}k+=q.length;k+=h.eatWhiteSpace(m,k);var o={startStaff:z};var C=function(v){var s=h.getVoiceToken(m,k,j);if(s.warn!==undefined){e("Expected value for "+v+" in voice: "+s.warn,m,k)}else{if(s.token.length===0&&m.charAt(k)!=='"'){e("Expected value for "+v+" in voice",m,k)}else{o[v]=s.token}}k+=s.len};var y=function(E,v,D){var s=h.getVoiceToken(m,k,j);if(s.warn!==undefined){e("Expected value for "+v+" in voice: "+s.warn,m,k)}else{if(s.token.length===0&&m.charAt(k)!=='"'){e("Expected value for "+v+" in voice",m,k)}else{if(D==="number"){s.token=parseFloat(s.token)}b.voices[E][v]=s.token}}k+=s.len};while(k<j){var l=h.getVoiceToken(m,k,j);k+=l.len;if(l.warn){e("Error parsing voice: "+l.warn,m,k)}else{var t=null;switch(l.token){case"clef":case"cl":C("clef");var r=0;if(o.clef!==undefined){o.clef=o.clef.replace(/[',]/g,"");if(o.clef.indexOf("+16")!==-1){r+=14;o.clef=o.clef.replace("+16","")}o.verticalPos=i(o.clef,r)}break;case"treble":case"bass":case"tenor":case"alto":case"none":case"treble'":case"bass'":case"tenor'":case"alto'":case"none'":case"treble''":case"bass''":case"tenor''":case"alto''":case"none''":case"treble,":case"bass,":case"tenor,":case"alto,":case"none,":case"treble,,":case"bass,,":case"tenor,,":case"alto,,":case"none,,":var u=0;o.clef=l.token.replace(/[',]/g,"");o.verticalPos=i(o.clef,u);break;case"staves":case"stave":case"stv":C("staves");break;case"brace":case"brc":C("brace");break;case"bracket":case"brk":C("bracket");break;case"name":case"nm":C("name");break;case"subname":case"sname":case"snm":C("subname");break;case"merge":o.startStaff=false;break;case"stems":t=h.getVoiceToken(m,k,j);if(t.warn!==undefined){e("Expected value for stems in voice: "+t.warn,m,k)}else{if(t.token==="up"||t.token==="down"){b.voices[q].stem=t.token}else{e("Expected up or down for voice stem",m,k)}}k+=t.len;break;case"up":case"down":b.voices[q].stem=l.token;break;case"middle":case"m":C("verticalPos");o.verticalPos=a(o.verticalPos).mid;break;case"gchords":case"gch":b.voices[q].suppressChords=true;break;case"space":case"spc":C("spacing");break;case"scale":y(q,"scale","number");break;case"transpose":y(q,"transpose","number");break}}k+=h.eatWhiteSpace(m,k)}if(o.startStaff||b.staves.length===0){b.staves.push({index:b.staves.length,meter:b.origMeter});if(!b.score_is_present){b.staves[b.staves.length-1].numVoices=0 }}if(b.voices[q].staffNum===undefined){b.voices[q].staffNum=b.staves.length-1;var A=0;for(var n in b.voices){if(b.voices.hasOwnProperty(n)){if(b.voices[n].staffNum===b.voices[q].staffNum){A++}}}b.voices[q].index=A-1}var p=b.staves[b.voices[q].staffNum];if(!b.score_is_present){p.numVoices++}if(o.clef){p.clef={type:o.clef,verticalPos:o.verticalPos}}if(o.spacing){p.spacing_below_offset=o.spacing}if(o.verticalPos){p.verticalPos=o.verticalPos}if(o.name){if(p.name){p.name.push(o.name)}else{p.name=[o.name]}}if(o.subname){if(p.subname){p.subname.push(o.subname)}else{p.subname=[o.subname]}}f(q)}})();if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.parse){window.ABCJS.parse={}}window.ABCJS.parse.tokenizer=function(){this.skipWhiteSpace=function(j){for(var h=0;h<j.length;h++){if(!this.isWhiteSpace(j.charAt(h))){return h}}return j.length};var g=function(j,h){return h>=j.length};this.eatWhiteSpace=function(h,j){for(var k=j;k<h.length;k++){if(!this.isWhiteSpace(h.charAt(k))){return k-j}}return k-j};this.getKeyPitch=function(j){var h=this.skipWhiteSpace(j);if(g(j,h)){return{len:0}}switch(j.charAt(h)){case"A":return{len:h+1,token:"A"};case"B":return{len:h+1,token:"B"};case"C":return{len:h+1,token:"C"};case"D":return{len:h+1,token:"D"};case"E":return{len:h+1,token:"E"};case"F":return{len:h+1,token:"F"};case"G":return{len:h+1,token:"G"}}return{len:0}};this.getSharpFlat=function(h){if(h==="bass"){return{len:0}}switch(h.charAt(0)){case"#":return{len:1,token:"#"};case"b":return{len:1,token:"b"}}return{len:0}};this.getMode=function(l){var k=function(i,m){while(m<i.length&&((i.charAt(m)>="a"&&i.charAt(m)<="z")||(i.charAt(m)>="A"&&i.charAt(m)<="Z"))){m++}return m};var j=this.skipWhiteSpace(l);if(g(l,j)){return{len:0}}var h=l.substring(j,j+3).toLowerCase();if(h.length>1&&h.charAt(1)===" "||h.charAt(1)==="^"||h.charAt(1)==="_"||h.charAt(1)==="="){h=h.charAt(0)}switch(h){case"mix":return{len:k(l,j),token:"Mix"};case"dor":return{len:k(l,j),token:"Dor"};case"phr":return{len:k(l,j),token:"Phr"};case"lyd":return{len:k(l,j),token:"Lyd"};case"loc":return{len:k(l,j),token:"Loc"};case"aeo":return{len:k(l,j),token:"m"};case"maj":return{len:k(l,j),token:""};case"ion":return{len:k(l,j),token:""};case"min":return{len:k(l,j),token:"m"};case"m":return{len:k(l,j),token:"m"}}return{len:0}};this.getClef=function(o,n){var h=o;var m=this.skipWhiteSpace(o);if(g(o,m)){return{len:0}}var q=false;var p=o.substring(m);if(window.ABCJS.parse.startsWith(p,"clef=")){q=true;p=p.substring(5);m+=5}if(p.length===0&&q){return{len:m+5,warn:"No clef specified: "+h}}var l=this.skipWhiteSpace(p);if(g(p,l)){return{len:0}}if(l>0){m+=l;p=p.substring(l)}var k=null;if(window.ABCJS.parse.startsWith(p,"treble")){k="treble"}else{if(window.ABCJS.parse.startsWith(p,"bass3")){k="bass3"}else{if(window.ABCJS.parse.startsWith(p,"bass")){k="bass"}else{if(window.ABCJS.parse.startsWith(p,"tenor")){k="tenor"}else{if(window.ABCJS.parse.startsWith(p,"alto2")){k="alto2"}else{if(window.ABCJS.parse.startsWith(p,"alto1")){k="alto1"}else{if(window.ABCJS.parse.startsWith(p,"alto")){k="alto"}else{if(!n&&(q&&window.ABCJS.parse.startsWith(p,"none"))){k="none"}else{if(window.ABCJS.parse.startsWith(p,"perc")){k="perc"}else{if(!n&&(q&&window.ABCJS.parse.startsWith(p,"C"))){k="tenor"}else{if(!n&&(q&&window.ABCJS.parse.startsWith(p,"F"))){k="bass"}else{if(!n&&(q&&window.ABCJS.parse.startsWith(p,"G"))){k="treble"}else{return{len:m+5,warn:"Unknown clef specified: "+h}}}}}}}}}}}}}p=p.substring(k.length);l=this.isMatch(p,"+8");if(l>0){k+="+8"}else{l=this.isMatch(p,"-8");if(l>0){k+="-8"}}return{len:m+k.length,token:k,explicit:q}};this.getBarLine=function(h,k){switch(h.charAt(k)){case"]":++k;switch(h.charAt(k)){case"|":return{len:2,token:"bar_thick_thin"};case"[":++k;if((h.charAt(k)>="1"&&h.charAt(k)<="9")||h.charAt(k)==='"'){return{len:2,token:"bar_invisible"}}return{len:1,warn:"Unknown bar symbol"};default:return{len:1,token:"bar_invisible"}}break;case":":++k;switch(h.charAt(k)){case":":return{len:2,token:"bar_dbl_repeat"};case"|":++k;switch(h.charAt(k)){case"]":++k;switch(h.charAt(k)){case"|":++k;if(h.charAt(k)===":"){return{len:5,token:"bar_dbl_repeat"}}return{len:3,token:"bar_right_repeat"};default:return{len:3,token:"bar_right_repeat"}}break;case"|":++k;if(h.charAt(k)===":"){return{len:4,token:"bar_dbl_repeat"}}return{len:3,token:"bar_right_repeat"};default:return{len:2,token:"bar_right_repeat"}}break;default:return{len:1,warn:"Unknown bar symbol"}}break;case"[":++k;if(h.charAt(k)==="|"){++k;switch(h.charAt(k)){case":":return{len:3,token:"bar_left_repeat"};case"]":return{len:3,token:"bar_invisible"};default:return{len:2,token:"bar_thick_thin"}}}else{if((h.charAt(k)>="1"&&h.charAt(k)<="9")||h.charAt(k)==='"'){return{len:1,token:"bar_invisible"}}return{len:0}}break;case"|":++k;switch(h.charAt(k)){case"]":return{len:2,token:"bar_thin_thick"};case"|":++k;if(h.charAt(k)===":"){return{len:3,token:"bar_left_repeat"}}return{len:2,token:"bar_thin_thin"};case":":var j=0;while(h.charAt(k+j)===":"){j++}return{len:1+j,token:"bar_left_repeat"};default:return{len:1,token:"bar_thin"}}break}return{len:0}};this.getTokenOf=function(k,j){for(var h=0;h<k.length;h++){if(j.indexOf(k.charAt(h))<0){return{len:h,token:k.substring(0,h)}}}return{len:h,token:k}};this.getToken=function(k,l,h){var j=l;while(j<h&&!this.isWhiteSpace(k.charAt(j))){j++}return k.substring(l,j)};this.isMatch=function(k,h){var j=this.skipWhiteSpace(k);if(g(k,j)){return 0}if(window.ABCJS.parse.startsWith(k.substring(j),h)){return j+h.length}return 0};this.getPitchFromTokens=function(j){var h={};var i={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11};h.position=i[j[0].token];if(h.position===undefined){return{warn:"Pitch expected. Found: "+j[0].token}}j.shift();while(j.length){switch(j[0].token){case",":h.position-=7;j.shift();break;case"'":h.position+=7;j.shift();break;default:return h}}return h};this.getKeyAccidentals2=function(j){var h;while(j.length>0){var i;if(j[0].token==="^"){i="sharp";j.shift();if(j.length===0){return{accs:h,warn:"Expected note name after "+i}}switch(j[0].token){case"^":i="dblsharp";j.shift();break;case"/":i="quartersharp";j.shift();break}}else{if(j[0].token==="="){i="natural";j.shift()}else{if(j[0].token==="_"){i="flat";j.shift();if(j.length===0){return{accs:h,warn:"Expected note name after "+i}}switch(j[0].token){case"_":i="dblflat";j.shift();break;case"/":i="quarterflat";j.shift();break}}else{return{accs:h}}}}if(j.length===0){return{accs:h,warn:"Expected note name after "+i}}switch(j[0].token.charAt(0)){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":if(h===undefined){h=[]}h.push({acc:i,note:j[0].token.charAt(0)});if(j[0].token.length===1){j.shift()}else{j[0].token=j[0].token.substring(1)}break;default:return{accs:h,warn:"Expected note name after "+i+" Found: "+j[0].token}}}return{accs:h}};this.getKeyAccidental=function(l){var k={"^":"sharp","^^":"dblsharp","=":"natural",_:"flat",__:"dblflat","_/":"quarterflat","^/":"quartersharp"}; var h=this.skipWhiteSpace(l);if(g(l,h)){return{len:0}}var j=null;switch(l.charAt(h)){case"^":case"_":case"=":j=l.charAt(h);break;default:return{len:0}}h++;if(g(l,h)){return{len:1,warn:"Expected note name after accidental"}}switch(l.charAt(h)){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":return{len:h+1,token:{acc:k[j],note:l.charAt(h)}};case"^":case"_":case"/":j+=l.charAt(h);h++;if(g(l,h)){return{len:2,warn:"Expected note name after accidental"}}switch(l.charAt(h)){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":return{len:h+1,token:{acc:k[j],note:l.charAt(h)}};default:return{len:2,warn:"Expected note name after accidental"}}break;default:return{len:1,warn:"Expected note name after accidental"}}};this.isWhiteSpace=function(h){return h===" "||h==="\t"||h==="\x12"};this.getMeat=function(i,k,h){var j=i.indexOf("%",k);if(j>=0&&j<h){h=j}while(k<h&&(i.charAt(k)===" "||i.charAt(k)==="\t"||i.charAt(k)==="\x12")){k++}while(k<h&&(i.charAt(h-1)===" "||i.charAt(h-1)==="\t"||i.charAt(h-1)==="\x12")){h--}return{start:k,end:h}};var d=function(h){return(h>="A"&&h<="Z")||(h>="a"&&h<="z")};var c=function(h){return(h>="0"&&h<="9")};this.tokenize=function(r,j,k){var n=this.getMeat(r,j,k);j=n.start;k=n.end;var p=[];var l;while(j<k){if(r.charAt(j)==='"'){l=j+1;while(l<k&&r.charAt(l)!=='"'){l++}p.push({type:"quote",token:r.substring(j+1,l),start:j+1,end:l});l++}else{if(d(r.charAt(j))){l=j+1;while(l<k&&d(r.charAt(l))){l++}p.push({type:"alpha",token:r.substring(j,l),continueId:c(r.charAt(l)),start:j,end:l});j=l+1}else{if(r.charAt(j)==="."&&c(r.charAt(l+1))){l=j+1;var q=null;var m=null;while(l<k&&c(r.charAt(l))){l++}m=parseFloat(r.substring(j,l));p.push({type:"number",token:r.substring(j,l),intt:q,floatt:m,continueId:d(r.charAt(l)),start:j,end:l});j=l+1}else{if(c(r.charAt(j))||(r.charAt(j)==="-"&&c(r.charAt(l+1)))){l=j+1;var h=null;var o=null;while(l<k&&c(r.charAt(l))){l++}if(r.charAt(l)==="."&&c(r.charAt(l+1))){l++;while(l<k&&c(r.charAt(l))){l++}}else{h=parseInt(r.substring(j,l))}o=parseFloat(r.substring(j,l));p.push({type:"number",token:r.substring(j,l),intt:h,floatt:o,continueId:d(r.charAt(l)),start:j,end:l});j=l+1}else{if(r.charAt(j)===" "||r.charAt(j)==="\t"){l=j+1}else{p.push({type:"punct",token:r.charAt(j),start:j,end:j+1});l=j+1}}}}}j=l}return p};this.getVoiceToken=function(j,n,h){var k=n;while(k<h&&this.isWhiteSpace(j.charAt(k))||j.charAt(k)==="="){k++}if(j.charAt(k)==='"'){var m=j.indexOf('"',k+1);if(m===-1||m>=h){return{len:1,err:"Missing close quote"}}return{len:m-n+1,token:this.translateString(j.substring(k+1,m))}}else{var l=k;while(l<h&&!this.isWhiteSpace(j.charAt(l))&&j.charAt(l)!=="="){l++}return{len:l-n+1,token:j.substring(k,l)}}};var f={"`a":"à","'a":"á","^a":"â","~a":"ã",'"a':"ä",oa:"å","=a":"ā",ua:"ă",";a":"ą","`e":"è","'e":"é","^e":"ê",'"e':"ë","=e":"ē",ue:"ĕ",";e":"ę",".e":"ė","`i":"ì","'i":"í","^i":"î",'"i':"ï","=i":"ī",ui:"ĭ",";i":"į","`o":"ò","'o":"ó","^o":"ô","~o":"õ",'"o':"ö","=o":"ō",uo:"ŏ","/o":"ø","`u":"ù","'u":"ú","^u":"û","~u":"ũ",'"u':"ü",ou:"ů","=u":"ū",uu:"ŭ",";u":"ų","`A":"À","'A":"Á","^A":"Â","~A":"Ã",'"A':"Ä",oA:"Å","=A":"Ā",uA:"Ă",";A":"Ą","`E":"È","'E":"É","^E":"Ê",'"E':"Ë","=E":"Ē",uE:"Ĕ",";E":"Ę",".E":"Ė","`I":"Ì","'I":"Í","^I":"Î","~I":"Ĩ",'"I':"Ï","=I":"Ī",uI:"Ĭ",";I":"Į",".I":"İ","`O":"Ò","'O":"Ó","^O":"Ô","~O":"Õ",'"O':"Ö","=O":"Ō",uO:"Ŏ","/O":"Ø","`U":"Ù","'U":"Ú","^U":"Û","~U":"Ũ",'"U':"Ü",oU:"Ů","=U":"Ū",uU:"Ŭ",";U":"Ų",ae:"æ",AE:"Æ",oe:"œ",OE:"Œ",ss:"ß","'c":"ć","^c":"ĉ",uc:"č",cc:"ç",".c":"ċ",cC:"Ç","'C":"Ć","^C":"Ĉ",uC:"Č",".C":"Ċ","~n":"ñ","=s":"š",vs:"š",vz:"ž"};var e={"#":"♯",b:"♭","=":"♮"};var b={"201":"♯","202":"♭","203":"♮","241":"¡","242":"¢","252":"a","262":"2","272":"o","302":"Â","312":"Ê","322":"Ò","332":"Ú","342":"â","352":"ê","362":"ò","372":"ú","243":"£","253":"«","263":"3","273":"»","303":"Ã","313":"Ë","323":"Ó","333":"Û","343":"ã","353":"ë","363":"ó","373":"û","244":"¤","254":"¬","264":" ́","274":"1⁄4","304":"Ä","314":"Ì","324":"Ô","334":"Ü","344":"ä","354":"ì","364":"ô","374":"ü","245":"¥","255":"-","265":"μ","275":"1⁄2","305":"Å","315":"Í","325":"Õ","335":"Ý","345":"å","355":"í","365":"õ","375":"ý","246":"¦","256":"®","266":"¶","276":"3⁄4","306":"Æ","316":"Î","326":"Ö","336":"Þ","346":"æ","356":"î","366":"ö","376":"þ","247":"§","257":" ̄","267":"·","277":"¿","307":"Ç","317":"Ï","327":"×","337":"ß","347":"ç","357":"ï","367":"÷","377":"ÿ","250":" ̈","260":"°","270":" ̧","300":"À","310":"È","320":"Ð","330":"Ø","340":"à","350":"è","360":"ð","370":"ø","251":"©","261":"±","271":"1","301":"Á","311":"É","321":"Ñ","331":"Ù","341":"á","351":"é","361":"ñ","371":"ù"};this.translateString=function(j){var h=j.split("\\");if(h.length===1){return j}var i=null;window.ABCJS.parse.each(h,function(k){if(i===null){i=k}else{var l=f[k.substring(0,2)];if(l!==undefined){i+=l+k.substring(2)}else{l=b[k.substring(0,3)];if(l!==undefined){i+=l+k.substring(3)}else{l=e[k.substring(0,1)];if(l!==undefined){i+=l+k.substring(1)}else{i+="\\"+k}}}}});return i};this.getNumber=function(h,j){var i=0;while(j<h.length){switch(h.charAt(j)){case"0":i=i*10;j++;break;case"1":i=i*10+1;j++;break;case"2":i=i*10+2;j++;break;case"3":i=i*10+3;j++;break;case"4":i=i*10+4;j++;break;case"5":i=i*10+5;j++;break;case"6":i=i*10+6;j++;break;case"7":i=i*10+7;j++;break;case"8":i=i*10+8;j++;break;case"9":i=i*10+9;j++;break;default:return{num:i,index:j}}}return{num:i,index:j}};this.getFraction=function(h,k){var j=1;var o=1;if(h.charAt(k)!=="/"){var i=this.getNumber(h,k);j=i.num;k=i.index}if(h.charAt(k)==="/"){k++;if(h.charAt(k)==="/"){var n=0.5;while(h.charAt(k++)==="/"){n=n/2}return{value:j*n,index:k-1}}else{var l=k;var m=this.getNumber(h,k);if(m.num===0&&l===k){m.num=2}if(m.num!==0){o=m.num}k=m.index}}return{value:j/o,index:k}};this.theReverser=function(h){if(window.ABCJS.parse.endsWith(h,", The")){return"The "+h.substring(0,h.length-5)}if(window.ABCJS.parse.endsWith(h,", A")){return"A "+h.substring(0,h.length-3)}return h};this.stripComment=function(j){var h=j.indexOf("%");if(h>=0){return window.ABCJS.parse.strip(j.substring(0,h))}return window.ABCJS.parse.strip(j)};this.getInt=function(l){var h=parseInt(l);if(isNaN(h)){return{digits:0}}var k=""+h;var j=l.indexOf(k);return{value:h,digits:j+k.length}};this.getFloat=function(l){var h=parseFloat(l);if(isNaN(h)){return{digits:0}}var k=""+h;var j=l.indexOf(k);return{value:h,digits:j+k.length}};this.getMeasurement=function(k){if(k.length===0){return{used:0}}var j=1;var i="";if(k[0].token==="-"){k.shift();i="-";j++}else{if(k[0].type!=="number"){return{used:0}}}i+=k.shift().token;if(k.length===0){return{used:1,value:parseInt(i)}}var h=k.shift();if(h.token==="."){j++;if(k.length===0){return{used:j,value:parseInt(i)}}if(k[0].type==="number"){h=k.shift(); i=i+"."+h.token;j++;if(k.length===0){return{used:j,value:parseFloat(i)}}}h=k.shift()}switch(h.token){case"pt":return{used:j+1,value:parseFloat(i)};case"cm":return{used:j+1,value:parseFloat(i)/2.54*72};case"in":return{used:j+1,value:parseFloat(i)*72};default:k.unshift(h);return{used:j,value:parseFloat(i)}}return{used:0}};var a=function(h){while(h.indexOf("\\n")!==-1){h=h.replace("\\n","\n")}return h};this.getBrackettedSubstring=function(h,j,n,l){var k=l||h.charAt(j);var m=j+1;while((m<h.length)&&(h.charAt(m)!==k)){++m}if(h.charAt(m)===k){return[m-j+1,a(h.substring(j+1,m)),true]}else{m=j+n;if(m>h.length-1){m=h.length-1}return[m-j+1,a(h.substring(j+1,m)),false]}}};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.write){window.ABCJS.write={}}ABCJS.write.Glyphs=function(){var a={"rests.whole":{d:[["M",0.06,0.03],["l",0.09,-0.06],["l",5.46,0],["l",5.49,0],["l",0.09,0.06],["l",0.06,0.09],["l",0,2.19],["l",0,2.19],["l",-0.06,0.09],["l",-0.09,0.06],["l",-5.49,0],["l",-5.46,0],["l",-0.09,-0.06],["l",-0.06,-0.09],["l",0,-2.19],["l",0,-2.19],["z"]],w:11.25,h:4.68},"rests.half":{d:[["M",0.06,-4.62],["l",0.09,-0.06],["l",5.46,0],["l",5.49,0],["l",0.09,0.06],["l",0.06,0.09],["l",0,2.19],["l",0,2.19],["l",-0.06,0.09],["l",-0.09,0.06],["l",-5.49,0],["l",-5.46,0],["l",-0.09,-0.06],["l",-0.06,-0.09],["l",0,-2.19],["l",0,-2.19],["z"]],w:11.25,h:4.68},"rests.quarter":{d:[["M",1.89,-11.82],["c",0.12,-0.06,0.24,-0.06,0.36,-0.03],["c",0.09,0.06,4.74,5.58,4.86,5.82],["c",0.21,0.39,0.15,0.78,-0.15,1.26],["c",-0.24,0.33,-0.72,0.81,-1.62,1.56],["c",-0.45,0.36,-0.87,0.75,-0.96,0.84],["c",-0.93,0.99,-1.14,2.49,-0.6,3.63],["c",0.18,0.39,0.27,0.48,1.32,1.68],["c",1.92,2.25,1.83,2.16,1.83,2.34],["c",-0,0.18,-0.18,0.36,-0.36,0.39],["c",-0.15,-0,-0.27,-0.06,-0.48,-0.27],["c",-0.75,-0.75,-2.46,-1.29,-3.39,-1.08],["c",-0.45,0.09,-0.69,0.27,-0.9,0.69],["c",-0.12,0.3,-0.21,0.66,-0.24,1.14],["c",-0.03,0.66,0.09,1.35,0.3,2.01],["c",0.15,0.42,0.24,0.66,0.45,0.96],["c",0.18,0.24,0.18,0.33,0.03,0.42],["c",-0.12,0.06,-0.18,0.03,-0.45,-0.3],["c",-1.08,-1.38,-2.07,-3.36,-2.4,-4.83],["c",-0.27,-1.05,-0.15,-1.77,0.27,-2.07],["c",0.21,-0.12,0.42,-0.15,0.87,-0.15],["c",0.87,0.06,2.1,0.39,3.3,0.9],["l",0.39,0.18],["l",-1.65,-1.95],["c",-2.52,-2.97,-2.61,-3.09,-2.7,-3.27],["c",-0.09,-0.24,-0.12,-0.48,-0.03,-0.75],["c",0.15,-0.48,0.57,-0.96,1.83,-2.01],["c",0.45,-0.36,0.84,-0.72,0.93,-0.78],["c",0.69,-0.75,1.02,-1.8,0.9,-2.79],["c",-0.06,-0.33,-0.21,-0.84,-0.39,-1.11],["c",-0.09,-0.15,-0.45,-0.6,-0.81,-1.05],["c",-0.36,-0.42,-0.69,-0.81,-0.72,-0.87],["c",-0.09,-0.18,-0,-0.42,0.21,-0.51],["z"]],w:7.888,h:21.435},"rests.8th":{d:[["M",1.68,-6.12],["c",0.66,-0.09,1.23,0.09,1.68,0.51],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.12,0.27,0.33,0.45,0.6,0.48],["c",0.12,0,0.18,0,0.33,-0.09],["c",0.39,-0.18,1.32,-1.29,1.68,-1.98],["c",0.09,-0.21,0.24,-0.3,0.39,-0.3],["c",0.12,0,0.27,0.09,0.33,0.18],["c",0.03,0.06,-0.27,1.11,-1.86,6.42],["c",-1.02,3.48,-1.89,6.39,-1.92,6.42],["c",0,0.03,-0.12,0.12,-0.24,0.15],["c",-0.18,0.09,-0.21,0.09,-0.45,0.09],["c",-0.24,0,-0.3,0,-0.48,-0.06],["c",-0.09,-0.06,-0.21,-0.12,-0.21,-0.15],["c",-0.06,-0.03,0.15,-0.57,1.68,-4.92],["c",0.96,-2.67,1.74,-4.89,1.71,-4.89],["l",-0.51,0.15],["c",-1.08,0.36,-1.74,0.48,-2.55,0.48],["c",-0.66,0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.33,-0.45,0.84,-0.81,1.38,-0.9],["z"]],w:7.534,h:13.883},"rests.16th":{d:[["M",3.33,-6.12],["c",0.66,-0.09,1.23,0.09,1.68,0.51],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.15,0.39,0.57,0.57,0.87,0.42],["c",0.39,-0.18,1.2,-1.23,1.62,-2.07],["c",0.06,-0.15,0.24,-0.24,0.36,-0.24],["c",0.12,0,0.27,0.09,0.33,0.18],["c",0.03,0.06,-0.45,1.86,-2.67,10.17],["c",-1.5,5.55,-2.73,10.14,-2.76,10.17],["c",-0.03,0.03,-0.12,0.12,-0.24,0.15],["c",-0.18,0.09,-0.21,0.09,-0.45,0.09],["c",-0.24,0,-0.3,0,-0.48,-0.06],["c",-0.09,-0.06,-0.21,-0.12,-0.21,-0.15],["c",-0.06,-0.03,0.12,-0.57,1.44,-4.92],["c",0.81,-2.67,1.47,-4.86,1.47,-4.89],["c",-0.03,0,-0.27,0.06,-0.54,0.15],["c",-1.08,0.36,-1.77,0.48,-2.58,0.48],["c",-0.66,0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.72,-1.05,2.22,-1.23,3.06,-0.42],["c",0.3,0.33,0.42,0.6,0.6,1.38],["c",0.09,0.45,0.21,0.78,0.33,0.9],["c",0.09,0.09,0.27,0.18,0.45,0.21],["c",0.12,0,0.18,0,0.33,-0.09],["c",0.33,-0.15,1.02,-0.93,1.41,-1.59],["c",0.12,-0.21,0.18,-0.39,0.39,-1.08],["c",0.66,-2.1,1.17,-3.84,1.17,-3.87],["c",0,0,-0.21,0.06,-0.42,0.15],["c",-0.51,0.15,-1.2,0.33,-1.68,0.42],["c",-0.33,0.06,-0.51,0.06,-0.96,0.06],["c",-0.66,0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.33,-0.45,0.84,-0.81,1.38,-0.9],["z"]],w:9.724,h:21.383},"rests.32nd":{d:[["M",4.23,-13.62],["c",0.66,-0.09,1.23,0.09,1.68,0.51],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.12,0.27,0.33,0.45,0.6,0.48],["c",0.12,0,0.18,0,0.27,-0.06],["c",0.33,-0.21,0.99,-1.11,1.44,-1.98],["c",0.09,-0.24,0.21,-0.33,0.39,-0.33],["c",0.12,0,0.27,0.09,0.33,0.18],["c",0.03,0.06,-0.57,2.67,-3.21,13.89],["c",-1.8,7.62,-3.3,13.89,-3.3,13.92],["c",-0.03,0.06,-0.12,0.12,-0.24,0.18],["c",-0.21,0.09,-0.24,0.09,-0.48,0.09],["c",-0.24,-0,-0.3,-0,-0.48,-0.06],["c",-0.09,-0.06,-0.21,-0.12,-0.21,-0.15],["c",-0.06,-0.03,0.09,-0.57,1.23,-4.92],["c",0.69,-2.67,1.26,-4.86,1.29,-4.89],["c",0,-0.03,-0.12,-0.03,-0.48,0.12],["c",-1.17,0.39,-2.22,0.57,-3,0.54],["c",-0.42,-0.03,-0.75,-0.12,-1.11,-0.3],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.72,-1.05,2.22,-1.23,3.06,-0.42],["c",0.3,0.33,0.42,0.6,0.6,1.38],["c",0.09,0.45,0.21,0.78,0.33,0.9],["c",0.12,0.09,0.3,0.18,0.48,0.21],["c",0.12,-0,0.18,-0,0.3,-0.09],["c",0.42,-0.21,1.29,-1.29,1.56,-1.89],["c",0.03,-0.12,1.23,-4.59,1.23,-4.65],["c",0,-0.03,-0.18,0.03,-0.39,0.12],["c",-0.63,0.18,-1.2,0.36,-1.74,0.45],["c",-0.39,0.06,-0.54,0.06,-1.02,0.06],["c",-0.66,-0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.72,-1.05,2.22,-1.23,3.06,-0.42],["c",0.3,0.33,0.42,0.6,0.6,1.38],["c",0.09,0.45,0.21,0.78,0.33,0.9],["c",0.18,0.18,0.51,0.27,0.72,0.15],["c",0.3,-0.12,0.69,-0.57,1.08,-1.17],["c",0.42,-0.6,0.39,-0.51,1.05,-3.03],["c",0.33,-1.26,0.6,-2.31,0.6,-2.34],["c",0,-0,-0.21,0.03,-0.45,0.12],["c",-0.57,0.18,-1.14,0.33,-1.62,0.42],["c",-0.33,0.06,-0.51,0.06,-0.96,0.06],["c",-0.66,-0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.33,-0.45,0.84,-0.81,1.38,-0.9],["z"]],w:11.373,h:28.883},"rests.64th":{d:[["M",5.13,-13.62],["c",0.66,-0.09,1.23,0.09,1.68,0.51],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.15,0.63,0.21,0.81,0.33,0.96],["c",0.18,0.21,0.54,0.3,0.75,0.18],["c",0.24,-0.12,0.63,-0.66,1.08,-1.56],["c",0.33,-0.66,0.39,-0.72,0.6,-0.72],["c",0.12,0,0.27,0.09,0.33,0.18],["c",0.03,0.06,-0.69,3.66,-3.54,17.64],["c",-1.95,9.66,-3.57,17.61,-3.57,17.64],["c",-0.03,0.06,-0.12,0.12,-0.24,0.18],["c",-0.21,0.09,-0.24,0.09,-0.48,0.09],["c",-0.24,0,-0.3,0,-0.48,-0.06],["c",-0.09,-0.06,-0.21,-0.12,-0.21,-0.15],["c",-0.06,-0.03,0.06,-0.57,1.05,-4.95],["c",0.6,-2.7,1.08,-4.89,1.08,-4.92],["c",0,0,-0.24,0.06,-0.51,0.15],["c",-0.66,0.24,-1.2,0.36,-1.77,0.48],["c",-0.42,0.06,-0.57,0.06,-1.05,0.06],["c",-0.69,0,-0.87,-0.03,-1.35,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.72,-1.05,2.22,-1.23,3.06,-0.42],["c",0.3,0.33,0.42,0.6,0.6,1.38],["c",0.09,0.45,0.21,0.78,0.33,0.9],["c",0.09,0.09,0.27,0.18,0.45,0.21],["c",0.21,0.03,0.39,-0.09,0.72,-0.42],["c",0.45,-0.45,1.02,-1.26,1.17,-1.65],["c",0.03,-0.09,0.27,-1.14,0.54,-2.34],["c",0.27,-1.2,0.48,-2.19,0.51,-2.22],["c",0,-0.03,-0.09,-0.03,-0.48,0.12],["c",-1.17,0.39,-2.22,0.57,-3,0.54],["c",-0.42,-0.03,-0.75,-0.12,-1.11,-0.3],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.36,-0.54,0.96,-0.87,1.65,-0.93],["c",0.54,-0.03,1.02,0.15,1.41,0.54],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.15,0.39,0.57,0.57,0.9,0.42],["c",0.36,-0.18,1.2,-1.26,1.47,-1.89],["c",0.03,-0.09,0.3,-1.2,0.57,-2.43],["l",0.51,-2.28],["l",-0.54,0.18],["c",-1.11,0.36,-1.8,0.48,-2.61,0.48],["c",-0.66,0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.36,-0.54,0.96,-0.87,1.65,-0.93],["c",0.54,-0.03,1.02,0.15,1.41,0.54],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.15,0.63,0.21,0.81,0.33,0.96],["c",0.21,0.21,0.54,0.3,0.75,0.18],["c",0.36,-0.18,0.93,-0.93,1.29,-1.68],["c",0.12,-0.24,0.18,-0.48,0.63,-2.55],["l",0.51,-2.31],["c",0,-0.03,-0.18,0.03,-0.39,0.12],["c",-1.14,0.36,-2.1,0.54,-2.82,0.51],["c",-0.42,-0.03,-0.75,-0.12,-1.11,-0.3],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.33,-0.45,0.84,-0.81,1.38,-0.9],["z"]],w:12.453,h:36.383},"rests.128th":{d:[["M",6.03,-21.12],["c",0.66,-0.09,1.23,0.09,1.68,0.51],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.12,0.27,0.33,0.45,0.6,0.48],["c",0.21,0,0.33,-0.06,0.54,-0.36],["c",0.15,-0.21,0.54,-0.93,0.78,-1.47],["c",0.15,-0.33,0.18,-0.39,0.3,-0.48],["c",0.18,-0.09,0.45,0,0.51,0.15],["c",0.03,0.09,-7.11,42.75,-7.17,42.84],["c",-0.03,0.03,-0.15,0.09,-0.24,0.15],["c",-0.18,0.06,-0.24,0.06,-0.45,0.06],["c",-0.24,-0,-0.3,-0,-0.48,-0.06],["c",-0.09,-0.06,-0.21,-0.12,-0.21,-0.15],["c",-0.06,-0.03,0.03,-0.57,0.84,-4.98],["c",0.51,-2.7,0.93,-4.92,0.9,-4.92],["c",0,-0,-0.15,0.06,-0.36,0.12],["c",-0.78,0.27,-1.62,0.48,-2.31,0.57],["c",-0.15,0.03,-0.54,0.03,-0.81,0.03],["c",-0.66,-0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.36,-0.54,0.96,-0.87,1.65,-0.93],["c",0.54,-0.03,1.02,0.15,1.41,0.54],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.12,0.27,0.33,0.45,0.63,0.48],["c",0.12,-0,0.18,-0,0.3,-0.09],["c",0.42,-0.21,1.14,-1.11,1.5,-1.83],["c",0.12,-0.27,0.12,-0.27,0.54,-2.52],["c",0.24,-1.23,0.42,-2.25,0.39,-2.25],["c",0,-0,-0.24,0.06,-0.51,0.18],["c",-1.26,0.39,-2.25,0.57,-3.06,0.54],["c",-0.42,-0.03,-0.75,-0.12,-1.11,-0.3],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.36,-0.54,0.96,-0.87,1.65,-0.93],["c",0.54,-0.03,1.02,0.15,1.41,0.54],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.15,0.63,0.21,0.81,0.33,0.96],["c",0.18,0.21,0.51,0.3,0.75,0.18],["c",0.36,-0.15,1.05,-0.99,1.41,-1.77],["l",0.15,-0.3],["l",0.42,-2.25],["c",0.21,-1.26,0.42,-2.28,0.39,-2.28],["l",-0.51,0.15],["c",-1.11,0.39,-1.89,0.51,-2.7,0.51],["c",-0.66,-0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.36,-0.54,0.96,-0.87,1.65,-0.93],["c",0.54,-0.03,1.02,0.15,1.41,0.54],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.15,0.63,0.21,0.81,0.33,0.96],["c",0.18,0.18,0.48,0.27,0.72,0.21],["c",0.33,-0.12,1.14,-1.26,1.41,-1.95],["c",0,-0.09,0.21,-1.11,0.45,-2.34],["c",0.21,-1.2,0.39,-2.22,0.39,-2.28],["c",0.03,-0.03,0,-0.03,-0.45,0.12],["c",-0.57,0.18,-1.2,0.33,-1.71,0.42],["c",-0.3,0.06,-0.51,0.06,-0.93,0.06],["c",-0.66,-0,-0.84,-0.03,-1.32,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.36,-0.54,0.96,-0.87,1.65,-0.93],["c",0.54,-0.03,1.02,0.15,1.41,0.54],["c",0.27,0.3,0.39,0.54,0.57,1.26],["c",0.09,0.33,0.18,0.66,0.21,0.72],["c",0.12,0.27,0.33,0.45,0.6,0.48],["c",0.18,-0,0.36,-0.09,0.57,-0.33],["c",0.33,-0.36,0.78,-1.14,0.93,-1.56],["c",0.03,-0.12,0.24,-1.2,0.45,-2.4],["c",0.24,-1.2,0.42,-2.22,0.42,-2.28],["c",0.03,-0.03,0,-0.03,-0.39,0.09],["c",-1.05,0.36,-1.8,0.48,-2.58,0.48],["c",-0.63,-0,-0.84,-0.03,-1.29,-0.27],["c",-1.32,-0.63,-1.77,-2.16,-1.02,-3.3],["c",0.33,-0.45,0.84,-0.81,1.38,-0.9],["z"]],w:12.992,h:43.883},"accidentals.sharp":{d:[["M",5.73,-11.19],["c",0.21,-0.12,0.54,-0.03,0.66,0.24],["c",0.06,0.12,0.06,0.21,0.06,2.31],["c",0,1.23,0,2.22,0.03,2.22],["c",0,-0,0.27,-0.12,0.6,-0.24],["c",0.69,-0.27,0.78,-0.3,0.96,-0.15],["c",0.21,0.15,0.21,0.18,0.21,1.38],["c",0,1.02,0,1.11,-0.06,1.2],["c",-0.03,0.06,-0.09,0.12,-0.12,0.15],["c",-0.06,0.03,-0.42,0.21,-0.84,0.36],["l",-0.75,0.33],["l",-0.03,2.43],["c",0,1.32,0,2.43,0.03,2.43],["c",0,-0,0.27,-0.12,0.6,-0.24],["c",0.69,-0.27,0.78,-0.3,0.96,-0.15],["c",0.21,0.15,0.21,0.18,0.21,1.38],["c",0,1.02,0,1.11,-0.06,1.2],["c",-0.03,0.06,-0.09,0.12,-0.12,0.15],["c",-0.06,0.03,-0.42,0.21,-0.84,0.36],["l",-0.75,0.33],["l",-0.03,2.52],["c",0,2.28,-0.03,2.55,-0.06,2.64],["c",-0.21,0.36,-0.72,0.36,-0.93,-0],["c",-0.03,-0.09,-0.06,-0.33,-0.06,-2.43],["l",0,-2.31],["l",-1.29,0.51],["l",-1.26,0.51],["l",0,2.43],["c",0,2.58,0,2.52,-0.15,2.67],["c",-0.06,0.09,-0.27,0.18,-0.36,0.18],["c",-0.12,-0,-0.33,-0.09,-0.39,-0.18],["c",-0.15,-0.15,-0.15,-0.09,-0.15,-2.43],["c",0,-1.23,0,-2.22,-0.03,-2.22],["c",0,-0,-0.27,0.12,-0.6,0.24],["c",-0.69,0.27,-0.78,0.3,-0.96,0.15],["c",-0.21,-0.15,-0.21,-0.18,-0.21,-1.38],["c",0,-1.02,0,-1.11,0.06,-1.2],["c",0.03,-0.06,0.09,-0.12,0.12,-0.15],["c",0.06,-0.03,0.42,-0.21,0.84,-0.36],["l",0.78,-0.33],["l",0,-2.43],["c",0,-1.32,0,-2.43,-0.03,-2.43],["c",0,-0,-0.27,0.12,-0.6,0.24],["c",-0.69,0.27,-0.78,0.3,-0.96,0.15],["c",-0.21,-0.15,-0.21,-0.18,-0.21,-1.38],["c",0,-1.02,0,-1.11,0.06,-1.2],["c",0.03,-0.06,0.09,-0.12,0.12,-0.15],["c",0.06,-0.03,0.42,-0.21,0.84,-0.36],["l",0.78,-0.33],["l",0,-2.52],["c",0,-2.28,0.03,-2.55,0.06,-2.64],["c",0.21,-0.36,0.72,-0.36,0.93,0],["c",0.03,0.09,0.06,0.33,0.06,2.43],["l",0.03,2.31],["l",1.26,-0.51],["l",1.26,-0.51],["l",0,-2.43],["c",0,-2.28,0,-2.43,0.06,-2.55],["c",0.06,-0.12,0.12,-0.18,0.27,-0.24],["z"],["m",-0.33,10.65],["l",0,-2.43],["l",-1.29,0.51],["l",-1.26,0.51],["l",0,2.46],["l",0,2.43],["l",0.09,-0.03],["c",0.06,-0.03,0.63,-0.27,1.29,-0.51],["l",1.17,-0.48],["l",0,-2.46],["z"]],w:8.25,h:22.462},"accidentals.halfsharp":{d:[["M",2.43,-10.05],["c",0.21,-0.12,0.54,-0.03,0.66,0.24],["c",0.06,0.12,0.06,0.21,0.06,2.01],["c",0,1.05,0,1.89,0.03,1.89],["l",0.72,-0.48],["c",0.69,-0.48,0.69,-0.51,0.87,-0.51],["c",0.15,0,0.18,0.03,0.27,0.09],["c",0.21,0.15,0.21,0.18,0.21,1.41],["c",0,1.11,-0.03,1.14,-0.09,1.23],["c",-0.03,0.03,-0.48,0.39,-1.02,0.75],["l",-0.99,0.66],["l",0,2.37],["c",0,1.32,0,2.37,0.03,2.37],["l",0.72,-0.48],["c",0.69,-0.48,0.69,-0.51,0.87,-0.51],["c",0.15,0,0.18,0.03,0.27,0.09],["c",0.21,0.15,0.21,0.18,0.21,1.41],["c",0,1.11,-0.03,1.14,-0.09,1.23],["c",-0.03,0.03,-0.48,0.39,-1.02,0.75],["l",-0.99,0.66],["l",0,2.25],["c",0,1.95,0,2.28,-0.06,2.37],["c",-0.06,0.12,-0.12,0.21,-0.24,0.27],["c",-0.27,0.12,-0.54,0.03,-0.69,-0.24],["c",-0.06,-0.12,-0.06,-0.21,-0.06,-2.01],["c",0,-1.05,0,-1.89,-0.03,-1.89],["l",-0.72,0.48],["c",-0.69,0.48,-0.69,0.48,-0.87,0.48],["c",-0.15,0,-0.18,0,-0.27,-0.06],["c",-0.21,-0.15,-0.21,-0.18,-0.21,-1.41],["c",0,-1.11,0.03,-1.14,0.09,-1.23],["c",0.03,-0.03,0.48,-0.39,1.02,-0.75],["l",0.99,-0.66],["l",0,-2.37],["c",0,-1.32,0,-2.37,-0.03,-2.37],["l",-0.72,0.48],["c",-0.69,0.48,-0.69,0.48,-0.87,0.48],["c",-0.15,0,-0.18,0,-0.27,-0.06],["c",-0.21,-0.15,-0.21,-0.18,-0.21,-1.41],["c",0,-1.11,0.03,-1.14,0.09,-1.23],["c",0.03,-0.03,0.48,-0.39,1.02,-0.75],["l",0.99,-0.66],["l",0,-2.25],["c",0,-2.13,0,-2.28,0.06,-2.4],["c",0.06,-0.12,0.12,-0.18,0.27,-0.24],["z"]],w:5.25,h:20.174},"accidentals.nat":{d:[["M",0.204,-11.4],["c",0.24,-0.06,0.78,0,0.99,0.15],["c",0.03,0.03,0.03,0.48,0,2.61],["c",-0.03,1.44,-0.03,2.61,-0.03,2.61],["c",0,0.03,0.75,-0.09,1.68,-0.24],["c",0.96,-0.18,1.71,-0.27,1.74,-0.27],["c",0.15,0.03,0.27,0.15,0.36,0.3],["l",0.06,0.12],["l",0.09,8.67],["c",0.09,6.96,0.12,8.67,0.09,8.67],["c",-0.03,0.03,-0.12,0.06,-0.21,0.09],["c",-0.24,0.09,-0.72,0.09,-0.96,0],["c",-0.09,-0.03,-0.18,-0.06,-0.21,-0.09],["c",-0.03,-0.03,-0.03,-0.48,0,-2.61],["c",0.03,-1.44,0.03,-2.61,0.03,-2.61],["c",0,-0.03,-0.75,0.09,-1.68,0.24],["c",-0.96,0.18,-1.71,0.27,-1.74,0.27],["c",-0.15,-0.03,-0.27,-0.15,-0.36,-0.3],["l",-0.06,-0.15],["l",-0.09,-7.53],["c",-0.06,-4.14,-0.09,-8.04,-0.12,-8.67],["l",0,-1.11],["l",0.15,-0.06],["c",0.09,-0.03,0.21,-0.06,0.27,-0.09],["z"],["m",3.75,8.4],["c",0,-0.33,0,-0.42,-0.03,-0.42],["c",-0.12,0,-2.79,0.45,-2.79,0.48],["c",-0.03,0,-0.09,6.3,-0.09,6.33],["c",0.03,0,2.79,-0.45,2.82,-0.48],["c",0,0,0.09,-4.53,0.09,-5.91],["z"]],w:5.411,h:22.8},"accidentals.flat":{d:[["M",-0.36,-14.07],["c",0.33,-0.06,0.87,0,1.08,0.15],["c",0.06,0.03,0.06,0.36,-0.03,5.25],["c",-0.06,2.85,-0.09,5.19,-0.09,5.19],["c",0,0.03,0.12,-0.03,0.24,-0.12],["c",0.63,-0.42,1.41,-0.66,2.19,-0.72],["c",0.81,-0.03,1.47,0.21,2.04,0.78],["c",0.57,0.54,0.87,1.26,0.93,2.04],["c",0.03,0.57,-0.09,1.08,-0.36,1.62],["c",-0.42,0.81,-1.02,1.38,-2.82,2.61],["c",-1.14,0.78,-1.44,1.02,-1.8,1.44],["c",-0.18,0.18,-0.39,0.39,-0.45,0.42],["c",-0.27,0.18,-0.57,0.15,-0.81,-0.06],["c",-0.06,-0.09,-0.12,-0.18,-0.15,-0.27],["c",-0.03,-0.06,-0.09,-3.27,-0.18,-8.34],["c",-0.09,-4.53,-0.15,-8.58,-0.18,-9.03],["l",0,-0.78],["l",0.12,-0.06],["c",0.06,-0.03,0.18,-0.09,0.27,-0.12],["z"],["m",3.18,11.01],["c",-0.21,-0.12,-0.54,-0.15,-0.81,-0.06],["c",-0.54,0.15,-0.99,0.63,-1.17,1.26],["c",-0.06,0.3,-0.12,2.88,-0.06,3.87],["c",0.03,0.42,0.03,0.81,0.06,0.9],["l",0.03,0.12],["l",0.45,-0.39],["c",0.63,-0.54,1.26,-1.17,1.56,-1.59],["c",0.3,-0.42,0.6,-0.99,0.72,-1.41],["c",0.18,-0.69,0.09,-1.47,-0.18,-2.07],["c",-0.15,-0.3,-0.33,-0.51,-0.6,-0.63],["z"]],w:6.75,h:18.801},"accidentals.halfflat":{d:[["M",4.83,-14.07],["c",0.33,-0.06,0.87,0,1.08,0.15],["c",0.06,0.03,0.06,0.6,-0.12,9.06],["c",-0.09,5.55,-0.15,9.06,-0.18,9.12],["c",-0.03,0.09,-0.09,0.18,-0.15,0.27],["c",-0.24,0.21,-0.54,0.24,-0.81,0.06],["c",-0.06,-0.03,-0.27,-0.24,-0.45,-0.42],["c",-0.36,-0.42,-0.66,-0.66,-1.8,-1.44],["c",-1.23,-0.84,-1.83,-1.32,-2.25,-1.77],["c",-0.66,-0.78,-0.96,-1.56,-0.93,-2.46],["c",0.09,-1.41,1.11,-2.58,2.4,-2.79],["c",0.3,-0.06,0.84,-0.03,1.23,0.06],["c",0.54,0.12,1.08,0.33,1.53,0.63],["c",0.12,0.09,0.24,0.15,0.24,0.12],["c",0,0,-0.12,-8.37,-0.18,-9.75],["l",0,-0.66],["l",0.12,-0.06],["c",0.06,-0.03,0.18,-0.09,0.27,-0.12],["z"],["m",-1.65,10.95],["c",-0.6,-0.18,-1.08,0.09,-1.38,0.69],["c",-0.27,0.6,-0.36,1.38,-0.18,2.07],["c",0.12,0.42,0.42,0.99,0.72,1.41],["c",0.3,0.42,0.93,1.05,1.56,1.59],["l",0.48,0.39],["l",0,-0.12],["c",0.03,-0.09,0.03,-0.48,0.06,-0.9],["c",0.03,-0.57,0.03,-1.08,0,-2.22],["c",-0.03,-1.62,-0.03,-1.62,-0.24,-2.07],["c",-0.21,-0.42,-0.6,-0.75,-1.02,-0.84],["z"]],w:6.728,h:18.801},"accidentals.dblflat":{d:[["M",-0.36,-14.07],["c",0.33,-0.06,0.87,0,1.08,0.15],["c",0.06,0.03,0.06,0.33,-0.03,4.89],["c",-0.06,2.67,-0.09,5.01,-0.09,5.22],["l",0,0.36],["l",0.15,-0.15],["c",0.36,-0.3,0.75,-0.51,1.2,-0.63],["c",0.33,-0.09,0.96,-0.09,1.26,-0.03],["c",0.27,0.09,0.63,0.27,0.87,0.45],["l",0.21,0.15],["l",0,-0.27],["c",0,-0.15,-0.03,-2.43,-0.09,-5.1],["c",-0.09,-4.56,-0.09,-4.86,-0.03,-4.89],["c",0.15,-0.12,0.39,-0.15,0.72,-0.15],["c",0.3,0,0.54,0.03,0.69,0.15],["c",0.06,0.03,0.06,0.33,-0.03,4.95],["c",-0.06,2.7,-0.09,5.04,-0.09,5.22],["l",0.03,0.3],["l",0.21,-0.15],["c",0.69,-0.48,1.44,-0.69,2.28,-0.69],["c",0.51,0,0.78,0.03,1.2,0.21],["c",1.32,0.63,2.01,2.28,1.53,3.69],["c",-0.21,0.57,-0.51,1.02,-1.05,1.56],["c",-0.42,0.42,-0.81,0.72,-1.92,1.5],["c",-1.26,0.87,-1.5,1.08,-1.86,1.5],["c",-0.39,0.45,-0.54,0.54,-0.81,0.51],["c",-0.18,0,-0.21,0,-0.33,-0.06],["l",-0.21,-0.21],["l",-0.06,-0.12],["l",-0.03,-0.99],["c",-0.03,-0.54,-0.03,-1.29,-0.06,-1.68],["l",0,-0.69],["l",-0.21,0.24],["c",-0.36,0.42,-0.75,0.75,-1.8,1.62],["c",-1.02,0.84,-1.2,0.99,-1.44,1.38],["c",-0.36,0.51,-0.54,0.6,-0.9,0.51],["c",-0.15,-0.03,-0.39,-0.27,-0.42,-0.42],["c",-0.03,-0.06,-0.09,-3.27,-0.18,-8.34],["c",-0.09,-4.53,-0.15,-8.58,-0.18,-9.03],["l",0,-0.78],["l",0.12,-0.06],["c",0.06,-0.03,0.18,-0.09,0.27,-0.12],["z"],["m",2.52,10.98],["c",-0.18,-0.09,-0.48,-0.12,-0.66,-0.06],["c",-0.39,0.15,-0.69,0.54,-0.84,1.14],["c",-0.06,0.24,-0.06,0.39,-0.09,1.74],["c",-0.03,1.44,0,2.73,0.06,3.18],["l",0.03,0.15],["l",0.27,-0.27],["c",0.93,-0.96,1.5,-1.95,1.74,-3.06],["c",0.06,-0.27,0.06,-0.39,0.06,-0.96],["c",0,-0.54,0,-0.69,-0.06,-0.93],["c",-0.09,-0.51,-0.27,-0.81,-0.51,-0.93],["z"],["m",5.43,0],["c",-0.18,-0.09,-0.51,-0.12,-0.72,-0.06],["c",-0.54,0.12,-0.96,0.63,-1.17,1.26],["c",-0.06,0.3,-0.12,2.88,-0.06,3.9],["c",0.03,0.42,0.03,0.81,0.06,0.9],["l",0.03,0.12],["l",0.36,-0.3],["c",0.42,-0.36,1.02,-0.96,1.29,-1.29],["c",0.36,-0.45,0.66,-0.99,0.81,-1.41],["c",0.42,-1.23,0.15,-2.76,-0.6,-3.12],["z"]],w:11.613,h:18.804},"accidentals.dblsharp":{d:[["M",-0.186,-3.96],["c",0.06,-0.03,0.12,-0.06,0.15,-0.06],["c",0.09,0,2.76,0.27,2.79,0.3],["c",0.12,0.03,0.15,0.12,0.15,0.51],["c",0.06,0.96,0.24,1.59,0.57,2.1],["c",0.06,0.09,0.15,0.21,0.18,0.24],["l",0.09,0.06],["l",0.09,-0.06],["c",0.03,-0.03,0.12,-0.15,0.18,-0.24],["c",0.33,-0.51,0.51,-1.14,0.57,-2.1],["c",0,-0.39,0.03,-0.45,0.12,-0.51],["c",0.03,0,0.66,-0.09,1.44,-0.15],["c",1.47,-0.15,1.5,-0.15,1.56,-0.03],["c",0.03,0.06,0,0.42,-0.09,1.44],["c",-0.09,0.72,-0.15,1.35,-0.15,1.38],["c",0,0.03,-0.03,0.09,-0.06,0.12],["c",-0.06,0.06,-0.12,0.09,-0.51,0.09],["c",-1.08,0.06,-1.8,0.3,-2.28,0.75],["l",-0.12,0.09],["l",0.09,0.09],["c",0.12,0.15,0.39,0.33,0.63,0.45],["c",0.42,0.18,0.96,0.27,1.68,0.33],["c",0.39,-0,0.45,0.03,0.51,0.09],["c",0.03,0.03,0.06,0.09,0.06,0.12],["c",0,0.03,0.06,0.66,0.15,1.38],["c",0.09,1.02,0.12,1.38,0.09,1.44],["c",-0.06,0.12,-0.09,0.12,-1.56,-0.03],["c",-0.78,-0.06,-1.41,-0.15,-1.44,-0.15],["c",-0.09,-0.06,-0.12,-0.12,-0.12,-0.54],["c",-0.06,-0.93,-0.24,-1.56,-0.57,-2.07],["c",-0.06,-0.09,-0.15,-0.21,-0.18,-0.24],["l",-0.09,-0.06],["l",-0.09,0.06],["c",-0.03,0.03,-0.12,0.15,-0.18,0.24],["c",-0.33,0.51,-0.51,1.14,-0.57,2.07],["c",0,0.42,-0.03,0.48,-0.12,0.54],["c",-0.03,0,-0.66,0.09,-1.44,0.15],["c",-1.47,0.15,-1.5,0.15,-1.56,0.03],["c",-0.03,-0.06,0,-0.42,0.09,-1.44],["c",0.09,-0.72,0.15,-1.35,0.15,-1.38],["c",0,-0.03,0.03,-0.09,0.06,-0.12],["c",0.06,-0.06,0.12,-0.09,0.51,-0.09],["c",0.72,-0.06,1.26,-0.15,1.68,-0.33],["c",0.24,-0.12,0.51,-0.3,0.63,-0.45],["l",0.09,-0.09],["l",-0.12,-0.09],["c",-0.48,-0.45,-1.2,-0.69,-2.28,-0.75],["c",-0.39,0,-0.45,-0.03,-0.51,-0.09],["c",-0.03,-0.03,-0.06,-0.09,-0.06,-0.12],["c",0,-0.03,-0.06,-0.63,-0.12,-1.38],["c",-0.09,-0.72,-0.15,-1.35,-0.15,-1.38],["z"]],w:7.961,h:7.977},"dots.dot":{d:[["M",1.32,-1.68],["c",0.09,-0.03,0.27,-0.06,0.39,-0.06],["c",0.96,0,1.74,0.78,1.74,1.71],["c",0,0.96,-0.78,1.74,-1.71,1.74],["c",-0.96,0,-1.74,-0.78,-1.74,-1.71],["c",0,-0.78,0.54,-1.5,1.32,-1.68],["z"]],w:3.45,h:3.45},"noteheads.dbl":{d:[["M",-0.69,-4.02],["c",0.18,-0.09,0.36,-0.09,0.54,0],["c",0.18,0.09,0.24,0.15,0.33,0.3],["c",0.06,0.15,0.06,0.18,0.06,1.41],["l",-0,1.23],["l",0.12,-0.18],["c",0.72,-1.26,2.64,-2.31,4.86,-2.64],["c",0.81,-0.15,1.11,-0.15,2.13,-0.15],["c",0.99,0,1.29,0,2.1,0.15],["c",0.75,0.12,1.38,0.27,2.04,0.54],["c",1.35,0.51,2.34,1.26,2.82,2.1],["l",0.12,0.18],["l",0,-1.23],["c",0,-1.2,0,-1.26,0.06,-1.38],["c",0.09,-0.18,0.15,-0.24,0.33,-0.33],["c",0.18,-0.09,0.36,-0.09,0.54,0],["c",0.18,0.09,0.24,0.15,0.33,0.3],["l",0.06,0.15],["l",0,3.54],["l",0,3.54],["l",-0.06,0.15],["c",-0.09,0.18,-0.15,0.24,-0.33,0.33],["c",-0.18,0.09,-0.36,0.09,-0.54,0],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["c",-0.06,-0.12,-0.06,-0.18,-0.06,-1.38],["l",0,-1.23],["l",-0.12,0.18],["c",-0.48,0.84,-1.47,1.59,-2.82,2.1],["c",-0.84,0.33,-1.71,0.54,-2.85,0.66],["c",-0.45,0.06,-2.16,0.06,-2.61,0],["c",-1.14,-0.12,-2.01,-0.33,-2.85,-0.66],["c",-1.35,-0.51,-2.34,-1.26,-2.82,-2.1],["l",-0.12,-0.18],["l",0,1.23],["c",0,1.23,0,1.26,-0.06,1.38],["c",-0.09,0.18,-0.15,0.24,-0.33,0.33],["c",-0.18,0.09,-0.36,0.09,-0.54,0],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["l",-0.06,-0.15],["l",0,-3.54],["c",0,-3.48,0,-3.54,0.06,-3.66],["c",0.09,-0.18,0.15,-0.24,0.33,-0.33],["z"],["m",7.71,0.63],["c",-0.36,-0.06,-0.9,-0.06,-1.14,0],["c",-0.3,0.03,-0.66,0.24,-0.87,0.42],["c",-0.6,0.54,-0.9,1.62,-0.75,2.82],["c",0.12,0.93,0.51,1.68,1.11,2.31],["c",0.75,0.72,1.83,1.2,2.85,1.26],["c",1.05,0.06,1.83,-0.54,2.1,-1.65],["c",0.21,-0.9,0.12,-1.95,-0.24,-2.82],["c",-0.36,-0.81,-1.08,-1.53,-1.95,-1.95],["c",-0.3,-0.15,-0.78,-0.3,-1.11,-0.39],["z"]],w:16.83,h:8.145},"noteheads.whole":{d:[["M",6.51,-4.05],["c",0.51,-0.03,2.01,0,2.52,0.03],["c",1.41,0.18,2.64,0.51,3.72,1.08],["c",1.2,0.63,1.95,1.41,2.19,2.31],["c",0.09,0.33,0.09,0.9,-0,1.23],["c",-0.24,0.9,-0.99,1.68,-2.19,2.31],["c",-1.08,0.57,-2.28,0.9,-3.75,1.08],["c",-0.66,0.06,-2.31,0.06,-2.97,0],["c",-1.47,-0.18,-2.67,-0.51,-3.75,-1.08],["c",-1.2,-0.63,-1.95,-1.41,-2.19,-2.31],["c",-0.09,-0.33,-0.09,-0.9,-0,-1.23],["c",0.24,-0.9,0.99,-1.68,2.19,-2.31],["c",1.2,-0.63,2.61,-0.99,4.23,-1.11],["z"],["m",0.57,0.66],["c",-0.87,-0.15,-1.53,0,-2.04,0.51],["c",-0.15,0.15,-0.24,0.27,-0.33,0.48],["c",-0.24,0.51,-0.36,1.08,-0.33,1.77],["c",0.03,0.69,0.18,1.26,0.42,1.77],["c",0.6,1.17,1.74,1.98,3.18,2.22],["c",1.11,0.21,1.95,-0.15,2.34,-0.99],["c",0.24,-0.51,0.36,-1.08,0.33,-1.8],["c",-0.06,-1.11,-0.45,-2.04,-1.17,-2.76],["c",-0.63,-0.63,-1.47,-1.05,-2.4,-1.2],["z"]],w:14.985,h:8.097},"noteheads.half":{d:[["M",7.44,-4.05],["c",0.06,-0.03,0.27,-0.03,0.48,-0.03],["c",1.05,0,1.71,0.24,2.1,0.81],["c",0.42,0.6,0.45,1.35,0.18,2.4],["c",-0.42,1.59,-1.14,2.73,-2.16,3.39],["c",-1.41,0.93,-3.18,1.44,-5.4,1.53],["c",-1.17,0.03,-1.89,-0.21,-2.28,-0.81],["c",-0.42,-0.6,-0.45,-1.35,-0.18,-2.4],["c",0.42,-1.59,1.14,-2.73,2.16,-3.39],["c",0.63,-0.42,1.23,-0.72,1.98,-0.96],["c",0.9,-0.3,1.65,-0.42,3.12,-0.54],["z"],["m",1.29,0.87],["c",-0.27,-0.09,-0.63,-0.12,-0.9,-0.03],["c",-0.72,0.24,-1.53,0.69,-3.27,1.8],["c",-2.34,1.5,-3.3,2.25,-3.57,2.79],["c",-0.36,0.72,-0.06,1.5,0.66,1.77],["c",0.24,0.12,0.69,0.09,0.99,0],["c",0.84,-0.3,1.92,-0.93,4.14,-2.37],["c",1.62,-1.08,2.37,-1.71,2.61,-2.19],["c",0.36,-0.72,0.06,-1.5,-0.66,-1.77],["z"]],w:10.37,h:8.132},"noteheads.quarter":{d:[["M",6.09,-4.05],["c",0.36,-0.03,1.2,0,1.53,0.06],["c",1.17,0.24,1.89,0.84,2.16,1.83],["c",0.06,0.18,0.06,0.3,0.06,0.66],["c",0,0.45,0,0.63,-0.15,1.08],["c",-0.66,2.04,-3.06,3.93,-5.52,4.38],["c",-0.54,0.09,-1.44,0.09,-1.83,0.03],["c",-1.23,-0.27,-1.98,-0.87,-2.25,-1.86],["c",-0.06,-0.18,-0.06,-0.3,-0.06,-0.66],["c",0,-0.45,0,-0.63,0.15,-1.08],["c",0.24,-0.78,0.75,-1.53,1.44,-2.22],["c",1.2,-1.2,2.85,-2.01,4.47,-2.22],["z"]],w:9.81,h:8.094},"scripts.ufermata":{d:[["M",-0.75,-10.77],["c",0.12,0,0.45,-0.03,0.69,-0.03],["c",2.91,-0.03,5.55,1.53,7.41,4.35],["c",1.17,1.71,1.95,3.72,2.43,6.03],["c",0.12,0.51,0.12,0.57,0.03,0.69],["c",-0.12,0.21,-0.48,0.27,-0.69,0.12],["c",-0.12,-0.09,-0.18,-0.24,-0.27,-0.69],["c",-0.78,-3.63,-3.42,-6.54,-6.78,-7.38],["c",-0.78,-0.21,-1.2,-0.24,-2.07,-0.24],["c",-0.63,-0,-0.84,-0,-1.2,0.06],["c",-1.83,0.27,-3.42,1.08,-4.8,2.37],["c",-1.41,1.35,-2.4,3.21,-2.85,5.19],["c",-0.09,0.45,-0.15,0.6,-0.27,0.69],["c",-0.21,0.15,-0.57,0.09,-0.69,-0.12],["c",-0.09,-0.12,-0.09,-0.18,0.03,-0.69],["c",0.33,-1.62,0.78,-3,1.47,-4.38],["c",1.77,-3.54,4.44,-5.67,7.56,-5.97],["z"],["m",0.33,7.47],["c",1.38,-0.3,2.58,0.9,2.31,2.25],["c",-0.15,0.72,-0.78,1.35,-1.47,1.5],["c",-1.38,0.27,-2.58,-0.93,-2.31,-2.31],["c",0.15,-0.69,0.78,-1.29,1.47,-1.44],["z"]],w:19.748,h:11.289},"scripts.dfermata":{d:[["M",-9.63,-0.42],["c",0.15,-0.09,0.36,-0.06,0.51,0.03],["c",0.12,0.09,0.18,0.24,0.27,0.66],["c",0.78,3.66,3.42,6.57,6.78,7.41],["c",0.78,0.21,1.2,0.24,2.07,0.24],["c",0.63,-0,0.84,-0,1.2,-0.06],["c",1.83,-0.27,3.42,-1.08,4.8,-2.37],["c",1.41,-1.35,2.4,-3.21,2.85,-5.22],["c",0.09,-0.42,0.15,-0.57,0.27,-0.66],["c",0.21,-0.15,0.57,-0.09,0.69,0.12],["c",0.09,0.12,0.09,0.18,-0.03,0.69],["c",-0.33,1.62,-0.78,3,-1.47,4.38],["c",-1.92,3.84,-4.89,6,-8.31,6],["c",-3.42,0,-6.39,-2.16,-8.31,-6],["c",-0.48,-0.96,-0.84,-1.92,-1.14,-2.97],["c",-0.18,-0.69,-0.42,-1.74,-0.42,-1.92],["c",0,-0.12,0.09,-0.27,0.24,-0.33],["z"],["m",9.21,0],["c",1.2,-0.27,2.34,0.63,2.34,1.86],["c",-0,0.9,-0.66,1.68,-1.5,1.89],["c",-1.38,0.27,-2.58,-0.93,-2.31,-2.31],["c",0.15,-0.69,0.78,-1.29,1.47,-1.44],["z"]],w:19.744,h:11.274},"scripts.sforzato":{d:[["M",-6.45,-3.69],["c",0.06,-0.03,0.15,-0.06,0.18,-0.06],["c",0.06,0,2.85,0.72,6.24,1.59],["l",6.33,1.65],["c",0.33,0.06,0.45,0.21,0.45,0.51],["c",0,0.3,-0.12,0.45,-0.45,0.51],["l",-6.33,1.65],["c",-3.39,0.87,-6.18,1.59,-6.21,1.59],["c",-0.21,-0,-0.48,-0.24,-0.51,-0.45],["c",0,-0.15,0.06,-0.36,0.18,-0.45],["c",0.09,-0.06,0.87,-0.27,3.84,-1.05],["c",2.04,-0.54,3.84,-0.99,4.02,-1.02],["c",0.15,-0.06,1.14,-0.24,2.22,-0.42],["c",1.05,-0.18,1.92,-0.36,1.92,-0.36],["c",0,-0,-0.87,-0.18,-1.92,-0.36],["c",-1.08,-0.18,-2.07,-0.36,-2.22,-0.42],["c",-0.18,-0.03,-1.98,-0.48,-4.02,-1.02],["c",-2.97,-0.78,-3.75,-0.99,-3.84,-1.05],["c",-0.12,-0.09,-0.18,-0.3,-0.18,-0.45],["c",0.03,-0.15,0.15,-0.3,0.3,-0.39],["z"]],w:13.5,h:7.5},"scripts.staccato":{d:[["M",-0.36,-1.47],["c",0.93,-0.21,1.86,0.51,1.86,1.47],["c",-0,0.93,-0.87,1.65,-1.8,1.47],["c",-0.54,-0.12,-1.02,-0.57,-1.14,-1.08],["c",-0.21,-0.81,0.27,-1.65,1.08,-1.86],["z"]],w:2.989,h:3.004},"scripts.tenuto":{d:[["M",-4.2,-0.48],["l",0.12,-0.06],["l",4.08,0],["l",4.08,0],["l",0.12,0.06],["c",0.39,0.21,0.39,0.75,0,0.96],["l",-0.12,0.06],["l",-4.08,0],["l",-4.08,0],["l",-0.12,-0.06],["c",-0.39,-0.21,-0.39,-0.75,0,-0.96],["z"]],w:8.985,h:1.08},"scripts.umarcato":{d:[["M",-0.15,-8.19],["c",0.15,-0.12,0.36,-0.03,0.45,0.15],["c",0.21,0.42,3.45,7.65,3.45,7.71],["c",-0,0.12,-0.12,0.27,-0.21,0.3],["c",-0.03,0.03,-0.51,0.03,-1.14,0.03],["c",-1.05,0,-1.08,0,-1.17,-0.06],["c",-0.09,-0.06,-0.24,-0.36,-1.17,-2.4],["c",-0.57,-1.29,-1.05,-2.34,-1.08,-2.34],["c",-0,-0.03,-0.51,1.02,-1.08,2.34],["c",-0.93,2.07,-1.08,2.34,-1.14,2.4],["c",-0.06,0.03,-0.15,0.06,-0.18,0.06],["c",-0.15,0,-0.33,-0.18,-0.33,-0.33],["c",-0,-0.06,3.24,-7.32,3.45,-7.71],["c",0.03,-0.06,0.09,-0.15,0.15,-0.15],["z"]],w:7.5,h:8.245},"scripts.dmarcato":{d:[["M",-3.57,0.03],["c",0.03,0,0.57,-0.03,1.17,-0.03],["c",1.05,0,1.08,0,1.17,0.06],["c",0.09,0.06,0.24,0.36,1.17,2.4],["c",0.57,1.29,1.05,2.34,1.08,2.34],["c",0,0.03,0.51,-1.02,1.08,-2.34],["c",0.93,-2.07,1.08,-2.34,1.14,-2.4],["c",0.06,-0.03,0.15,-0.06,0.18,-0.06],["c",0.15,0,0.33,0.18,0.33,0.33],["c",0,0.09,-3.45,7.74,-3.54,7.83],["c",-0.12,0.12,-0.3,0.12,-0.42,0],["c",-0.09,-0.09,-3.54,-7.74,-3.54,-7.83],["c",0,-0.09,0.12,-0.27,0.18,-0.3],["z"]],w:7.5,h:8.25},"scripts.stopped":{d:[["M",-0.27,-4.08],["c",0.18,-0.09,0.36,-0.09,0.54,0],["c",0.18,0.09,0.24,0.15,0.33,0.3],["l",0.06,0.15],["l",-0,1.5],["l",-0,1.47],["l",1.47,0],["l",1.5,0],["l",0.15,0.06],["c",0.15,0.09,0.21,0.15,0.3,0.33],["c",0.09,0.18,0.09,0.36,-0,0.54],["c",-0.09,0.18,-0.15,0.24,-0.33,0.33],["c",-0.12,0.06,-0.18,0.06,-1.62,0.06],["l",-1.47,0],["l",-0,1.47],["l",-0,1.47],["l",-0.06,0.15],["c",-0.09,0.18,-0.15,0.24,-0.33,0.33],["c",-0.18,0.09,-0.36,0.09,-0.54,0],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["l",-0.06,-0.15],["l",-0,-1.47],["l",-0,-1.47],["l",-1.47,0],["c",-1.44,0,-1.5,0,-1.62,-0.06],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["c",-0.09,-0.18,-0.09,-0.36,-0,-0.54],["c",0.09,-0.18,0.15,-0.24,0.33,-0.33],["l",0.15,-0.06],["l",1.47,0],["l",1.47,0],["l",-0,-1.47],["c",-0,-1.44,-0,-1.5,0.06,-1.62],["c",0.09,-0.18,0.15,-0.24,0.33,-0.33],["z"]],w:8.295,h:8.295},"scripts.upbow":{d:[["M",-4.65,-15.54],["c",0.12,-0.09,0.36,-0.06,0.48,0.03],["c",0.03,0.03,0.09,0.09,0.12,0.15],["c",0.03,0.06,0.66,2.13,1.41,4.62],["c",1.35,4.41,1.38,4.56,2.01,6.96],["l",0.63,2.46],["l",0.63,-2.46],["c",0.63,-2.4,0.66,-2.55,2.01,-6.96],["c",0.75,-2.49,1.38,-4.56,1.41,-4.62],["c",0.06,-0.15,0.18,-0.21,0.36,-0.24],["c",0.15,0,0.3,0.06,0.39,0.18],["c",0.15,0.21,0.24,-0.18,-2.1,7.56],["c",-1.2,3.96,-2.22,7.32,-2.25,7.41],["c",0,0.12,-0.06,0.27,-0.09,0.3],["c",-0.12,0.21,-0.6,0.21,-0.72,0],["c",-0.03,-0.03,-0.09,-0.18,-0.09,-0.3],["c",-0.03,-0.09,-1.05,-3.45,-2.25,-7.41],["c",-2.34,-7.74,-2.25,-7.35,-2.1,-7.56],["c",0.03,-0.03,0.09,-0.09,0.15,-0.12],["z"]],w:9.73,h:15.608},"scripts.downbow":{d:[["M",-5.55,-9.93],["l",0.09,-0.06],["l",5.46,0],["l",5.46,0],["l",0.09,0.06],["l",0.06,0.09],["l",0,4.77],["c",0,5.28,0,4.89,-0.18,5.01],["c",-0.18,0.12,-0.42,0.06,-0.54,-0.12],["c",-0.06,-0.09,-0.06,-0.18,-0.06,-2.97],["l",0,-2.85],["l",-4.83,0],["l",-4.83,0],["l",0,2.85],["c",0,2.79,0,2.88,-0.06,2.97],["c",-0.15,0.24,-0.51,0.24,-0.66,0],["c",-0.06,-0.09,-0.06,-0.21,-0.06,-4.89],["l",0,-4.77],["z"]],w:11.22,h:9.992},"scripts.turn":{d:[["M",-4.77,-3.9],["c",0.36,-0.06,1.05,-0.06,1.44,0.03],["c",0.78,0.15,1.5,0.51,2.34,1.14],["c",0.6,0.45,1.05,0.87,2.22,2.01],["c",1.11,1.08,1.62,1.5,2.22,1.86],["c",0.6,0.36,1.32,0.57,1.92,0.57],["c",0.9,-0,1.71,-0.57,1.89,-1.35],["c",0.24,-0.93,-0.39,-1.89,-1.35,-2.1],["l",-0.15,-0.06],["l",-0.09,0.15],["c",-0.03,0.09,-0.15,0.24,-0.24,0.33],["c",-0.72,0.72,-2.04,0.54,-2.49,-0.36],["c",-0.48,-0.93,0.03,-1.86,1.17,-2.19],["c",0.3,-0.09,1.02,-0.09,1.35,-0],["c",0.99,0.27,1.74,0.87,2.25,1.83],["c",0.69,1.41,0.63,3,-0.21,4.26],["c",-0.21,0.3,-0.69,0.81,-0.99,1.02],["c",-0.3,0.21,-0.84,0.45,-1.17,0.54],["c",-1.23,0.36,-2.49,0.15,-3.72,-0.6],["c",-0.75,-0.48,-1.41,-1.02,-2.85,-2.46],["c",-1.11,-1.08,-1.62,-1.5,-2.22,-1.86],["c",-0.6,-0.36,-1.32,-0.57,-1.92,-0.57],["c",-0.9,0,-1.71,0.57,-1.89,1.35],["c",-0.24,0.93,0.39,1.89,1.35,2.1],["l",0.15,0.06],["l",0.09,-0.15],["c",0.03,-0.09,0.15,-0.24,0.24,-0.33],["c",0.72,-0.72,2.04,-0.54,2.49,0.36],["c",0.48,0.93,-0.03,1.86,-1.17,2.19],["c",-0.3,0.09,-1.02,0.09,-1.35,0],["c",-0.99,-0.27,-1.74,-0.87,-2.25,-1.83],["c",-0.69,-1.41,-0.63,-3,0.21,-4.26],["c",0.21,-0.3,0.69,-0.81,0.99,-1.02],["c",0.48,-0.33,1.11,-0.57,1.74,-0.66],["z"]],w:16.366,h:7.893},"scripts.trill":{d:[["M",-0.51,-16.02],["c",0.12,-0.09,0.21,-0.18,0.21,-0.18],["l",-0.81,4.02],["l",-0.81,4.02],["c",0.03,0,0.51,-0.27,1.08,-0.6],["c",0.6,-0.3,1.14,-0.63,1.26,-0.66],["c",1.14,-0.54,2.31,-0.6,3.09,-0.18],["c",0.27,0.15,0.54,0.36,0.6,0.51],["l",0.06,0.12],["l",0.21,-0.21],["c",0.9,-0.81,2.22,-0.99,3.12,-0.42],["c",0.6,0.42,0.9,1.14,0.78,2.07],["c",-0.15,1.29,-1.05,2.31,-1.95,2.25],["c",-0.48,-0.03,-0.78,-0.3,-0.96,-0.81],["c",-0.09,-0.27,-0.09,-0.9,-0.03,-1.2],["c",0.21,-0.75,0.81,-1.23,1.59,-1.32],["l",0.24,-0.03],["l",-0.09,-0.12],["c",-0.51,-0.66,-1.62,-0.63,-2.31,0.03],["c",-0.39,0.42,-0.3,0.09,-1.23,4.77],["l",-0.81,4.14],["c",-0.03,0,-0.12,-0.03,-0.21,-0.09],["c",-0.33,-0.15,-0.54,-0.18,-0.99,-0.18],["c",-0.42,0,-0.66,0.03,-1.05,0.18],["c",-0.12,0.06,-0.21,0.09,-0.21,0.09],["c",0,-0.03,0.36,-1.86,0.81,-4.11],["c",0.9,-4.47,0.87,-4.26,0.69,-4.53],["c",-0.21,-0.36,-0.66,-0.51,-1.17,-0.36],["c",-0.15,0.06,-2.22,1.14,-2.58,1.38],["c",-0.12,0.09,-0.12,0.09,-0.21,0.6],["l",-0.09,0.51],["l",0.21,0.24],["c",0.63,0.75,1.02,1.47,1.2,2.19],["c",0.06,0.27,0.06,0.36,0.06,0.81],["c",0,0.42,0,0.54,-0.06,0.78],["c",-0.15,0.54,-0.33,0.93,-0.63,1.35],["c",-0.18,0.24,-0.57,0.63,-0.81,0.78],["c",-0.24,0.15,-0.63,0.36,-0.84,0.42],["c",-0.27,0.06,-0.66,0.06,-0.87,0.03],["c",-0.81,-0.18,-1.32,-1.05,-1.38,-2.46],["c",-0.03,-0.6,0.03,-0.99,0.33,-2.46],["c",0.21,-1.08,0.24,-1.32,0.21,-1.29],["c",-1.2,0.48,-2.4,0.75,-3.21,0.72],["c",-0.69,-0.06,-1.17,-0.3,-1.41,-0.72],["c",-0.39,-0.75,-0.12,-1.8,0.66,-2.46],["c",0.24,-0.18,0.69,-0.42,1.02,-0.51],["c",0.69,-0.18,1.53,-0.15,2.31,0.09],["c",0.3,0.09,0.75,0.3,0.99,0.45],["c",0.12,0.09,0.15,0.09,0.15,0.03],["c",0.03,-0.03,0.33,-1.59,0.72,-3.45],["c",0.36,-1.86,0.66,-3.42,0.69,-3.45],["c",0,-0.03,0.03,-0.03,0.21,0.03],["c",0.21,0.06,0.27,0.06,0.48,0.06],["c",0.42,-0.03,0.78,-0.18,1.26,-0.48],["c",0.15,-0.12,0.36,-0.27,0.48,-0.39],["z"],["m",-5.73,7.68],["c",-0.27,-0.03,-0.96,-0.06,-1.2,-0.03],["c",-0.81,0.12,-1.35,0.57,-1.5,1.2],["c",-0.18,0.66,0.12,1.14,0.75,1.29],["c",0.66,0.12,1.92,-0.12,3.18,-0.66],["l",0.33,-0.15],["l",0.09,-0.39],["c",0.06,-0.21,0.09,-0.42,0.09,-0.45],["c",0,-0.03,-0.45,-0.3,-0.75,-0.45],["c",-0.27,-0.15,-0.66,-0.27,-0.99,-0.36],["z"],["m",4.29,3.63],["c",-0.24,-0.39,-0.51,-0.75,-0.51,-0.69],["c",-0.06,0.12,-0.39,1.92,-0.45,2.28],["c",-0.09,0.54,-0.12,1.14,-0.06,1.38],["c",0.06,0.42,0.21,0.6,0.51,0.57],["c",0.39,-0.06,0.75,-0.48,0.93,-1.14],["c",0.09,-0.33,0.09,-1.05,-0,-1.38],["c",-0.09,-0.39,-0.24,-0.69,-0.42,-1.02],["z"]],w:17.963,h:16.49},"scripts.segno":{d:[["M",-3.72,-11.22],["c",0.78,-0.09,1.59,0.03,2.31,0.42],["c",1.2,0.6,2.01,1.71,2.31,3.09],["c",0.09,0.42,0.09,1.2,0.03,1.5],["c",-0.15,0.45,-0.39,0.81,-0.66,0.93],["c",-0.33,0.18,-0.84,0.21,-1.23,0.15],["c",-0.81,-0.18,-1.32,-0.93,-1.26,-1.89],["c",0.03,-0.36,0.09,-0.57,0.24,-0.9],["c",0.15,-0.33,0.45,-0.6,0.72,-0.75],["c",0.12,-0.06,0.18,-0.09,0.18,-0.12],["c",0,-0.03,-0.03,-0.15,-0.09,-0.24],["c",-0.18,-0.45,-0.54,-0.87,-0.96,-1.08],["c",-1.11,-0.57,-2.34,-0.18,-2.88,0.9],["c",-0.24,0.51,-0.33,1.11,-0.24,1.83],["c",0.27,1.92,1.5,3.54,3.93,5.13],["c",0.48,0.33,1.26,0.78,1.29,0.78],["c",0.03,0,1.35,-2.19,2.94,-4.89],["l",2.88,-4.89],["l",0.84,0],["l",0.87,0],["l",-0.03,0.06],["c",-0.15,0.21,-6.15,10.41,-6.15,10.44],["c",0,0,0.21,0.15,0.48,0.27],["c",2.61,1.47,4.35,3.03,5.13,4.65],["c",1.14,2.34,0.51,5.07,-1.44,6.39],["c",-0.66,0.42,-1.32,0.63,-2.13,0.69],["c",-2.01,0.09,-3.81,-1.41,-4.26,-3.54],["c",-0.09,-0.42,-0.09,-1.2,-0.03,-1.5],["c",0.15,-0.45,0.39,-0.81,0.66,-0.93],["c",0.33,-0.18,0.84,-0.21,1.23,-0.15],["c",0.81,0.18,1.32,0.93,1.26,1.89],["c",-0.03,0.36,-0.09,0.57,-0.24,0.9],["c",-0.15,0.33,-0.45,0.6,-0.72,0.75],["c",-0.12,0.06,-0.18,0.09,-0.18,0.12],["c",0,0.03,0.03,0.15,0.09,0.24],["c",0.18,0.45,0.54,0.87,0.96,1.08],["c",1.11,0.57,2.34,0.18,2.88,-0.9],["c",0.24,-0.51,0.33,-1.11,0.24,-1.83],["c",-0.27,-1.92,-1.5,-3.54,-3.93,-5.13],["c",-0.48,-0.33,-1.26,-0.78,-1.29,-0.78],["c",-0.03,0,-1.35,2.19,-2.91,4.89],["l",-2.88,4.89],["l",-0.87,0],["l",-0.87,0],["l",0.03,-0.06],["c",0.15,-0.21,6.15,-10.41,6.15,-10.44],["c",0,0,-0.21,-0.15,-0.48,-0.3],["c",-2.61,-1.44,-4.35,-3,-5.13,-4.62],["c",-0.9,-1.89,-0.72,-4.02,0.48,-5.52],["c",0.69,-0.84,1.68,-1.41,2.73,-1.53],["z"],["m",8.76,9.09],["c",0.03,-0.03,0.15,-0.03,0.27,-0.03],["c",0.33,0.03,0.57,0.18,0.72,0.48],["c",0.09,0.18,0.09,0.57,0,0.75],["c",-0.09,0.18,-0.21,0.3,-0.36,0.39],["c",-0.15,0.06,-0.21,0.06,-0.39,0.06],["c",-0.21,0,-0.27,0,-0.39,-0.06],["c",-0.3,-0.15,-0.48,-0.45,-0.48,-0.75],["c",0,-0.39,0.24,-0.72,0.63,-0.84],["z"],["m",-10.53,2.61],["c",0.03,-0.03,0.15,-0.03,0.27,-0.03],["c",0.33,0.03,0.57,0.18,0.72,0.48],["c",0.09,0.18,0.09,0.57,0,0.75],["c",-0.09,0.18,-0.21,0.3,-0.36,0.39],["c",-0.15,0.06,-0.21,0.06,-0.39,0.06],["c",-0.21,0,-0.27,0,-0.39,-0.06],["c",-0.3,-0.15,-0.48,-0.45,-0.48,-0.75],["c",0,-0.39,0.24,-0.72,0.63,-0.84],["z"]],w:15,h:22.504},"scripts.coda":{d:[["M",-0.21,-10.47],["c",0.18,-0.12,0.42,-0.06,0.54,0.12],["c",0.06,0.09,0.06,0.18,0.06,1.5],["l",0,1.38],["l",0.18,0],["c",0.39,0.06,0.96,0.24,1.38,0.48],["c",1.68,0.93,2.82,3.24,3.03,6.12],["c",0.03,0.24,0.03,0.45,0.03,0.45],["c",0,0.03,0.6,0.03,1.35,0.03],["c",1.5,0,1.47,0,1.59,0.18],["c",0.09,0.12,0.09,0.3,-0,0.42],["c",-0.12,0.18,-0.09,0.18,-1.59,0.18],["c",-0.75,0,-1.35,0,-1.35,0.03],["c",-0,0,-0,0.21,-0.03,0.42],["c",-0.24,3.15,-1.53,5.58,-3.45,6.36],["c",-0.27,0.12,-0.72,0.24,-0.96,0.27],["l",-0.18,-0],["l",-0,1.38],["c",-0,1.32,-0,1.41,-0.06,1.5],["c",-0.15,0.24,-0.51,0.24,-0.66,-0],["c",-0.06,-0.09,-0.06,-0.18,-0.06,-1.5],["l",-0,-1.38],["l",-0.18,-0],["c",-0.39,-0.06,-0.96,-0.24,-1.38,-0.48],["c",-1.68,-0.93,-2.82,-3.24,-3.03,-6.15],["c",-0.03,-0.21,-0.03,-0.42,-0.03,-0.42],["c",0,-0.03,-0.6,-0.03,-1.35,-0.03],["c",-1.5,-0,-1.47,-0,-1.59,-0.18],["c",-0.09,-0.12,-0.09,-0.3,0,-0.42],["c",0.12,-0.18,0.09,-0.18,1.59,-0.18],["c",0.75,-0,1.35,-0,1.35,-0.03],["c",0,-0,0,-0.21,0.03,-0.45],["c",0.24,-3.12,1.53,-5.55,3.45,-6.33],["c",0.27,-0.12,0.72,-0.24,0.96,-0.27],["l",0.18,-0],["l",0,-1.38],["c",0,-1.53,0,-1.5,0.18,-1.62],["z"],["m",-0.18,6.93],["c",0,-2.97,0,-3.15,-0.06,-3.15],["c",-0.09,0,-0.51,0.15,-0.66,0.21],["c",-0.87,0.51,-1.38,1.62,-1.56,3.51],["c",-0.06,0.54,-0.12,1.59,-0.12,2.16],["l",0,0.42],["l",1.2,0],["l",1.2,0],["l",0,-3.15],["z"],["m",1.17,-3.06],["c",-0.09,-0.03,-0.21,-0.06,-0.27,-0.09],["l",-0.12,0],["l",0,3.15],["l",0,3.15],["l",1.2,0],["l",1.2,0],["l",0,-0.81],["c",-0.06,-2.4,-0.33,-3.69,-0.93,-4.59],["c",-0.27,-0.39,-0.66,-0.69,-1.08,-0.81],["z"],["m",-1.17,10.14],["l",0,-3.15],["l",-1.2,-0],["l",-1.2,-0],["l",0,0.81],["c",0.03,0.96,0.06,1.47,0.15,2.13],["c",0.24,2.04,0.96,3.12,2.13,3.36],["l",0.12,-0],["l",0,-3.15],["z"],["m",3.18,-2.34],["l",0,-0.81],["l",-1.2,0],["l",-1.2,0],["l",0,3.15],["l",0,3.15],["l",0.12,0],["c",1.17,-0.24,1.89,-1.32,2.13,-3.36],["c",0.09,-0.66,0.12,-1.17,0.15,-2.13],["z"]],w:16.035,h:21.062},"scripts.comma":{d:[["M",1.14,-4.62],["c",0.3,-0.12,0.69,-0.03,0.93,0.15],["c",0.12,0.12,0.36,0.45,0.51,0.78],["c",0.9,1.77,0.54,4.05,-1.08,6.75],["c",-0.36,0.63,-0.87,1.38,-0.96,1.44],["c",-0.18,0.12,-0.42,0.06,-0.54,-0.12],["c",-0.09,-0.18,-0.09,-0.3,0.12,-0.6],["c",0.96,-1.44,1.44,-2.97,1.38,-4.35],["c",-0.06,-0.93,-0.3,-1.68,-0.78,-2.46],["c",-0.27,-0.39,-0.33,-0.63,-0.24,-0.96],["c",0.09,-0.27,0.36,-0.54,0.66,-0.63],["z"]],w:3.042,h:9.237},"scripts.roll":{d:[["M",1.95,-6],["c",0.21,-0.09,0.36,-0.09,0.57,0],["c",0.39,0.15,0.63,0.39,1.47,1.35],["c",0.66,0.75,0.78,0.87,1.08,1.05],["c",0.75,0.45,1.65,0.42,2.4,-0.06],["c",0.12,-0.09,0.27,-0.27,0.54,-0.6],["c",0.42,-0.54,0.51,-0.63,0.69,-0.63],["c",0.09,0,0.3,0.12,0.36,0.21],["c",0.09,0.12,0.12,0.3,0.03,0.42],["c",-0.06,0.12,-3.15,3.9,-3.3,4.08],["c",-0.06,0.06,-0.18,0.12,-0.27,0.18],["c",-0.27,0.12,-0.6,0.06,-0.99,-0.27],["c",-0.27,-0.21,-0.42,-0.39,-1.08,-1.14],["c",-0.63,-0.72,-0.81,-0.9,-1.17,-1.08],["c",-0.36,-0.18,-0.57,-0.21,-0.99,-0.21],["c",-0.39,0,-0.63,0.03,-0.93,0.18],["c",-0.36,0.15,-0.51,0.27,-0.9,0.81],["c",-0.24,0.27,-0.45,0.51,-0.48,0.54],["c",-0.12,0.09,-0.27,0.06,-0.39,0],["c",-0.24,-0.15,-0.33,-0.39,-0.21,-0.6],["c",0.09,-0.12,3.18,-3.87,3.33,-4.02],["c",0.06,-0.06,0.18,-0.15,0.24,-0.21],["z"]],w:10.817,h:6.125},"scripts.prall":{d:[["M",-4.38,-3.69],["c",0.06,-0.03,0.18,-0.06,0.24,-0.06],["c",0.3,0,0.27,-0.03,1.89,1.95],["l",1.53,1.83],["c",0.03,-0,0.57,-0.84,1.23,-1.83],["c",1.14,-1.68,1.23,-1.83,1.35,-1.89],["c",0.06,-0.03,0.18,-0.06,0.24,-0.06],["c",0.3,0,0.27,-0.03,1.89,1.95],["l",1.53,1.83],["l",0.48,-0.69],["c",0.51,-0.78,0.54,-0.84,0.69,-0.9],["c",0.42,-0.18,0.87,0.15,0.81,0.6],["c",-0.03,0.12,-0.3,0.51,-1.5,2.37],["c",-1.38,2.07,-1.5,2.22,-1.62,2.28],["c",-0.06,0.03,-0.18,0.06,-0.24,0.06],["c",-0.3,0,-0.27,0.03,-1.89,-1.95],["l",-1.53,-1.83],["c",-0.03,0,-0.57,0.84,-1.23,1.83],["c",-1.14,1.68,-1.23,1.83,-1.35,1.89],["c",-0.06,0.03,-0.18,0.06,-0.24,0.06],["c",-0.3,0,-0.27,0.03,-1.89,-1.95],["l",-1.53,-1.83],["l",-0.48,0.69],["c",-0.51,0.78,-0.54,0.84,-0.69,0.9],["c",-0.42,0.18,-0.87,-0.15,-0.81,-0.6],["c",0.03,-0.12,0.3,-0.51,1.5,-2.37],["c",1.38,-2.07,1.5,-2.22,1.62,-2.28],["z"]],w:15.011,h:7.5},"scripts.mordent":{d:[["M",-0.21,-4.95],["c",0.27,-0.15,0.63,0,0.75,0.27],["c",0.06,0.12,0.06,0.24,0.06,1.44],["l",0,1.29],["l",0.57,-0.84],["c",0.51,-0.75,0.57,-0.84,0.69,-0.9],["c",0.06,-0.03,0.18,-0.06,0.24,-0.06],["c",0.3,0,0.27,-0.03,1.89,1.95],["l",1.53,1.83],["l",0.48,-0.69],["c",0.51,-0.78,0.54,-0.84,0.69,-0.9],["c",0.42,-0.18,0.87,0.15,0.81,0.6],["c",-0.03,0.12,-0.3,0.51,-1.5,2.37],["c",-1.38,2.07,-1.5,2.22,-1.62,2.28],["c",-0.06,0.03,-0.18,0.06,-0.24,0.06],["c",-0.3,0,-0.27,0.03,-1.83,-1.89],["c",-0.81,-0.99,-1.5,-1.8,-1.53,-1.86],["c",-0.06,-0.03,-0.06,-0.03,-0.12,0.03],["c",-0.06,0.06,-0.06,0.15,-0.06,2.28],["c",-0,1.95,-0,2.25,-0.06,2.34],["c",-0.18,0.45,-0.81,0.48,-1.05,0.03],["c",-0.03,-0.06,-0.06,-0.24,-0.06,-1.41],["l",-0,-1.35],["l",-0.57,0.84],["c",-0.54,0.78,-0.6,0.87,-0.72,0.93],["c",-0.06,0.03,-0.18,0.06,-0.24,0.06],["c",-0.3,0,-0.27,0.03,-1.89,-1.95],["l",-1.53,-1.83],["l",-0.48,0.69],["c",-0.51,0.78,-0.54,0.84,-0.69,0.9],["c",-0.42,0.18,-0.87,-0.15,-0.81,-0.6],["c",0.03,-0.12,0.3,-0.51,1.5,-2.37],["c",1.38,-2.07,1.5,-2.22,1.62,-2.28],["c",0.06,-0.03,0.18,-0.06,0.24,-0.06],["c",0.3,0,0.27,-0.03,1.89,1.95],["l",1.53,1.83],["c",0.03,-0,0.06,-0.06,0.09,-0.09],["c",0.06,-0.12,0.06,-0.15,0.06,-2.28],["c",-0,-1.92,-0,-2.22,0.06,-2.31],["c",0.06,-0.15,0.15,-0.24,0.3,-0.3],["z"]],w:15.011,h:10.012},"flags.u8th":{d:[["M",-0.42,3.75],["l",0,-3.75],["l",0.21,0],["l",0.21,0],["l",0,0.18],["c",0,0.3,0.06,0.84,0.12,1.23],["c",0.24,1.53,0.9,3.12,2.13,5.16],["l",0.99,1.59],["c",0.87,1.44,1.38,2.34,1.77,3.09],["c",0.81,1.68,1.2,3.06,1.26,4.53],["c",0.03,1.53,-0.21,3.27,-0.75,5.01],["c",-0.21,0.69,-0.51,1.5,-0.6,1.59],["c",-0.09,0.12,-0.27,0.21,-0.42,0.21],["c",-0.15,0,-0.42,-0.12,-0.51,-0.21],["c",-0.15,-0.18,-0.18,-0.42,-0.09,-0.66],["c",0.15,-0.33,0.45,-1.2,0.57,-1.62],["c",0.42,-1.38,0.6,-2.58,0.6,-3.9],["c",0,-0.66,0,-0.81,-0.06,-1.11],["c",-0.39,-2.07,-1.8,-4.26,-4.59,-7.14],["l",-0.42,-0.45],["l",-0.21,0],["l",-0.21,0],["l",0,-3.75],["z"]],w:6.692,h:22.59},"flags.u16th":{d:[["M",-0.42,7.5],["l",0,-7.5],["l",0.21,0],["l",0.21,0],["l",0,0.39],["c",0.06,1.08,0.39,2.19,0.99,3.39],["c",0.45,0.9,0.87,1.59,1.95,3.12],["c",1.29,1.86,1.77,2.64,2.22,3.57],["c",0.45,0.93,0.72,1.8,0.87,2.64],["c",0.06,0.51,0.06,1.5,0,1.92],["c",-0.12,0.6,-0.3,1.2,-0.54,1.71],["l",-0.09,0.24],["l",0.18,0.45],["c",0.51,1.2,0.72,2.22,0.69,3.42],["c",-0.06,1.53,-0.39,3.03,-0.99,4.53],["c",-0.3,0.75,-0.36,0.81,-0.57,0.9],["c",-0.15,0.09,-0.33,0.06,-0.48,-0],["c",-0.18,-0.09,-0.27,-0.18,-0.33,-0.33],["c",-0.09,-0.18,-0.06,-0.3,0.12,-0.75],["c",0.66,-1.41,1.02,-2.88,1.08,-4.32],["c",0,-0.6,-0.03,-1.05,-0.18,-1.59],["c",-0.3,-1.2,-0.99,-2.4,-2.25,-3.87],["c",-0.42,-0.48,-1.53,-1.62,-2.19,-2.22],["l",-0.45,-0.42],["l",-0.03,1.11],["l",0,1.11],["l",-0.21,-0],["l",-0.21,-0],["l",0,-7.5],["z"],["m",1.65,0.09],["c",-0.3,-0.3,-0.69,-0.72,-0.9,-0.87],["l",-0.33,-0.33],["l",0,0.15],["c",0,0.3,0.06,0.81,0.15,1.26],["c",0.27,1.29,0.87,2.61,2.04,4.29],["c",0.15,0.24,0.6,0.87,0.96,1.38],["l",1.08,1.53],["l",0.42,0.63],["c",0.03,0,0.12,-0.36,0.21,-0.72],["c",0.06,-0.33,0.06,-1.2,0,-1.62],["c",-0.33,-1.71,-1.44,-3.48,-3.63,-5.7],["z"]],w:6.693,h:26.337},"flags.u32nd":{d:[["M",-0.42,11.247],["l",0,-11.25],["l",0.21,0],["l",0.21,0],["l",0,0.36],["c",0.09,1.68,0.69,3.27,2.07,5.46],["l",0.87,1.35],["c",1.02,1.62,1.47,2.37,1.86,3.18],["c",0.48,1.02,0.78,1.92,0.93,2.88],["c",0.06,0.48,0.06,1.5,0,1.89],["c",-0.09,0.42,-0.21,0.87,-0.36,1.26],["l",-0.12,0.3],["l",0.15,0.39],["c",0.69,1.56,0.84,2.88,0.54,4.38],["c",-0.09,0.45,-0.27,1.08,-0.45,1.47],["l",-0.12,0.24],["l",0.18,0.36],["c",0.33,0.72,0.57,1.56,0.69,2.34],["c",0.12,1.02,-0.06,2.52,-0.42,3.84],["c",-0.27,0.93,-0.75,2.13,-0.93,2.31],["c",-0.18,0.15,-0.45,0.18,-0.66,0.09],["c",-0.18,-0.09,-0.27,-0.18,-0.33,-0.33],["c",-0.09,-0.18,-0.06,-0.3,0.06,-0.6],["c",0.21,-0.36,0.42,-0.9,0.57,-1.38],["c",0.51,-1.41,0.69,-3.06,0.48,-4.08],["c",-0.15,-0.81,-0.57,-1.68,-1.2,-2.55],["c",-0.72,-0.99,-1.83,-2.13,-3.3,-3.33],["l",-0.48,-0.42],["l",-0.03,1.53],["l",0,1.56],["l",-0.21,0],["l",-0.21,0],["l",0,-11.25],["z"],["m",1.26,-3.96],["c",-0.27,-0.3,-0.54,-0.6,-0.66,-0.72],["l",-0.18,-0.21],["l",0,0.42],["c",0.06,0.87,0.24,1.74,0.66,2.67],["c",0.36,0.87,0.96,1.86,1.92,3.18],["c",0.21,0.33,0.63,0.87,0.87,1.23],["c",0.27,0.39,0.6,0.84,0.75,1.08],["l",0.27,0.39],["l",0.03,-0.12],["c",0.12,-0.45,0.15,-1.05,0.09,-1.59],["c",-0.27,-1.86,-1.38,-3.78,-3.75,-6.33],["z"],["m",-0.27,6.09],["c",-0.27,-0.21,-0.48,-0.42,-0.51,-0.45],["c",-0.06,-0.03,-0.06,-0.03,-0.06,0.21],["c",0,0.9,0.3,2.04,0.81,3.09],["c",0.48,1.02,0.96,1.77,2.37,3.63],["c",0.6,0.78,1.05,1.44,1.29,1.77],["c",0.06,0.12,0.15,0.21,0.15,0.18],["c",0.03,-0.03,0.18,-0.57,0.24,-0.87],["c",0.06,-0.45,0.06,-1.32,-0.03,-1.74],["c",-0.09,-0.48,-0.24,-0.9,-0.51,-1.44],["c",-0.66,-1.35,-1.83,-2.7,-3.75,-4.38],["z"]],w:6.697,h:32.145},"flags.u64th":{d:[["M",-0.42,15],["l",0,-15],["l",0.21,0],["l",0.21,0],["l",0,0.36],["c",0.06,1.2,0.39,2.37,1.02,3.66],["c",0.39,0.81,0.84,1.56,1.8,3.09],["c",0.81,1.26,1.05,1.68,1.35,2.22],["c",0.87,1.5,1.35,2.79,1.56,4.08],["c",0.06,0.54,0.06,1.56,-0.03,2.04],["c",-0.09,0.48,-0.21,0.99,-0.36,1.35],["l",-0.12,0.27],["l",0.12,0.27],["c",0.09,0.15,0.21,0.45,0.27,0.66],["c",0.69,1.89,0.63,3.66,-0.18,5.46],["l",-0.18,0.39],["l",0.15,0.33],["c",0.3,0.66,0.51,1.44,0.63,2.1],["c",0.06,0.48,0.06,1.35,0,1.71],["c",-0.15,0.57,-0.42,1.2,-0.78,1.68],["l",-0.21,0.27],["l",0.18,0.33],["c",0.57,1.05,0.93,2.13,1.02,3.18],["c",0.06,0.72,0,1.83,-0.21,2.79],["c",-0.18,1.02,-0.63,2.34,-1.02,3.09],["c",-0.15,0.33,-0.48,0.45,-0.78,0.3],["c",-0.18,-0.09,-0.27,-0.18,-0.33,-0.33],["c",-0.09,-0.18,-0.06,-0.3,0.03,-0.54],["c",0.75,-1.5,1.23,-3.45,1.17,-4.89],["c",-0.06,-1.02,-0.42,-2.01,-1.17,-3.15],["c",-0.48,-0.72,-1.02,-1.35,-1.89,-2.22],["c",-0.57,-0.57,-1.56,-1.5,-1.92,-1.77],["l",-0.12,-0.09],["l",0,1.68],["l",0,1.68],["l",-0.21,0],["l",-0.21,0],["l",0,-15],["z"],["m",0.93,-8.07],["c",-0.27,-0.3,-0.48,-0.54,-0.51,-0.54],["c",-0,0,-0,0.69,0.03,1.02],["c",0.15,1.47,0.75,2.94,2.04,4.83],["l",1.08,1.53],["c",0.39,0.57,0.84,1.2,0.99,1.44],["c",0.15,0.24,0.3,0.45,0.3,0.45],["c",-0,0,0.03,-0.09,0.06,-0.21],["c",0.36,-1.59,-0.15,-3.33,-1.47,-5.4],["c",-0.63,-0.93,-1.35,-1.83,-2.52,-3.12],["z"],["m",0.06,6.72],["c",-0.24,-0.21,-0.48,-0.42,-0.51,-0.45],["l",-0.06,-0.06],["l",0,0.33],["c",0,1.2,0.3,2.34,0.93,3.6],["c",0.45,0.9,0.96,1.68,2.25,3.51],["c",0.39,0.54,0.84,1.17,1.02,1.44],["c",0.21,0.33,0.33,0.51,0.33,0.48],["c",0.06,-0.09,0.21,-0.63,0.3,-0.99],["c",0.06,-0.33,0.06,-0.45,0.06,-0.96],["c",-0,-0.6,-0.03,-0.84,-0.18,-1.35],["c",-0.3,-1.08,-1.02,-2.28,-2.13,-3.57],["c",-0.39,-0.45,-1.44,-1.47,-2.01,-1.98],["z"],["m",0,6.72],["c",-0.24,-0.21,-0.48,-0.39,-0.51,-0.42],["l",-0.06,-0.06],["l",0,0.33],["c",0,1.41,0.45,2.82,1.38,4.35],["c",0.42,0.72,0.72,1.14,1.86,2.73],["c",0.36,0.45,0.75,0.99,0.87,1.2],["c",0.15,0.21,0.3,0.36,0.3,0.36],["c",0.06,0,0.3,-0.48,0.39,-0.75],["c",0.09,-0.36,0.12,-0.63,0.12,-1.05],["c",-0.06,-1.05,-0.45,-2.04,-1.2,-3.18],["c",-0.57,-0.87,-1.11,-1.53,-2.07,-2.49],["c",-0.36,-0.33,-0.84,-0.78,-1.08,-1.02],["z"]],w:6.682,h:39.694},"flags.d8th":{d:[["M",5.67,-21.63],["c",0.24,-0.12,0.54,-0.06,0.69,0.15],["c",0.06,0.06,0.21,0.36,0.39,0.66],["c",0.84,1.77,1.26,3.36,1.32,5.1],["c",0.03,1.29,-0.21,2.37,-0.81,3.63],["c",-0.6,1.23,-1.26,2.13,-3.21,4.38],["c",-1.35,1.53,-1.86,2.19,-2.4,2.97],["c",-0.63,0.93,-1.11,1.92,-1.38,2.79],["c",-0.15,0.54,-0.27,1.35,-0.27,1.8],["l",0,0.15],["l",-0.21,-0],["l",-0.21,-0],["l",0,-3.75],["l",0,-3.75],["l",0.21,0],["l",0.21,0],["l",0.48,-0.3],["c",1.83,-1.11,3.12,-2.1,4.17,-3.12],["c",0.78,-0.81,1.32,-1.53,1.71,-2.31],["c",0.45,-0.93,0.6,-1.74,0.51,-2.88],["c",-0.12,-1.56,-0.63,-3.18,-1.47,-4.68],["c",-0.12,-0.21,-0.15,-0.33,-0.06,-0.51],["c",0.06,-0.15,0.15,-0.24,0.33,-0.33],["z"]],w:8.492,h:21.691},"flags.ugrace":{d:[["M",6.03,6.93],["c",0.15,-0.09,0.33,-0.06,0.51,0],["c",0.15,0.09,0.21,0.15,0.3,0.33],["c",0.09,0.18,0.06,0.39,-0.03,0.54],["c",-0.06,0.15,-10.89,8.88,-11.07,8.97],["c",-0.15,0.09,-0.33,0.06,-0.48,0],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["c",-0.09,-0.18,-0.06,-0.39,0.03,-0.54],["c",0.06,-0.15,10.89,-8.88,11.07,-8.97],["z"]],w:12.019,h:9.954},"flags.dgrace":{d:[["M",-6.06,-15.93],["c",0.18,-0.09,0.33,-0.12,0.48,-0.06],["c",0.18,0.09,14.01,8.04,14.1,8.1],["c",0.12,0.12,0.18,0.33,0.18,0.51],["c",-0.03,0.21,-0.15,0.39,-0.36,0.48],["c",-0.18,0.09,-0.33,0.12,-0.48,0.06],["c",-0.18,-0.09,-14.01,-8.04,-14.1,-8.1],["c",-0.12,-0.12,-0.18,-0.33,-0.18,-0.51],["c",0.03,-0.21,0.15,-0.39,0.36,-0.48],["z"]],w:15.12,h:9.212},"flags.d16th":{d:[["M",6.84,-22.53],["c",0.27,-0.12,0.57,-0.06,0.72,0.15],["c",0.15,0.15,0.33,0.87,0.45,1.56],["c",0.06,0.33,0.06,1.35,0,1.65],["c",-0.06,0.33,-0.15,0.78,-0.27,1.11],["c",-0.12,0.33,-0.45,0.96,-0.66,1.32],["l",-0.18,0.27],["l",0.09,0.18],["c",0.48,1.02,0.72,2.25,0.69,3.3],["c",-0.06,1.23,-0.42,2.28,-1.26,3.45],["c",-0.57,0.87,-0.99,1.32,-3,3.39],["c",-1.56,1.56,-2.22,2.4,-2.76,3.45],["c",-0.42,0.84,-0.66,1.8,-0.66,2.55],["l",0,0.15],["l",-0.21,-0],["l",-0.21,-0],["l",0,-7.5],["l",0,-7.5],["l",0.21,-0],["l",0.21,-0],["l",0,1.14],["l",0,1.11],["l",0.27,-0.15],["c",1.11,-0.57,1.77,-0.99,2.52,-1.47],["c",2.37,-1.56,3.69,-3.15,4.05,-4.83],["c",0.03,-0.18,0.03,-0.39,0.03,-0.78],["c",0,-0.6,-0.03,-0.93,-0.24,-1.5],["c",-0.06,-0.18,-0.12,-0.39,-0.15,-0.45],["c",-0.03,-0.24,0.12,-0.48,0.36,-0.6],["z"],["m",-0.63,7.5],["c",-0.06,-0.18,-0.15,-0.36,-0.15,-0.36],["c",-0.03,0,-0.03,0.03,-0.06,0.06],["c",-0.06,0.12,-0.96,1.02,-1.95,1.98],["c",-0.63,0.57,-1.26,1.17,-1.44,1.35],["c",-1.53,1.62,-2.28,2.85,-2.55,4.32],["c",-0.03,0.18,-0.03,0.54,-0.06,0.99],["l",0,0.69],["l",0.18,-0.09],["c",0.93,-0.54,2.1,-1.29,2.82,-1.83],["c",0.69,-0.51,1.02,-0.81,1.53,-1.29],["c",1.86,-1.89,2.37,-3.66,1.68,-5.82],["z"]],w:8.475,h:22.591},"flags.d32nd":{d:[["M",6.794,-29.13],["c",0.27,-0.12,0.57,-0.06,0.72,0.15],["c",0.12,0.12,0.27,0.63,0.36,1.11],["c",0.33,1.59,0.06,3.06,-0.81,4.47],["l",-0.18,0.27],["l",0.09,0.15],["c",0.12,0.24,0.33,0.69,0.45,1.05],["c",0.63,1.83,0.45,3.57,-0.57,5.22],["l",-0.18,0.3],["l",0.15,0.27],["c",0.42,0.87,0.6,1.71,0.57,2.61],["c",-0.06,1.29,-0.48,2.46,-1.35,3.78],["c",-0.54,0.81,-0.93,1.29,-2.46,3],["c",-0.51,0.54,-1.05,1.17,-1.26,1.41],["c",-1.56,1.86,-2.25,3.36,-2.37,5.01],["l",0,0.33],["l",-0.21,-0],["l",-0.21,-0],["l",0,-11.25],["l",0,-11.25],["l",0.21,0],["l",0.21,0],["l",0,1.35],["l",0.03,1.35],["l",0.78,-0.39],["c",1.38,-0.69,2.34,-1.26,3.24,-1.92],["c",1.38,-1.02,2.28,-2.13,2.64,-3.21],["c",0.15,-0.48,0.18,-0.72,0.18,-1.29],["c",0,-0.57,-0.06,-0.9,-0.24,-1.47],["c",-0.06,-0.18,-0.12,-0.39,-0.15,-0.45],["c",-0.03,-0.24,0.12,-0.48,0.36,-0.6],["z"],["m",-0.63,7.2],["c",-0.09,-0.18,-0.12,-0.21,-0.12,-0.15],["c",-0.03,0.09,-1.02,1.08,-2.04,2.04],["c",-1.17,1.08,-1.65,1.56,-2.07,2.04],["c",-0.84,0.96,-1.38,1.86,-1.68,2.76],["c",-0.21,0.57,-0.27,0.99,-0.3,1.65],["l",0,0.54],["l",0.66,-0.33],["c",3.57,-1.86,5.49,-3.69,5.94,-5.7],["c",0.06,-0.39,0.06,-1.2,-0.03,-1.65],["c",-0.06,-0.39,-0.24,-0.9,-0.36,-1.2],["z"],["m",-0.06,7.2],["c",-0.06,-0.15,-0.12,-0.33,-0.15,-0.45],["l",-0.06,-0.18],["l",-0.18,0.21],["l",-1.83,1.83],["c",-0.87,0.9,-1.77,1.8,-1.95,2.01],["c",-1.08,1.29,-1.62,2.31,-1.89,3.51],["c",-0.06,0.3,-0.06,0.51,-0.09,0.93],["l",0,0.57],["l",0.09,-0.06],["c",0.75,-0.45,1.89,-1.26,2.52,-1.74],["c",0.81,-0.66,1.74,-1.53,2.22,-2.16],["c",1.26,-1.53,1.68,-3.06,1.32,-4.47],["z"]],w:8.475,h:29.191},"flags.d64th":{d:[["M",7.08,-32.88],["c",0.3,-0.12,0.66,-0.03,0.78,0.24],["c",0.18,0.33,0.27,2.1,0.15,2.64],["c",-0.09,0.39,-0.21,0.78,-0.39,1.08],["l",-0.15,0.3],["l",0.09,0.27],["c",0.03,0.12,0.09,0.45,0.12,0.69],["c",0.27,1.44,0.18,2.55,-0.3,3.6],["l",-0.12,0.33],["l",0.06,0.42],["c",0.27,1.35,0.33,2.82,0.21,3.63],["c",-0.12,0.6,-0.3,1.23,-0.57,1.8],["l",-0.15,0.27],["l",0.03,0.42],["c",0.06,1.02,0.06,2.7,0.03,3.06],["c",-0.15,1.47,-0.66,2.76,-1.74,4.41],["c",-0.45,0.69,-0.75,1.11,-1.74,2.37],["c",-1.05,1.38,-1.5,1.98,-1.95,2.73],["c",-0.93,1.5,-1.38,2.82,-1.44,4.2],["l",0,0.42],["l",-0.21,-0],["l",-0.21,-0],["l",0,-15],["l",0,-15],["l",0.21,-0],["l",0.21,-0],["l",0,1.86],["l",0,1.89],["c",0,-0,0.21,-0.03,0.45,-0.09],["c",2.22,-0.39,4.08,-1.11,5.19,-2.01],["c",0.63,-0.54,1.02,-1.14,1.2,-1.8],["c",0.06,-0.3,0.06,-1.14,-0.03,-1.65],["c",-0.03,-0.18,-0.06,-0.39,-0.09,-0.48],["c",-0.03,-0.24,0.12,-0.48,0.36,-0.6],["z"],["m",-0.45,6.15],["c",-0.03,-0.18,-0.06,-0.42,-0.06,-0.54],["l",-0.03,-0.18],["l",-0.33,0.3],["c",-0.42,0.36,-0.87,0.72,-1.68,1.29],["c",-1.98,1.38,-2.25,1.59,-2.85,2.16],["c",-0.75,0.69,-1.23,1.44,-1.47,2.19],["c",-0.15,0.45,-0.18,0.63,-0.21,1.35],["l",0,0.66],["l",0.39,-0.18],["c",1.83,-0.9,3.45,-1.95,4.47,-2.91],["c",0.93,-0.9,1.53,-1.83,1.74,-2.82],["c",0.06,-0.33,0.06,-0.87,0.03,-1.32],["z"],["m",-0.27,4.86],["c",-0.03,-0.21,-0.06,-0.36,-0.06,-0.36],["c",0,-0.03,-0.12,0.09,-0.24,0.24],["c",-0.39,0.48,-0.99,1.08,-2.16,2.19],["c",-1.47,1.38,-1.92,1.83,-2.46,2.49],["c",-0.66,0.87,-1.08,1.74,-1.29,2.58],["c",-0.09,0.42,-0.15,0.87,-0.15,1.44],["l",0,0.54],["l",0.48,-0.33],["c",1.5,-1.02,2.58,-1.89,3.51,-2.82],["c",1.47,-1.47,2.25,-2.85,2.4,-4.26],["c",0.03,-0.39,0.03,-1.17,-0.03,-1.71],["z"],["m",-0.66,7.68],["c",0.03,-0.15,0.03,-0.6,0.03,-0.99],["l",0,-0.72],["l",-0.27,0.33],["l",-1.74,1.98],["c",-1.77,1.92,-2.43,2.76,-2.97,3.9],["c",-0.51,1.02,-0.72,1.77,-0.75,2.91],["c",0,0.63,0,0.63,0.06,0.6],["c",0.03,-0.03,0.3,-0.27,0.63,-0.54],["c",0.66,-0.6,1.86,-1.8,2.31,-2.31],["c",1.65,-1.89,2.52,-3.54,2.7,-5.16],["z"]],w:8.485,h:32.932},"clefs.C":{d:[["M",0.06,-14.94],["l",0.09,-0.06],["l",1.92,0],["l",1.92,0],["l",0.09,0.06],["l",0.06,0.09],["l",0,14.85],["l",0,14.82],["l",-0.06,0.09],["l",-0.09,0.06],["l",-1.92,0],["l",-1.92,0],["l",-0.09,-0.06],["l",-0.06,-0.09],["l",0,-14.82],["l",0,-14.85],["z"],["m",5.37,0],["c",0.09,-0.06,0.09,-0.06,0.57,-0.06],["c",0.45,0,0.45,0,0.54,0.06],["l",0.06,0.09],["l",0,7.14],["l",0,7.11],["l",0.09,-0.06],["c",0.18,-0.18,0.72,-0.84,0.96,-1.2],["c",0.3,-0.45,0.66,-1.17,0.84,-1.65],["c",0.36,-0.9,0.57,-1.83,0.6,-2.79],["c",0.03,-0.48,0.03,-0.54,0.09,-0.63],["c",0.12,-0.18,0.36,-0.21,0.54,-0.12],["c",0.18,0.09,0.21,0.15,0.24,0.66],["c",0.06,0.87,0.21,1.56,0.57,2.22],["c",0.51,1.02,1.26,1.68,2.22,1.92],["c",0.21,0.06,0.33,0.06,0.78,0.06],["c",0.45,-0,0.57,-0,0.84,-0.06],["c",0.45,-0.12,0.81,-0.33,1.08,-0.6],["c",0.57,-0.57,0.87,-1.41,0.99,-2.88],["c",0.06,-0.54,0.06,-3,0,-3.57],["c",-0.21,-2.58,-0.84,-3.87,-2.16,-4.5],["c",-0.48,-0.21,-1.17,-0.36,-1.77,-0.36],["c",-0.69,0,-1.29,0.27,-1.5,0.72],["c",-0.06,0.15,-0.06,0.21,-0.06,0.42],["c",0,0.24,0,0.3,0.06,0.45],["c",0.12,0.24,0.24,0.39,0.63,0.66],["c",0.42,0.3,0.57,0.48,0.69,0.72],["c",0.06,0.15,0.06,0.21,0.06,0.48],["c",0,0.39,-0.03,0.63,-0.21,0.96],["c",-0.3,0.6,-0.87,1.08,-1.5,1.26],["c",-0.27,0.06,-0.87,0.06,-1.14,0],["c",-0.78,-0.24,-1.44,-0.87,-1.65,-1.68],["c",-0.12,-0.42,-0.09,-1.17,0.09,-1.71],["c",0.51,-1.65,1.98,-2.82,3.81,-3.09],["c",0.84,-0.09,2.46,0.03,3.51,0.27],["c",2.22,0.57,3.69,1.8,4.44,3.75],["c",0.36,0.93,0.57,2.13,0.57,3.36],["c",-0,1.44,-0.48,2.73,-1.38,3.81],["c",-1.26,1.5,-3.27,2.43,-5.28,2.43],["c",-0.48,-0,-0.51,-0,-0.75,-0.09],["c",-0.15,-0.03,-0.48,-0.21,-0.78,-0.36],["c",-0.69,-0.36,-0.87,-0.42,-1.26,-0.42],["c",-0.27,-0,-0.3,-0,-0.51,0.09],["c",-0.57,0.3,-0.81,0.9,-0.81,2.1],["c",-0,1.23,0.24,1.83,0.81,2.13],["c",0.21,0.09,0.24,0.09,0.51,0.09],["c",0.39,-0,0.57,-0.06,1.26,-0.42],["c",0.3,-0.15,0.63,-0.33,0.78,-0.36],["c",0.24,-0.09,0.27,-0.09,0.75,-0.09],["c",2.01,-0,4.02,0.93,5.28,2.4],["c",0.9,1.11,1.38,2.4,1.38,3.84],["c",-0,1.5,-0.3,2.88,-0.84,3.96],["c",-0.78,1.59,-2.19,2.64,-4.17,3.15],["c",-1.05,0.24,-2.67,0.36,-3.51,0.27],["c",-1.83,-0.27,-3.3,-1.44,-3.81,-3.09],["c",-0.18,-0.54,-0.21,-1.29,-0.09,-1.74],["c",0.15,-0.6,0.63,-1.2,1.23,-1.47],["c",0.36,-0.18,0.57,-0.21,0.99,-0.21],["c",0.42,0,0.63,0.03,1.02,0.21],["c",0.42,0.21,0.84,0.63,1.05,1.05],["c",0.18,0.36,0.21,0.6,0.21,0.96],["c",-0,0.3,-0,0.36,-0.06,0.51],["c",-0.12,0.24,-0.27,0.42,-0.69,0.72],["c",-0.57,0.42,-0.69,0.63,-0.69,1.08],["c",-0,0.24,-0,0.3,0.06,0.45],["c",0.12,0.21,0.3,0.39,0.57,0.54],["c",0.42,0.18,0.87,0.21,1.53,0.15],["c",1.08,-0.15,1.8,-0.57,2.34,-1.32],["c",0.54,-0.75,0.84,-1.83,0.99,-3.51],["c",0.06,-0.57,0.06,-3.03,-0,-3.57],["c",-0.12,-1.47,-0.42,-2.31,-0.99,-2.88],["c",-0.27,-0.27,-0.63,-0.48,-1.08,-0.6],["c",-0.27,-0.06,-0.39,-0.06,-0.84,-0.06],["c",-0.45,0,-0.57,0,-0.78,0.06],["c",-1.14,0.27,-2.01,1.17,-2.46,2.49],["c",-0.21,0.57,-0.3,0.99,-0.33,1.65],["c",-0.03,0.51,-0.06,0.57,-0.24,0.66],["c",-0.12,0.06,-0.27,0.06,-0.39,0],["c",-0.21,-0.09,-0.21,-0.15,-0.24,-0.75],["c",-0.09,-1.92,-0.78,-3.72,-2.01,-5.19],["c",-0.18,-0.21,-0.36,-0.42,-0.39,-0.45],["l",-0.09,-0.06],["l",-0,7.11],["l",-0,7.14],["l",-0.06,0.09],["c",-0.09,0.06,-0.09,0.06,-0.54,0.06],["c",-0.48,0,-0.48,0,-0.57,-0.06],["l",-0.06,-0.09],["l",-0,-14.82],["l",-0,-14.85],["z"]],w:20.31,h:29.97},"clefs.F":{d:[["M",6.3,-7.8],["c",0.36,-0.03,1.65,0,2.13,0.03],["c",3.6,0.42,6.03,2.1,6.93,4.86],["c",0.27,0.84,0.36,1.5,0.36,2.58],["c",0,0.9,-0.03,1.35,-0.18,2.16],["c",-0.78,3.78,-3.54,7.08,-8.37,9.96],["c",-1.74,1.05,-3.87,2.13,-6.18,3.12],["c",-0.39,0.18,-0.75,0.33,-0.81,0.36],["c",-0.06,0.03,-0.15,0.06,-0.18,0.06],["c",-0.15,0,-0.33,-0.18,-0.33,-0.33],["c",0,-0.15,0.06,-0.21,0.51,-0.48],["c",3,-1.77,5.13,-3.21,6.84,-4.74],["c",0.51,-0.45,1.59,-1.5,1.95,-1.95],["c",1.89,-2.19,2.88,-4.32,3.15,-6.78],["c",0.06,-0.42,0.06,-1.77,0,-2.19],["c",-0.24,-2.01,-0.93,-3.63,-2.04,-4.71],["c",-0.63,-0.63,-1.29,-1.02,-2.07,-1.2],["c",-1.62,-0.39,-3.36,0.15,-4.56,1.44],["c",-0.54,0.6,-1.05,1.47,-1.32,2.22],["l",-0.09,0.21],["l",0.24,-0.12],["c",0.39,-0.21,0.63,-0.24,1.11,-0.24],["c",0.3,0,0.45,0,0.66,0.06],["c",1.92,0.48,2.85,2.55,1.95,4.38],["c",-0.45,0.99,-1.41,1.62,-2.46,1.71],["c",-1.47,0.09,-2.91,-0.87,-3.39,-2.25],["c",-0.18,-0.57,-0.21,-1.32,-0.03,-2.28],["c",0.39,-2.25,1.83,-4.2,3.81,-5.19],["c",0.69,-0.36,1.59,-0.6,2.37,-0.69],["z"],["m",11.58,2.52],["c",0.84,-0.21,1.71,0.3,1.89,1.14],["c",0.3,1.17,-0.72,2.19,-1.89,1.89],["c",-0.99,-0.21,-1.5,-1.32,-1.02,-2.25],["c",0.18,-0.39,0.6,-0.69,1.02,-0.78],["z"],["m",0,7.5],["c",0.84,-0.21,1.71,0.3,1.89,1.14],["c",0.21,0.87,-0.3,1.71,-1.14,1.89],["c",-0.87,0.21,-1.71,-0.3,-1.89,-1.14],["c",-0.21,-0.84,0.3,-1.71,1.14,-1.89],["z"]],w:20.153,h:23.142},"clefs.G":{d:[["M",9.69,-37.41],["c",0.09,-0.09,0.24,-0.06,0.36,0],["c",0.12,0.09,0.57,0.6,0.96,1.11],["c",1.77,2.34,3.21,5.85,3.57,8.73],["c",0.21,1.56,0.03,3.27,-0.45,4.86],["c",-0.69,2.31,-1.92,4.47,-4.23,7.44],["c",-0.3,0.39,-0.57,0.72,-0.6,0.75],["c",-0.03,0.06,0,0.15,0.18,0.78],["c",0.54,1.68,1.38,4.44,1.68,5.49],["l",0.09,0.42],["l",0.39,-0],["c",1.47,0.09,2.76,0.51,3.96,1.29],["c",1.83,1.23,3.06,3.21,3.39,5.52],["c",0.09,0.45,0.12,1.29,0.06,1.74],["c",-0.09,1.02,-0.33,1.83,-0.75,2.73],["c",-0.84,1.71,-2.28,3.06,-4.02,3.72],["l",-0.33,0.12],["l",0.03,1.26],["c",0,1.74,-0.06,3.63,-0.21,4.62],["c",-0.45,3.06,-2.19,5.49,-4.47,6.21],["c",-0.57,0.18,-0.9,0.21,-1.59,0.21],["c",-0.69,-0,-1.02,-0.03,-1.65,-0.21],["c",-1.14,-0.27,-2.13,-0.84,-2.94,-1.65],["c",-0.99,-0.99,-1.56,-2.16,-1.71,-3.54],["c",-0.09,-0.81,0.06,-1.53,0.45,-2.13],["c",0.63,-0.99,1.83,-1.56,3,-1.53],["c",1.5,0.09,2.64,1.32,2.73,2.94],["c",0.06,1.47,-0.93,2.7,-2.37,2.97],["c",-0.45,0.06,-0.84,0.03,-1.29,-0.09],["l",-0.21,-0.09],["l",0.09,0.12],["c",0.39,0.54,0.78,0.93,1.32,1.26],["c",1.35,0.87,3.06,1.02,4.35,0.36],["c",1.44,-0.72,2.52,-2.28,2.97,-4.35],["c",0.15,-0.66,0.24,-1.5,0.3,-3.03],["c",0.03,-0.84,0.03,-2.94,-0,-3],["c",-0.03,-0,-0.18,-0,-0.36,0.03],["c",-0.66,0.12,-0.99,0.12,-1.83,0.12],["c",-1.05,-0,-1.71,-0.06,-2.61,-0.3],["c",-4.02,-0.99,-7.11,-4.35,-7.8,-8.46],["c",-0.12,-0.66,-0.12,-0.99,-0.12,-1.83],["c",-0,-0.84,-0,-1.14,0.15,-1.92],["c",0.36,-2.28,1.41,-4.62,3.3,-7.29],["l",2.79,-3.6],["c",0.54,-0.66,0.96,-1.2,0.96,-1.23],["c",-0,-0.03,-0.09,-0.33,-0.18,-0.69],["c",-0.96,-3.21,-1.41,-5.28,-1.59,-7.68],["c",-0.12,-1.38,-0.15,-3.09,-0.06,-3.96],["c",0.33,-2.67,1.38,-5.07,3.12,-7.08],["c",0.36,-0.42,0.99,-1.05,1.17,-1.14],["z"],["m",2.01,4.71],["c",-0.15,-0.3,-0.3,-0.54,-0.3,-0.54],["c",-0.03,0,-0.18,0.09,-0.3,0.21],["c",-2.4,1.74,-3.87,4.2,-4.26,7.11],["c",-0.06,0.54,-0.06,1.41,-0.03,1.89],["c",0.09,1.29,0.48,3.12,1.08,5.22],["c",0.15,0.42,0.24,0.78,0.24,0.81],["c",0,0.03,0.84,-1.11,1.23,-1.68],["c",1.89,-2.73,2.88,-5.07,3.15,-7.53],["c",0.09,-0.57,0.12,-1.74,0.06,-2.37],["c",-0.09,-1.23,-0.27,-1.92,-0.87,-3.12],["z"],["m",-2.94,20.7],["c",-0.21,-0.72,-0.39,-1.32,-0.42,-1.32],["c",0,0,-1.2,1.47,-1.86,2.37],["c",-2.79,3.63,-4.02,6.3,-4.35,9.3],["c",-0.03,0.21,-0.03,0.69,-0.03,1.08],["c",0,0.69,0,0.75,0.06,1.11],["c",0.12,0.54,0.27,0.99,0.51,1.47],["c",0.69,1.38,1.83,2.55,3.42,3.42],["c",0.96,0.54,2.07,0.9,3.21,1.08],["c",0.78,0.12,2.04,0.12,2.94,-0.03],["c",0.51,-0.06,0.45,-0.03,0.42,-0.3],["c",-0.24,-3.33,-0.72,-6.33,-1.62,-10.08],["c",-0.09,-0.39,-0.18,-0.75,-0.18,-0.78],["c",-0.03,-0.03,-0.42,-0,-0.81,0.09],["c",-0.9,0.18,-1.65,0.57,-2.22,1.14],["c",-0.72,0.72,-1.08,1.65,-1.05,2.64],["c",0.06,0.96,0.48,1.83,1.23,2.58],["c",0.36,0.36,0.72,0.63,1.17,0.9],["c",0.33,0.18,0.36,0.21,0.42,0.33],["c",0.18,0.42,-0.18,0.9,-0.6,0.87],["c",-0.18,-0.03,-0.84,-0.36,-1.26,-0.63],["c",-0.78,-0.51,-1.38,-1.11,-1.86,-1.83],["c",-1.77,-2.7,-0.99,-6.42,1.71,-8.19],["c",0.3,-0.21,0.81,-0.48,1.17,-0.63],["c",0.3,-0.09,1.02,-0.3,1.14,-0.3],["c",0.06,-0,0.09,-0,0.09,-0.03],["c",0.03,-0.03,-0.51,-1.92,-1.23,-4.26],["z"],["m",3.78,7.41],["c",-0.18,-0.03,-0.36,-0.06,-0.39,-0.06],["c",-0.03,0,0,0.21,0.18,1.02],["c",0.75,3.18,1.26,6.3,1.5,9.09],["c",0.06,0.72,0,0.69,0.51,0.42],["c",0.78,-0.36,1.44,-0.96,1.98,-1.77],["c",1.08,-1.62,1.2,-3.69,0.3,-5.55],["c",-0.81,-1.62,-2.31,-2.79,-4.08,-3.15],["z"]],w:19.051,h:57.057},"clefs.perc":{d:[["M",5.07,-7.44],["l",0.09,-0.06],["l",1.53,0],["l",1.53,0],["l",0.09,0.06],["l",0.06,0.09],["l",0,7.35],["l",0,7.32],["l",-0.06,0.09],["l",-0.09,0.06],["l",-1.53,-0],["l",-1.53,-0],["l",-0.09,-0.06],["l",-0.06,-0.09],["l",0,-7.32],["l",0,-7.35],["z"],["m",6.63,0],["l",0.09,-0.06],["l",1.53,0],["l",1.53,0],["l",0.09,0.06],["l",0.06,0.09],["l",0,7.35],["l",0,7.32],["l",-0.06,0.09],["l",-0.09,0.06],["l",-1.53,-0],["l",-1.53,-0],["l",-0.09,-0.06],["l",-0.06,-0.09],["l",0,-7.32],["l",0,-7.35],["z"]],w:9.99,h:14.97},"timesig.common":{d:[["M",6.66,-7.826],["c",0.72,-0.06,1.41,-0.03,1.98,0.09],["c",1.2,0.27,2.34,0.96,3.09,1.92],["c",0.63,0.81,1.08,1.86,1.14,2.73],["c",0.06,1.02,-0.51,1.92,-1.44,2.22],["c",-0.24,0.09,-0.3,0.09,-0.63,0.09],["c",-0.33,-0,-0.42,-0,-0.63,-0.06],["c",-0.66,-0.24,-1.14,-0.63,-1.41,-1.2],["c",-0.15,-0.3,-0.21,-0.51,-0.24,-0.9],["c",-0.06,-1.08,0.57,-2.04,1.56,-2.37],["c",0.18,-0.06,0.27,-0.06,0.63,-0.06],["l",0.45,0],["c",0.06,0.03,0.09,0.03,0.09,0],["c",0,0,-0.09,-0.12,-0.24,-0.27],["c",-1.02,-1.11,-2.55,-1.68,-4.08,-1.5],["c",-1.29,0.15,-2.04,0.69,-2.4,1.74],["c",-0.36,0.93,-0.42,1.89,-0.42,5.37],["c",0,2.97,0.06,3.96,0.24,4.77],["c",0.24,1.08,0.63,1.68,1.41,2.07],["c",0.81,0.39,2.16,0.45,3.18,0.09],["c",1.29,-0.45,2.37,-1.53,3.03,-2.97],["c",0.15,-0.33,0.33,-0.87,0.39,-1.17],["c",0.09,-0.24,0.15,-0.36,0.3,-0.39],["c",0.21,-0.03,0.42,0.15,0.39,0.36],["c",-0.06,0.39,-0.42,1.38,-0.69,1.89],["c",-0.96,1.8,-2.49,2.94,-4.23,3.18],["c",-0.99,0.12,-2.58,-0.06,-3.63,-0.45],["c",-0.96,-0.36,-1.71,-0.84,-2.4,-1.5],["c",-1.11,-1.11,-1.8,-2.61,-2.04,-4.56],["c",-0.06,-0.6,-0.06,-2.01,0,-2.61],["c",0.24,-1.95,0.9,-3.45,2.01,-4.56],["c",0.69,-0.66,1.44,-1.11,2.37,-1.47],["c",0.63,-0.24,1.47,-0.42,2.22,-0.48],["z"]],w:13.038,h:15.697},"timesig.cut":{d:[["M",6.24,-10.44],["c",0.09,-0.06,0.09,-0.06,0.48,-0.06],["c",0.36,0,0.36,0,0.45,0.06],["l",0.06,0.09],["l",0,1.23],["l",0,1.26],["l",0.27,0],["c",1.26,0,2.49,0.45,3.48,1.29],["c",1.05,0.87,1.8,2.28,1.89,3.48],["c",0.06,1.02,-0.51,1.92,-1.44,2.22],["c",-0.24,0.09,-0.3,0.09,-0.63,0.09],["c",-0.33,-0,-0.42,-0,-0.63,-0.06],["c",-0.66,-0.24,-1.14,-0.63,-1.41,-1.2],["c",-0.15,-0.3,-0.21,-0.51,-0.24,-0.9],["c",-0.06,-1.08,0.57,-2.04,1.56,-2.37],["c",0.18,-0.06,0.27,-0.06,0.63,-0.06],["l",0.45,-0],["c",0.06,0.03,0.09,0.03,0.09,-0],["c",0,-0.03,-0.45,-0.51,-0.66,-0.69],["c",-0.87,-0.69,-1.83,-1.05,-2.94,-1.11],["l",-0.42,0],["l",0,7.17],["l",0,7.14],["l",0.42,0],["c",0.69,-0.03,1.23,-0.18,1.86,-0.51],["c",1.05,-0.51,1.89,-1.47,2.46,-2.7],["c",0.15,-0.33,0.33,-0.87,0.39,-1.17],["c",0.09,-0.24,0.15,-0.36,0.3,-0.39],["c",0.21,-0.03,0.42,0.15,0.39,0.36],["c",-0.03,0.24,-0.21,0.78,-0.39,1.2],["c",-0.96,2.37,-2.94,3.9,-5.13,3.9],["l",-0.3,0],["l",0,1.26],["l",0,1.23],["l",-0.06,0.09],["c",-0.09,0.06,-0.09,0.06,-0.45,0.06],["c",-0.39,0,-0.39,0,-0.48,-0.06],["l",-0.06,-0.09],["l",0,-1.29],["l",0,-1.29],["l",-0.21,-0.03],["c",-1.23,-0.21,-2.31,-0.63,-3.21,-1.29],["c",-0.15,-0.09,-0.45,-0.36,-0.66,-0.57],["c",-1.11,-1.11,-1.8,-2.61,-2.04,-4.56],["c",-0.06,-0.6,-0.06,-2.01,0,-2.61],["c",0.24,-1.95,0.93,-3.45,2.04,-4.59],["c",0.42,-0.39,0.78,-0.66,1.26,-0.93],["c",0.75,-0.45,1.65,-0.75,2.61,-0.9],["l",0.21,-0.03],["l",0,-1.29],["l",0,-1.29],["z"],["m",-0.06,10.44],["c",0,-5.58,0,-6.99,-0.03,-6.99],["c",-0.15,0,-0.63,0.27,-0.87,0.45],["c",-0.45,0.36,-0.75,0.93,-0.93,1.77],["c",-0.18,0.81,-0.24,1.8,-0.24,4.74],["c",0,2.97,0.06,3.96,0.24,4.77],["c",0.24,1.08,0.66,1.68,1.41,2.07],["c",0.12,0.06,0.3,0.12,0.33,0.15],["l",0.09,0],["l",0,-6.96],["z"]],w:13.038,h:20.97},"0":{d:[["M",4.83,-14.97],["c",0.33,-0.03,1.11,0,1.47,0.06],["c",1.68,0.36,2.97,1.59,3.78,3.6],["c",1.2,2.97,0.81,6.96,-0.9,9.27],["c",-0.78,1.08,-1.71,1.71,-2.91,1.95],["c",-0.45,0.09,-1.32,0.09,-1.77,0],["c",-0.81,-0.18,-1.47,-0.51,-2.07,-1.02],["c",-2.34,-2.07,-3.15,-6.72,-1.74,-10.2],["c",0.87,-2.16,2.28,-3.42,4.14,-3.66],["z"],["m",1.11,0.87],["c",-0.21,-0.06,-0.69,-0.09,-0.87,-0.06],["c",-0.54,0.12,-0.87,0.42,-1.17,0.99],["c",-0.36,0.66,-0.51,1.56,-0.6,3],["c",-0.03,0.75,-0.03,4.59,-0,5.31],["c",0.09,1.5,0.27,2.4,0.6,3.06],["c",0.24,0.48,0.57,0.78,0.96,0.9],["c",0.27,0.09,0.78,0.09,1.05,-0],["c",0.39,-0.12,0.72,-0.42,0.96,-0.9],["c",0.33,-0.66,0.51,-1.56,0.6,-3.06],["c",0.03,-0.72,0.03,-4.56,-0,-5.31],["c",-0.09,-1.47,-0.27,-2.37,-0.6,-3.03],["c",-0.24,-0.48,-0.54,-0.78,-0.93,-0.9],["z"]],w:10.78,h:14.959},"1":{d:[["M",3.3,-15.06],["c",0.06,-0.06,0.21,-0.03,0.66,0.15],["c",0.81,0.39,1.08,0.39,1.83,0.03],["c",0.21,-0.09,0.39,-0.15,0.42,-0.15],["c",0.12,0,0.21,0.09,0.27,0.21],["c",0.06,0.12,0.06,0.33,0.06,5.94],["c",0,3.93,0,5.85,0.03,6.03],["c",0.06,0.36,0.15,0.69,0.27,0.96],["c",0.36,0.75,0.93,1.17,1.68,1.26],["c",0.3,0.03,0.39,0.09,0.39,0.3],["c",0,0.15,-0.03,0.18,-0.09,0.24],["c",-0.06,0.06,-0.09,0.06,-0.48,0.06],["c",-0.42,-0,-0.69,-0.03,-2.1,-0.24],["c",-0.9,-0.15,-1.77,-0.15,-2.67,-0],["c",-1.41,0.21,-1.68,0.24,-2.1,0.24],["c",-0.39,-0,-0.42,-0,-0.48,-0.06],["c",-0.06,-0.06,-0.06,-0.09,-0.06,-0.24],["c",0,-0.21,0.06,-0.27,0.36,-0.3],["c",0.75,-0.09,1.32,-0.51,1.68,-1.26],["c",0.12,-0.27,0.21,-0.6,0.27,-0.96],["c",0.03,-0.18,0.03,-1.59,0.03,-4.29],["c",0,-3.87,0,-4.05,-0.06,-4.14],["c",-0.09,-0.15,-0.18,-0.24,-0.39,-0.24],["c",-0.12,-0,-0.15,0.03,-0.21,0.06],["c",-0.03,0.06,-0.45,0.99,-0.96,2.13],["c",-0.48,1.14,-0.9,2.1,-0.93,2.16],["c",-0.06,0.15,-0.21,0.24,-0.33,0.24],["c",-0.24,0,-0.42,-0.18,-0.42,-0.39],["c",0,-0.06,3.27,-7.62,3.33,-7.74],["z"]],w:8.94,h:15.058},"2":{d:[["M",4.23,-14.97],["c",0.57,-0.06,1.68,0,2.34,0.18],["c",0.69,0.18,1.5,0.54,2.01,0.9],["c",1.35,0.96,1.95,2.25,1.77,3.81],["c",-0.15,1.35,-0.66,2.34,-1.68,3.15],["c",-0.6,0.48,-1.44,0.93,-3.12,1.65],["c",-1.32,0.57,-1.8,0.81,-2.37,1.14],["c",-0.57,0.33,-0.57,0.33,-0.24,0.27],["c",0.39,-0.09,1.26,-0.09,1.68,0],["c",0.72,0.15,1.41,0.45,2.1,0.9],["c",0.99,0.63,1.86,0.87,2.55,0.75],["c",0.24,-0.06,0.42,-0.15,0.57,-0.3],["c",0.12,-0.09,0.3,-0.42,0.3,-0.51],["c",0,-0.09,0.12,-0.21,0.24,-0.24],["c",0.18,-0.03,0.39,0.12,0.39,0.3],["c",0,0.12,-0.15,0.57,-0.3,0.87],["c",-0.54,1.02,-1.56,1.74,-2.79,2.01],["c",-0.42,0.09,-1.23,0.09,-1.62,0.03],["c",-0.81,-0.18,-1.32,-0.45,-2.01,-1.11],["c",-0.45,-0.45,-0.63,-0.57,-0.96,-0.69],["c",-0.84,-0.27,-1.89,0.12,-2.25,0.9],["c",-0.12,0.21,-0.21,0.54,-0.21,0.72],["c",0,0.12,-0.12,0.21,-0.27,0.24],["c",-0.15,0,-0.27,-0.03,-0.33,-0.15],["c",-0.09,-0.21,0.09,-1.08,0.33,-1.71],["c",0.24,-0.66,0.66,-1.26,1.29,-1.89],["c",0.45,-0.45,0.9,-0.81,1.92,-1.56],["c",1.29,-0.93,1.89,-1.44,2.34,-1.98],["c",0.87,-1.05,1.26,-2.19,1.2,-3.63],["c",-0.06,-1.29,-0.39,-2.31,-0.96,-2.91],["c",-0.36,-0.33,-0.72,-0.51,-1.17,-0.54],["c",-0.84,-0.03,-1.53,0.42,-1.59,1.05],["c",-0.03,0.33,0.12,0.6,0.57,1.14],["c",0.45,0.54,0.54,0.87,0.42,1.41],["c",-0.15,0.63,-0.54,1.11,-1.08,1.38],["c",-0.63,0.33,-1.2,0.33,-1.83,0],["c",-0.24,-0.12,-0.33,-0.18,-0.54,-0.39],["c",-0.18,-0.18,-0.27,-0.3,-0.36,-0.51],["c",-0.24,-0.45,-0.27,-0.84,-0.21,-1.38],["c",0.12,-0.75,0.45,-1.41,1.02,-1.98],["c",0.72,-0.72,1.74,-1.17,2.85,-1.32],["z"]],w:10.764,h:14.993},"3":{d:[["M",3.78,-14.97],["c",0.3,-0.03,1.41,0,1.83,0.06],["c",2.22,0.3,3.51,1.32,3.72,2.91],["c",0.03,0.33,0.03,1.26,-0.03,1.65],["c",-0.12,0.84,-0.48,1.47,-1.05,1.77],["c",-0.27,0.15,-0.36,0.24,-0.45,0.39],["c",-0.09,0.21,-0.09,0.36,0,0.57],["c",0.09,0.15,0.18,0.24,0.51,0.39],["c",0.75,0.42,1.23,1.14,1.41,2.13],["c",0.06,0.42,0.06,1.35,0,1.71],["c",-0.18,0.81,-0.48,1.38,-1.02,1.95],["c",-0.75,0.72,-1.8,1.2,-3.18,1.38],["c",-0.42,0.06,-1.56,0.06,-1.95,0],["c",-1.89,-0.33,-3.18,-1.29,-3.51,-2.64],["c",-0.03,-0.12,-0.03,-0.33,-0.03,-0.6],["c",0,-0.36,0,-0.42,0.06,-0.63],["c",0.12,-0.3,0.27,-0.51,0.51,-0.75],["c",0.24,-0.24,0.45,-0.39,0.75,-0.51],["c",0.21,-0.06,0.27,-0.06,0.6,-0.06],["c",0.33,0,0.39,0,0.6,0.06],["c",0.3,0.12,0.51,0.27,0.75,0.51],["c",0.36,0.33,0.57,0.75,0.6,1.2],["c",0,0.21,0,0.27,-0.06,0.42],["c",-0.09,0.18,-0.12,0.24,-0.54,0.54],["c",-0.51,0.36,-0.63,0.54,-0.6,0.87],["c",0.06,0.54,0.54,0.9,1.38,0.99],["c",0.36,0.06,0.72,0.03,0.96,-0.06],["c",0.81,-0.27,1.29,-1.23,1.44,-2.79],["c",0.03,-0.45,0.03,-1.95,-0.03,-2.37],["c",-0.09,-0.75,-0.33,-1.23,-0.75,-1.44],["c",-0.33,-0.18,-0.45,-0.18,-1.98,-0.18],["c",-1.35,0,-1.41,0,-1.5,-0.06],["c",-0.18,-0.12,-0.24,-0.39,-0.12,-0.6],["c",0.12,-0.15,0.15,-0.15,1.68,-0.15],["c",1.5,0,1.62,0,1.89,-0.15],["c",0.18,-0.09,0.42,-0.36,0.54,-0.57],["c",0.18,-0.42,0.27,-0.9,0.3,-1.95],["c",0.03,-1.2,-0.06,-1.8,-0.36,-2.37],["c",-0.24,-0.48,-0.63,-0.81,-1.14,-0.96],["c",-0.3,-0.06,-1.08,-0.06,-1.38,0.03],["c",-0.6,0.15,-0.9,0.42,-0.96,0.84],["c",-0.03,0.3,0.06,0.45,0.63,0.84],["c",0.33,0.24,0.42,0.39,0.45,0.63],["c",0.03,0.72,-0.57,1.5,-1.32,1.65],["c",-1.05,0.27,-2.1,-0.57,-2.1,-1.65],["c",0,-0.45,0.15,-0.96,0.39,-1.38],["c",0.12,-0.21,0.54,-0.63,0.81,-0.81],["c",0.57,-0.42,1.38,-0.69,2.25,-0.81],["z"]],w:9.735,h:14.967},"4":{d:[["M",8.64,-14.94],["c",0.27,-0.09,0.42,-0.12,0.54,-0.03],["c",0.09,0.06,0.15,0.21,0.15,0.3],["c",-0.03,0.06,-1.92,2.31,-4.23,5.04],["c",-2.31,2.73,-4.23,4.98,-4.26,5.01],["c",-0.03,0.06,0.12,0.06,2.55,0.06],["l",2.61,0],["l",0,-2.37],["c",0,-2.19,0.03,-2.37,0.06,-2.46],["c",0.03,-0.06,0.21,-0.18,0.57,-0.42],["c",1.08,-0.72,1.38,-1.08,1.86,-2.16],["c",0.12,-0.3,0.24,-0.54,0.27,-0.57],["c",0.12,-0.12,0.39,-0.06,0.45,0.12],["c",0.06,0.09,0.06,0.57,0.06,3.96],["l",0,3.9],["l",1.08,0],["c",1.05,0,1.11,0,1.2,0.06],["c",0.24,0.15,0.24,0.54,0,0.69],["c",-0.09,0.06,-0.15,0.06,-1.2,0.06],["l",-1.08,0],["l",0,0.33],["c",0,0.57,0.09,1.11,0.3,1.53],["c",0.36,0.75,0.93,1.17,1.68,1.26],["c",0.3,0.03,0.39,0.09,0.39,0.3],["c",0,0.15,-0.03,0.18,-0.09,0.24],["c",-0.06,0.06,-0.09,0.06,-0.48,0.06],["c",-0.42,0,-0.69,-0.03,-2.1,-0.24],["c",-0.9,-0.15,-1.77,-0.15,-2.67,0],["c",-1.41,0.21,-1.68,0.24,-2.1,0.24],["c",-0.39,0,-0.42,0,-0.48,-0.06],["c",-0.06,-0.06,-0.06,-0.09,-0.06,-0.24],["c",0,-0.21,0.06,-0.27,0.36,-0.3],["c",0.75,-0.09,1.32,-0.51,1.68,-1.26],["c",0.21,-0.42,0.3,-0.96,0.3,-1.53],["l",0,-0.33],["l",-2.7,0],["c",-2.91,0,-2.85,0,-3.09,-0.15],["c",-0.18,-0.12,-0.3,-0.39,-0.27,-0.54],["c",0.03,-0.06,0.18,-0.24,0.33,-0.45],["c",0.75,-0.9,1.59,-2.07,2.13,-3.03],["c",0.33,-0.54,0.84,-1.62,1.05,-2.16],["c",0.57,-1.41,0.84,-2.64,0.9,-4.05],["c",0.03,-0.63,0.06,-0.72,0.24,-0.81],["l",0.12,-0.06],["l",0.45,0.12],["c",0.66,0.18,1.02,0.24,1.47,0.27],["c",0.6,0.03,1.23,-0.09,2.01,-0.33],["z"]],w:11.795,h:14.994},"5":{d:[["M",1.02,-14.94],["c",0.12,-0.09,0.03,-0.09,1.08,0.06],["c",2.49,0.36,4.35,0.36,6.96,-0.06],["c",0.57,-0.09,0.66,-0.06,0.81,0.06],["c",0.15,0.18,0.12,0.24,-0.15,0.51],["c",-1.29,1.26,-3.24,2.04,-5.58,2.31],["c",-0.6,0.09,-1.2,0.12,-1.71,0.12],["c",-0.39,0,-0.45,0,-0.57,0.06],["c",-0.09,0.06,-0.15,0.12,-0.21,0.21],["l",-0.06,0.12],["l",0,1.65],["l",0,1.65],["l",0.21,-0.21],["c",0.66,-0.57,1.41,-0.96,2.19,-1.14],["c",0.33,-0.06,1.41,-0.06,1.95,0],["c",2.61,0.36,4.02,1.74,4.26,4.14],["c",0.03,0.45,0.03,1.08,-0.03,1.44],["c",-0.18,1.02,-0.78,2.01,-1.59,2.7],["c",-0.72,0.57,-1.62,1.02,-2.49,1.2],["c",-1.38,0.27,-3.03,0.06,-4.2,-0.54],["c",-1.08,-0.54,-1.71,-1.32,-1.86,-2.28],["c",-0.09,-0.69,0.09,-1.29,0.57,-1.74],["c",0.24,-0.24,0.45,-0.39,0.75,-0.51],["c",0.21,-0.06,0.27,-0.06,0.6,-0.06],["c",0.33,0,0.39,0,0.6,0.06],["c",0.3,0.12,0.51,0.27,0.75,0.51],["c",0.36,0.33,0.57,0.75,0.6,1.2],["c",0,0.21,0,0.27,-0.06,0.42],["c",-0.09,0.18,-0.12,0.24,-0.54,0.54],["c",-0.18,0.12,-0.36,0.3,-0.42,0.33],["c",-0.36,0.42,-0.18,0.99,0.36,1.26],["c",0.51,0.27,1.47,0.36,2.01,0.27],["c",0.93,-0.21,1.47,-1.17,1.65,-2.91],["c",0.06,-0.45,0.06,-1.89,0,-2.31],["c",-0.15,-1.2,-0.51,-2.1,-1.05,-2.55],["c",-0.21,-0.18,-0.54,-0.36,-0.81,-0.39],["c",-0.3,-0.06,-0.84,-0.03,-1.26,0.06],["c",-0.93,0.18,-1.65,0.6,-2.16,1.2],["c",-0.15,0.21,-0.27,0.3,-0.39,0.3],["c",-0.15,0,-0.3,-0.09,-0.36,-0.18],["c",-0.06,-0.09,-0.06,-0.15,-0.06,-3.66],["c",0,-3.39,0,-3.57,0.06,-3.66],["c",0.03,-0.06,0.09,-0.15,0.15,-0.18],["z"]],w:10.212,h:14.997},"6":{d:[["M",4.98,-14.97],["c",0.36,-0.03,1.2,0,1.59,0.06],["c",0.9,0.15,1.68,0.51,2.25,1.05],["c",0.57,0.51,0.87,1.23,0.84,1.98],["c",-0.03,0.51,-0.21,0.9,-0.6,1.26],["c",-0.24,0.24,-0.45,0.39,-0.75,0.51],["c",-0.21,0.06,-0.27,0.06,-0.6,0.06],["c",-0.33,0,-0.39,0,-0.6,-0.06],["c",-0.3,-0.12,-0.51,-0.27,-0.75,-0.51],["c",-0.39,-0.36,-0.57,-0.78,-0.57,-1.26],["c",0,-0.27,0,-0.3,0.09,-0.42],["c",0.03,-0.09,0.18,-0.21,0.3,-0.3],["c",0.12,-0.09,0.3,-0.21,0.39,-0.27],["c",0.09,-0.06,0.21,-0.18,0.27,-0.24],["c",0.06,-0.12,0.09,-0.15,0.09,-0.33],["c",0,-0.18,-0.03,-0.24,-0.09,-0.36],["c",-0.24,-0.39,-0.75,-0.6,-1.38,-0.57],["c",-0.54,0.03,-0.9,0.18,-1.23,0.48],["c",-0.81,0.72,-1.08,2.16,-0.96,5.37],["l",0,0.63],["l",0.3,-0.12],["c",0.78,-0.27,1.29,-0.33,2.1,-0.27],["c",1.47,0.12,2.49,0.54,3.27,1.29],["c",0.48,0.51,0.81,1.11,0.96,1.89],["c",0.06,0.27,0.06,0.42,0.06,0.93],["c",0,0.54,0,0.69,-0.06,0.96],["c",-0.15,0.78,-0.48,1.38,-0.96,1.89],["c",-0.54,0.51,-1.17,0.87,-1.98,1.08],["c",-1.14,0.3,-2.4,0.33,-3.24,0.03],["c",-1.5,-0.48,-2.64,-1.89,-3.27,-4.02],["c",-0.36,-1.23,-0.51,-2.82,-0.42,-4.08],["c",0.3,-3.66,2.28,-6.3,4.95,-6.66],["z"],["m",0.66,7.41],["c",-0.27,-0.09,-0.81,-0.12,-1.08,-0.06],["c",-0.72,0.18,-1.08,0.69,-1.23,1.71],["c",-0.06,0.54,-0.06,3,0,3.54],["c",0.18,1.26,0.72,1.77,1.8,1.74],["c",0.39,-0.03,0.63,-0.09,0.9,-0.27],["c",0.66,-0.42,0.9,-1.32,0.9,-3.24],["c",0,-2.22,-0.36,-3.12,-1.29,-3.42],["z"]],w:9.956,h:14.982},"7":{d:[["M",0.21,-14.97],["c",0.21,-0.06,0.45,0,0.54,0.15],["c",0.06,0.09,0.06,0.15,0.06,0.39],["c",0,0.24,0,0.33,0.06,0.42],["c",0.06,0.12,0.21,0.24,0.27,0.24],["c",0.03,0,0.12,-0.12,0.24,-0.21],["c",0.96,-1.2,2.58,-1.35,3.99,-0.42],["c",0.15,0.12,0.42,0.3,0.54,0.45],["c",0.48,0.39,0.81,0.57,1.29,0.6],["c",0.69,0.03,1.5,-0.3,2.13,-0.87],["c",0.09,-0.09,0.27,-0.3,0.39,-0.45],["c",0.12,-0.15,0.24,-0.27,0.3,-0.3],["c",0.18,-0.06,0.39,0.03,0.51,0.21],["c",0.06,0.18,0.06,0.24,-0.27,0.72],["c",-0.18,0.24,-0.54,0.78,-0.78,1.17],["c",-2.37,3.54,-3.54,6.27,-3.87,9],["c",-0.03,0.33,-0.03,0.66,-0.03,1.26],["c",0,0.9,0,1.08,0.15,1.89],["c",0.06,0.45,0.06,0.48,0.03,0.6],["c",-0.06,0.09,-0.21,0.21,-0.3,0.21],["c",-0.03,0,-0.27,-0.06,-0.54,-0.15],["c",-0.84,-0.27,-1.11,-0.3,-1.65,-0.3],["c",-0.57,0,-0.84,0.03,-1.56,0.27],["c",-0.6,0.18,-0.69,0.21,-0.81,0.15],["c",-0.12,-0.06,-0.21,-0.18,-0.21,-0.3],["c",0,-0.15,0.6,-1.44,1.2,-2.61],["c",1.14,-2.22,2.73,-4.68,5.1,-8.01],["c",0.21,-0.27,0.36,-0.48,0.33,-0.48],["c",0,0,-0.12,0.06,-0.27,0.12],["c",-0.54,0.3,-0.99,0.39,-1.56,0.39],["c",-0.75,0.03,-1.2,-0.18,-1.83,-0.75],["c",-0.99,-0.9,-1.83,-1.17,-2.31,-0.72],["c",-0.18,0.15,-0.36,0.51,-0.45,0.84],["c",-0.06,0.24,-0.06,0.33,-0.09,1.98],["c",0,1.62,-0.03,1.74,-0.06,1.8],["c",-0.15,0.24,-0.54,0.24,-0.69,0],["c",-0.06,-0.09,-0.06,-0.15,-0.06,-3.57],["c",0,-3.42,0,-3.48,0.06,-3.57],["c",0.03,-0.06,0.09,-0.12,0.15,-0.15],["z"]],w:10.561,h:15.093},"8":{d:[["M",4.98,-14.97],["c",0.33,-0.03,1.02,-0.03,1.32,0],["c",1.32,0.12,2.49,0.6,3.21,1.32],["c",0.39,0.39,0.66,0.81,0.78,1.29],["c",0.09,0.36,0.09,1.08,0,1.44],["c",-0.21,0.84,-0.66,1.59,-1.59,2.55],["l",-0.3,0.3],["l",0.27,0.18],["c",1.47,0.93,2.31,2.31,2.25,3.75],["c",-0.03,0.75,-0.24,1.35,-0.63,1.95],["c",-0.45,0.66,-1.02,1.14,-1.83,1.53],["c",-1.8,0.87,-4.2,0.87,-6,0.03],["c",-1.62,-0.78,-2.52,-2.16,-2.46,-3.66],["c",0.06,-0.99,0.54,-1.77,1.8,-2.97],["c",0.54,-0.51,0.54,-0.54,0.48,-0.57],["c",-0.39,-0.27,-0.96,-0.78,-1.2,-1.14],["c",-0.75,-1.11,-0.87,-2.4,-0.3,-3.6],["c",0.69,-1.35,2.25,-2.25,4.2,-2.4],["z"],["m",1.53,0.69],["c",-0.42,-0.09,-1.11,-0.12,-1.38,-0.06],["c",-0.3,0.06,-0.6,0.18,-0.81,0.3],["c",-0.21,0.12,-0.6,0.51,-0.72,0.72],["c",-0.51,0.87,-0.42,1.89,0.21,2.52],["c",0.21,0.21,0.36,0.3,1.95,1.23],["c",0.96,0.54,1.74,0.99,1.77,1.02],["c",0.09,0,0.63,-0.6,0.99,-1.11],["c",0.21,-0.36,0.48,-0.87,0.57,-1.23],["c",0.06,-0.24,0.06,-0.36,0.06,-0.72],["c",0,-0.45,-0.03,-0.66,-0.15,-0.99],["c",-0.39,-0.81,-1.29,-1.44,-2.49,-1.68],["z"],["m",-1.44,8.07],["l",-1.89,-1.08],["c",-0.03,0,-0.18,0.15,-0.39,0.33],["c",-1.2,1.08,-1.65,1.95,-1.59,3],["c",0.09,1.59,1.35,2.85,3.21,3.24],["c",0.33,0.06,0.45,0.06,0.93,0.06],["c",0.63,-0,0.81,-0.03,1.29,-0.27],["c",0.9,-0.42,1.47,-1.41,1.41,-2.4],["c",-0.06,-0.66,-0.39,-1.29,-0.9,-1.65],["c",-0.12,-0.09,-1.05,-0.63,-2.07,-1.23],["z"]],w:10.926,h:14.989},"9":{d:[["M",4.23,-14.97],["c",0.42,-0.03,1.29,0,1.62,0.06],["c",0.51,0.12,0.93,0.3,1.38,0.57],["c",1.53,1.02,2.52,3.24,2.73,5.94],["c",0.18,2.55,-0.48,4.98,-1.83,6.57],["c",-1.05,1.26,-2.4,1.89,-3.93,1.83],["c",-1.23,-0.06,-2.31,-0.45,-3.03,-1.14],["c",-0.57,-0.51,-0.87,-1.23,-0.84,-1.98],["c",0.03,-0.51,0.21,-0.9,0.6,-1.26],["c",0.24,-0.24,0.45,-0.39,0.75,-0.51],["c",0.21,-0.06,0.27,-0.06,0.6,-0.06],["c",0.33,-0,0.39,-0,0.6,0.06],["c",0.3,0.12,0.51,0.27,0.75,0.51],["c",0.39,0.36,0.57,0.78,0.57,1.26],["c",0,0.27,0,0.3,-0.09,0.42],["c",-0.03,0.09,-0.18,0.21,-0.3,0.3],["c",-0.12,0.09,-0.3,0.21,-0.39,0.27],["c",-0.09,0.06,-0.21,0.18,-0.27,0.24],["c",-0.06,0.12,-0.06,0.15,-0.06,0.33],["c",0,0.18,0,0.24,0.06,0.36],["c",0.24,0.39,0.75,0.6,1.38,0.57],["c",0.54,-0.03,0.9,-0.18,1.23,-0.48],["c",0.81,-0.72,1.08,-2.16,0.96,-5.37],["l",0,-0.63],["l",-0.3,0.12],["c",-0.78,0.27,-1.29,0.33,-2.1,0.27],["c",-1.47,-0.12,-2.49,-0.54,-3.27,-1.29],["c",-0.48,-0.51,-0.81,-1.11,-0.96,-1.89],["c",-0.06,-0.27,-0.06,-0.42,-0.06,-0.96],["c",0,-0.51,0,-0.66,0.06,-0.93],["c",0.15,-0.78,0.48,-1.38,0.96,-1.89],["c",0.15,-0.12,0.33,-0.27,0.42,-0.36],["c",0.69,-0.51,1.62,-0.81,2.76,-0.93],["z"],["m",1.17,0.66],["c",-0.21,-0.06,-0.57,-0.06,-0.81,-0.03],["c",-0.78,0.12,-1.26,0.69,-1.41,1.74],["c",-0.12,0.63,-0.15,1.95,-0.09,2.79],["c",0.12,1.71,0.63,2.4,1.77,2.46],["c",1.08,0.03,1.62,-0.48,1.8,-1.74],["c",0.06,-0.54,0.06,-3,0,-3.54],["c",-0.15,-1.05,-0.51,-1.53,-1.26,-1.68],["z"]],w:9.959,h:14.986},f:{d:[["M",9.93,-14.28],["c",1.53,-0.18,2.88,0.45,3.12,1.5],["c",0.12,0.51,0,1.32,-0.27,1.86],["c",-0.15,0.3,-0.42,0.57,-0.63,0.69],["c",-0.69,0.36,-1.56,0.03,-1.83,-0.69],["c",-0.09,-0.24,-0.09,-0.69,0,-0.87],["c",0.06,-0.12,0.21,-0.24,0.45,-0.42],["c",0.42,-0.24,0.57,-0.45,0.6,-0.72],["c",0.03,-0.33,-0.09,-0.39,-0.63,-0.42],["c",-0.3,0,-0.45,0,-0.6,0.03],["c",-0.81,0.21,-1.35,0.93,-1.74,2.46],["c",-0.06,0.27,-0.48,2.25,-0.48,2.31],["c",0,0.03,0.39,0.03,0.9,0.03],["c",0.72,0,0.9,0,0.99,0.06],["c",0.42,0.15,0.45,0.72,0.03,0.9],["c",-0.12,0.06,-0.24,0.06,-1.17,0.06],["l",-1.05,0],["l",-0.78,2.55],["c",-0.45,1.41,-0.87,2.79,-0.96,3.06],["c",-0.87,2.37,-2.37,4.74,-3.78,5.91],["c",-1.05,0.9,-2.04,1.23,-3.09,1.08],["c",-1.11,-0.18,-1.89,-0.78,-2.04,-1.59],["c",-0.12,-0.66,0.15,-1.71,0.54,-2.19],["c",0.69,-0.75,1.86,-0.54,2.22,0.39],["c",0.06,0.15,0.09,0.27,0.09,0.48],["c",-0,0.24,-0.03,0.27,-0.12,0.42],["c",-0.03,0.09,-0.15,0.18,-0.27,0.27],["c",-0.09,0.06,-0.27,0.21,-0.36,0.27],["c",-0.24,0.18,-0.36,0.36,-0.39,0.6],["c",-0.03,0.33,0.09,0.39,0.63,0.42],["c",0.42,0,0.63,-0.03,0.9,-0.15],["c",0.6,-0.3,0.96,-0.96,1.38,-2.64],["c",0.09,-0.42,0.63,-2.55,1.17,-4.77],["l",1.02,-4.08],["c",-0,-0.03,-0.36,-0.03,-0.81,-0.03],["c",-0.72,0,-0.81,0,-0.93,-0.06],["c",-0.42,-0.18,-0.39,-0.75,0.03,-0.9],["c",0.09,-0.06,0.27,-0.06,1.05,-0.06],["l",0.96,0],["l",0,-0.09],["c",0.06,-0.18,0.3,-0.72,0.51,-1.17],["c",1.2,-2.46,3.3,-4.23,5.34,-4.5],["z"]],w:16.155,h:19.445},m:{d:[["M",2.79,-8.91],["c",0.09,0,0.3,-0.03,0.45,-0.03],["c",0.24,0.03,0.3,0.03,0.45,0.12],["c",0.36,0.15,0.63,0.54,0.75,1.02],["l",0.03,0.21],["l",0.33,-0.3],["c",0.69,-0.69,1.38,-1.02,2.07,-1.02],["c",0.27,0,0.33,0,0.48,0.06],["c",0.21,0.09,0.48,0.36,0.63,0.6],["c",0.03,0.09,0.12,0.27,0.18,0.42],["c",0.03,0.15,0.09,0.27,0.12,0.27],["c",0,0,0.09,-0.09,0.18,-0.21],["c",0.33,-0.39,0.87,-0.81,1.29,-0.99],["c",0.78,-0.33,1.47,-0.21,2.01,0.33],["c",0.3,0.33,0.48,0.69,0.6,1.14],["c",0.09,0.42,0.06,0.54,-0.54,3.06],["c",-0.33,1.29,-0.57,2.4,-0.57,2.43],["c",0,0.12,0.09,0.21,0.21,0.21],["c",0.24,-0,0.75,-0.3,1.2,-0.72],["c",0.45,-0.39,0.6,-0.45,0.78,-0.27],["c",0.18,0.18,0.09,0.36,-0.45,0.87],["c",-1.05,0.96,-1.83,1.47,-2.58,1.71],["c",-0.93,0.33,-1.53,0.21,-1.8,-0.33],["c",-0.06,-0.15,-0.06,-0.21,-0.06,-0.45],["c",0,-0.24,0.03,-0.48,0.6,-2.82],["c",0.42,-1.71,0.6,-2.64,0.63,-2.79],["c",0.03,-0.57,-0.3,-0.75,-0.84,-0.48],["c",-0.24,0.12,-0.54,0.39,-0.66,0.63],["c",-0.03,0.09,-0.42,1.38,-0.9,3],["c",-0.9,3.15,-0.84,3,-1.14,3.15],["l",-0.15,0.09],["l",-0.78,0],["c",-0.6,0,-0.78,0,-0.84,-0.06],["c",-0.09,-0.03,-0.18,-0.18,-0.18,-0.27],["c",0,-0.03,0.36,-1.38,0.84,-2.97],["c",0.57,-2.04,0.81,-2.97,0.84,-3.12],["c",0.03,-0.54,-0.3,-0.72,-0.84,-0.45],["c",-0.24,0.12,-0.57,0.42,-0.66,0.63],["c",-0.06,0.09,-0.51,1.44,-1.05,2.97],["c",-0.51,1.56,-0.99,2.85,-0.99,2.91],["c",-0.06,0.12,-0.21,0.24,-0.36,0.3],["c",-0.12,0.06,-0.21,0.06,-0.9,0.06],["c",-0.6,0,-0.78,0,-0.84,-0.06],["c",-0.09,-0.03,-0.18,-0.18,-0.18,-0.27],["c",0,-0.03,0.45,-1.38,0.99,-2.97],["c",1.05,-3.18,1.05,-3.18,0.93,-3.45],["c",-0.12,-0.27,-0.39,-0.3,-0.72,-0.15],["c",-0.54,0.27,-1.14,1.17,-1.56,2.4],["c",-0.06,0.15,-0.15,0.3,-0.18,0.36],["c",-0.21,0.21,-0.57,0.27,-0.72,0.09],["c",-0.09,-0.09,-0.06,-0.21,0.06,-0.63],["c",0.48,-1.26,1.26,-2.46,2.01,-3.21],["c",0.57,-0.54,1.2,-0.87,1.83,-1.02],["z"]],w:14.687,h:9.126},p:{d:[["M",1.92,-8.7],["c",0.27,-0.09,0.81,-0.06,1.11,0.03],["c",0.54,0.18,0.93,0.51,1.17,0.99],["c",0.09,0.15,0.15,0.33,0.18,0.36],["l",-0,0.12],["l",0.3,-0.27],["c",0.66,-0.6,1.35,-1.02,2.13,-1.2],["c",0.21,-0.06,0.33,-0.06,0.78,-0.06],["c",0.45,0,0.51,0,0.84,0.09],["c",1.29,0.33,2.07,1.32,2.25,2.79],["c",0.09,0.81,-0.09,2.01,-0.45,2.79],["c",-0.54,1.26,-1.86,2.55,-3.18,3.03],["c",-0.45,0.18,-0.81,0.24,-1.29,0.24],["c",-0.69,-0.03,-1.35,-0.18,-1.86,-0.45],["c",-0.3,-0.15,-0.51,-0.18,-0.69,-0.09],["c",-0.09,0.03,-0.18,0.09,-0.18,0.12],["c",-0.09,0.12,-1.05,2.94,-1.05,3.06],["c",0,0.24,0.18,0.48,0.51,0.63],["c",0.18,0.06,0.54,0.15,0.75,0.15],["c",0.21,0,0.36,0.06,0.42,0.18],["c",0.12,0.18,0.06,0.42,-0.12,0.54],["c",-0.09,0.03,-0.15,0.03,-0.78,0],["c",-1.98,-0.15,-3.81,-0.15,-5.79,0],["c",-0.63,0.03,-0.69,0.03,-0.78,0],["c",-0.24,-0.15,-0.24,-0.57,0.03,-0.66],["c",0.06,-0.03,0.48,-0.09,0.99,-0.12],["c",0.87,-0.06,1.11,-0.09,1.35,-0.21],["c",0.18,-0.06,0.33,-0.18,0.39,-0.3],["c",0.06,-0.12,3.24,-9.42,3.27,-9.6],["c",0.06,-0.33,0.03,-0.57,-0.15,-0.69],["c",-0.09,-0.06,-0.12,-0.06,-0.3,-0.06],["c",-0.69,0.06,-1.53,1.02,-2.28,2.61],["c",-0.09,0.21,-0.21,0.45,-0.27,0.51],["c",-0.09,0.12,-0.33,0.24,-0.48,0.24],["c",-0.18,0,-0.36,-0.15,-0.36,-0.3],["c",0,-0.24,0.78,-1.83,1.26,-2.55],["c",0.72,-1.11,1.47,-1.74,2.28,-1.92],["z"],["m",5.37,1.47],["c",-0.27,-0.12,-0.75,-0.03,-1.14,0.21],["c",-0.75,0.48,-1.47,1.68,-1.89,3.15],["c",-0.45,1.47,-0.42,2.34,0,2.7],["c",0.45,0.39,1.26,0.21,1.83,-0.36],["c",0.51,-0.51,0.99,-1.68,1.38,-3.27],["c",0.3,-1.17,0.33,-1.74,0.15,-2.13],["c",-0.09,-0.15,-0.15,-0.21,-0.33,-0.3],["z"]],w:14.689,h:13.127},r:{d:[["M",6.33,-9.12],["c",0.27,-0.03,0.93,0,1.2,0.06],["c",0.84,0.21,1.23,0.81,1.02,1.53],["c",-0.24,0.75,-0.9,1.17,-1.56,0.96],["c",-0.33,-0.09,-0.51,-0.3,-0.66,-0.75],["c",-0.03,-0.12,-0.09,-0.24,-0.12,-0.3],["c",-0.09,-0.15,-0.3,-0.24,-0.48,-0.24],["c",-0.57,0,-1.38,0.54,-1.65,1.08],["c",-0.06,0.15,-0.33,1.17,-0.9,3.27],["c",-0.57,2.31,-0.81,3.12,-0.87,3.21],["c",-0.03,0.06,-0.12,0.15,-0.18,0.21],["l",-0.12,0.06],["l",-0.81,0.03],["c",-0.69,0,-0.81,0,-0.9,-0.03],["c",-0.09,-0.06,-0.18,-0.21,-0.18,-0.3],["c",0,-0.06,0.39,-1.62,0.9,-3.51],["c",0.84,-3.24,0.87,-3.45,0.87,-3.72],["c",0,-0.21,0,-0.27,-0.03,-0.36],["c",-0.12,-0.15,-0.21,-0.24,-0.42,-0.24],["c",-0.24,0,-0.45,0.15,-0.78,0.42],["c",-0.33,0.36,-0.45,0.54,-0.72,1.14],["c",-0.03,0.12,-0.21,0.24,-0.36,0.27],["c",-0.12,0,-0.15,0,-0.24,-0.06],["c",-0.18,-0.12,-0.18,-0.21,-0.06,-0.54],["c",0.21,-0.57,0.42,-0.93,0.78,-1.32],["c",0.54,-0.51,1.2,-0.81,1.95,-0.87],["c",0.81,-0.03,1.53,0.3,1.92,0.87],["l",0.12,0.18],["l",0.09,-0.09],["c",0.57,-0.45,1.41,-0.84,2.19,-0.96],["z"]],w:9.41,h:9.132},s:{d:[["M",4.47,-8.73],["c",0.09,0,0.36,-0.03,0.57,-0.03],["c",0.75,0.03,1.29,0.24,1.71,0.63],["c",0.51,0.54,0.66,1.26,0.36,1.83],["c",-0.24,0.42,-0.63,0.57,-1.11,0.42],["c",-0.33,-0.09,-0.6,-0.36,-0.6,-0.57],["c",0,-0.03,0.06,-0.21,0.15,-0.39],["c",0.12,-0.21,0.15,-0.33,0.18,-0.48],["c",0,-0.24,-0.06,-0.48,-0.15,-0.6],["c",-0.15,-0.21,-0.42,-0.24,-0.75,-0.15],["c",-0.27,0.06,-0.48,0.18,-0.69,0.36],["c",-0.39,0.39,-0.51,0.96,-0.33,1.38],["c",0.09,0.21,0.42,0.51,0.78,0.72],["c",1.11,0.69,1.59,1.11,1.89,1.68],["c",0.21,0.39,0.24,0.78,0.15,1.29],["c",-0.18,1.2,-1.17,2.16,-2.52,2.52],["c",-1.02,0.24,-1.95,0.12,-2.7,-0.42],["c",-0.72,-0.51,-0.99,-1.47,-0.6,-2.19],["c",0.24,-0.48,0.72,-0.63,1.17,-0.42],["c",0.33,0.18,0.54,0.45,0.57,0.81],["c",0,0.21,-0.03,0.3,-0.33,0.51],["c",-0.33,0.24,-0.39,0.42,-0.27,0.69],["c",0.06,0.15,0.21,0.27,0.45,0.33],["c",0.3,0.09,0.87,0.09,1.2,-0],["c",0.75,-0.21,1.23,-0.72,1.29,-1.35],["c",0.03,-0.42,-0.15,-0.81,-0.54,-1.2],["c",-0.24,-0.24,-0.48,-0.42,-1.41,-1.02],["c",-0.69,-0.42,-1.05,-0.93,-1.05,-1.47],["c",0,-0.39,0.12,-0.87,0.3,-1.23],["c",0.27,-0.57,0.78,-1.05,1.38,-1.35],["c",0.24,-0.12,0.63,-0.27,0.9,-0.3],["z"]],w:6.632,h:8.758},z:{d:[["M",2.64,-7.95],["c",0.36,-0.09,0.81,-0.03,1.71,0.27],["c",0.78,0.21,0.96,0.27,1.74,0.3],["c",0.87,0.06,1.02,0.03,1.38,-0.21],["c",0.21,-0.15,0.33,-0.15,0.48,-0.06],["c",0.15,0.09,0.21,0.3,0.15,0.45],["c",-0.03,0.06,-1.26,1.26,-2.76,2.67],["l",-2.73,2.55],["l",0.54,0.03],["c",0.54,0.03,0.72,0.03,2.01,0.15],["c",0.36,0.03,0.9,0.06,1.2,0.09],["c",0.66,0,0.81,-0.03,1.02,-0.24],["c",0.3,-0.3,0.39,-0.72,0.27,-1.23],["c",-0.06,-0.27,-0.06,-0.27,-0.03,-0.39],["c",0.15,-0.3,0.54,-0.27,0.69,0.03],["c",0.15,0.33,0.27,1.02,0.27,1.5],["c",0,1.47,-1.11,2.7,-2.52,2.79],["c",-0.57,0.03,-1.02,-0.09,-2.01,-0.51],["c",-1.02,-0.42,-1.23,-0.48,-2.13,-0.54],["c",-0.81,-0.06,-0.96,-0.03,-1.26,0.18],["c",-0.12,0.06,-0.24,0.12,-0.27,0.12],["c",-0.27,0,-0.45,-0.3,-0.36,-0.51],["c",0.03,-0.06,1.32,-1.32,2.91,-2.79],["l",2.88,-2.73],["c",-0.03,0,-0.21,0.03,-0.42,0.06],["c",-0.21,0.03,-0.78,0.09,-1.23,0.12],["c",-1.11,0.12,-1.23,0.15,-1.95,0.27],["c",-0.72,0.15,-1.17,0.18,-1.29,0.09],["c",-0.27,-0.18,-0.21,-0.75,0.12,-1.26],["c",0.39,-0.6,0.93,-1.02,1.59,-1.2],["z"]],w:8.573,h:8.743},"+":{d:[["M",3.48,-11.19],["c",0.18,-0.09,0.36,-0.09,0.54,0],["c",0.18,0.09,0.24,0.15,0.33,0.3],["l",0.06,0.15],["l",0,1.29],["l",0,1.29],["l",1.29,0],["c",1.23,0,1.29,0,1.41,0.06],["c",0.06,0.03,0.15,0.09,0.18,0.12],["c",0.12,0.09,0.21,0.33,0.21,0.48],["c",0,0.15,-0.09,0.39,-0.21,0.48],["c",-0.03,0.03,-0.12,0.09,-0.18,0.12],["c",-0.12,0.06,-0.18,0.06,-1.41,0.06],["l",-1.29,0],["l",0,1.29],["c",0,1.23,0,1.29,-0.06,1.41],["c",-0.09,0.18,-0.15,0.24,-0.3,0.33],["c",-0.21,0.09,-0.39,0.09,-0.57,0],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["c",-0.06,-0.12,-0.06,-0.18,-0.06,-1.41],["l",0,-1.29],["l",-1.29,0],["c",-1.23,0,-1.29,0,-1.41,-0.06],["c",-0.18,-0.09,-0.24,-0.15,-0.33,-0.33],["c",-0.09,-0.18,-0.09,-0.36,0,-0.54],["c",0.09,-0.18,0.15,-0.24,0.33,-0.33],["l",0.15,-0.06],["l",1.26,0],["l",1.29,0],["l",0,-1.29],["c",0,-1.23,0,-1.29,0.06,-1.41],["c",0.09,-0.18,0.15,-0.24,0.33,-0.33],["z"]],w:7.507,h:7.515},",":{d:[["M",1.32,-3.36],["c",0.57,-0.15,1.17,0.03,1.59,0.45],["c",0.45,0.45,0.6,0.96,0.51,1.89],["c",-0.09,1.23,-0.42,2.46,-0.99,3.93],["c",-0.3,0.72,-0.72,1.62,-0.78,1.68],["c",-0.18,0.21,-0.51,0.18,-0.66,-0.06],["c",-0.03,-0.06,-0.06,-0.15,-0.06,-0.18],["c",0,-0.06,0.12,-0.33,0.24,-0.63],["c",0.84,-1.8,1.02,-2.61,0.69,-3.24],["c",-0.12,-0.24,-0.27,-0.36,-0.75,-0.6],["c",-0.36,-0.15,-0.42,-0.21,-0.6,-0.39],["c",-0.69,-0.69,-0.69,-1.71,0,-2.4],["c",0.21,-0.21,0.51,-0.39,0.81,-0.45],["z"]],w:3.452,h:8.143},"-":{d:[["M",0.18,-5.34],["c",0.09,-0.06,0.15,-0.06,2.31,-0.06],["c",2.46,0,2.37,0,2.46,0.21],["c",0.12,0.21,0.03,0.42,-0.15,0.54],["c",-0.09,0.06,-0.15,0.06,-2.28,0.06],["c",-2.16,0,-2.22,0,-2.31,-0.06],["c",-0.27,-0.15,-0.27,-0.54,-0.03,-0.69],["z"]],w:5.001,h:0.81},".":{d:[["M",1.32,-3.36],["c",1.05,-0.27,2.1,0.57,2.1,1.65],["c",0,1.08,-1.05,1.92,-2.1,1.65],["c",-0.9,-0.21,-1.5,-1.14,-1.26,-2.04],["c",0.12,-0.63,0.63,-1.11,1.26,-1.26],["z"]],w:3.413,h:3.402}}; this.printSymbol=function(b,g,c,f){if(!a[c]){return null}var d=this.pathClone(a[c].d);d[0][1]+=b;d[0][2]+=g;var e=f.path().attr({path:d,stroke:"none",fill:"#000000"});return e};this.getPathForSymbol=function(b,g,e,d,c){d=d||1;c=c||1;if(!a[e]){return null}var f=this.pathClone(a[e].d);if(d!==1||c!==1){this.pathScale(f,d,c)}f[0][1]+=b;f[0][2]+=g;return f};this.getSymbolWidth=function(b){if(a[b]){return a[b].w}return 0};this.getSymbolHeight=function(b){if(a[b]){return a[b].h}return 0};this.getSymbolAlign=function(b){if(b.substring(0,7)==="scripts"&&b!=="scripts.roll"){return"center"}return"left"};this.pathClone=function(g){var d=[];for(var c=0,e=g.length;c<e;c++){d[c]=[];for(var b=0,f=g[c].length;b<f;b++){d[c][b]=g[c][b]}}return d};this.pathScale=function(h,f,d){for(var c=0,e=h.length;c<e;c++){var k=h[c];var b,g;for(b=1,g=k.length;b<g;b++){k[b]*=(b%2)?f:d}}};this.getYCorr=function(b){switch(b){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":return -3;case"timesig.common":case"timesig.cut":return -1;case"flags.d32nd":return -1;case"flags.d64th":return -2;case"flags.u32nd":return 1;case"flags.u64th":return 3;case"rests.whole":return 1;case"rests.half":return -1;case"rests.8th":return -1;case"rests.quarter":return -2;case"rests.16th":return -1;case"rests.32nd":return -1;case"rests.64th":return -1;default:return 0}}};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.write){window.ABCJS.write={}}ABCJS.write.StaffGroupElement=function(){this.voices=[];this.staffs=[];this.stafflines=[]};ABCJS.write.StaffGroupElement.prototype.addVoice=function(c,b,a){this.voices[this.voices.length]=c;if(!this.staffs[b]){this.staffs[this.staffs.length]={top:0,highest:7,lowest:7};this.stafflines[this.stafflines.length]=a}c.staff=this.staffs[b]};ABCJS.write.StaffGroupElement.prototype.finished=function(){for(var a=0;a<this.voices.length;a++){if(!this.voices[a].layoutEnded()){return false}}return true};ABCJS.write.StaffGroupElement.prototype.layout=function(f,n){this.spacingunits=0;this.minspace=1000;var k=n.paddingleft;var a=0;for(var d=0;d<this.voices.length;d++){if(this.voices[d].header){var o=n.paper.text(100,-10,this.voices[d].header).attr({"font-size":12,"font-family":"serif"});a=Math.max(a,o.getBBox().width);o.remove()}}k=k+a*1.1;this.startx=k;var c=0;for(d=0;d<this.voices.length;d++){this.voices[d].beginLayout(k)}while(!this.finished()){c=null;for(d=0;d<this.voices.length;d++){if(!this.voices[d].layoutEnded()&&(!c||this.voices[d].getDurationIndex()<c)){c=this.voices[d].getDurationIndex()}}var m=[];var l=[];for(d=0;d<this.voices.length;d++){if(this.voices[d].getDurationIndex()!==c){l.push(this.voices[d])}else{m.push(this.voices[d])}}var h=0;for(d=0;d<m.length;d++){if(m[d].nextx>k){k=m[d].nextx;h=m[d].spacingunits}}this.spacingunits+=h;this.minspace=Math.min(this.minspace,h);for(d=0;d<l.length;d++){if(l[d].spacingunits-=h){}}for(d=0;d<m.length;d++){var e=m[d].layoutOneItem(k,f);var p=e-k;if(p>0){k=e;for(var b=0;b<d;b++){m[b].shiftRight(p)}}}for(d=0;d<m.length;d++){var g=m[d];g.updateIndices()}}for(d=0;d<this.voices.length;d++){if(this.voices[d].nextx>k){k=this.voices[d].nextx;h=this.voices[d].spacingunits}}this.spacingunits+=h;this.w=k;for(d=0;d<this.voices.length;d++){this.voices[d].w=this.w}};ABCJS.write.StaffGroupElement.prototype.draw=function(e,h){this.y=h;for(var d=0;d<this.staffs.length;d++){var c=this.staffs[d].highest-((d===0)?20:15);var b=this.staffs[d].lowest-((d===this.staffs.length-1)?0:0);this.staffs[d].top=h;if(c>0){h+=c*ABCJS.write.spacing.STEP}this.staffs[d].y=h;h+=ABCJS.write.spacing.STAVEHEIGHT*0.9;if(b<0){h-=b*ABCJS.write.spacing.STEP}this.staffs[d].bottom=h}this.height=h-this.y;var g=0;for(d=0;d<this.voices.length;d++){this.voices[d].draw(e,g);g=this.voices[d].barbottom}if(this.staffs.length>1){e.y=this.staffs[0].y;var f=e.calcY(10);e.y=this.staffs[this.staffs.length-1].y;var a=e.calcY(2);e.printStem(this.startx,0.6,f,a)}for(d=0;d<this.staffs.length;d++){if(this.stafflines[d]===0){continue}e.y=this.staffs[d].y;if(this.stafflines[d]===undefined){this.stafflines[d]=5}e.printStave(this.startx,this.w,this.stafflines[d])}};ABCJS.write.VoiceElement=function(b,a){this.children=[];this.beams=[];this.otherchildren=[];this.w=0;this.duplicate=false;this.voicenumber=b;this.voicetotal=a};ABCJS.write.VoiceElement.prototype.addChild=function(a){this.children[this.children.length]=a};ABCJS.write.VoiceElement.prototype.addOther=function(a){if(a instanceof ABCJS.write.BeamElem){this.beams.push(a)}else{this.otherchildren.push(a)}};ABCJS.write.VoiceElement.prototype.updateIndices=function(){if(!this.layoutEnded()){this.durationindex+=this.children[this.i].duration;this.i++;this.minx=this.nextminx}};ABCJS.write.VoiceElement.prototype.layoutEnded=function(){return(this.i>=this.children.length)};ABCJS.write.VoiceElement.prototype.getDurationIndex=function(){return this.durationindex-(this.children[this.i]&&(this.children[this.i].duration>0)?0:5e-7)};ABCJS.write.VoiceElement.prototype.beginLayout=function(a){this.i=0;this.durationindex=0;this.ii=this.children.length;this.startx=a;this.minx=a;this.nextminx=a;this.nextx=a;this.spacingunits=0};ABCJS.write.VoiceElement.prototype.layoutOneItem=function(a,d){var c=this.children[this.i];if(!c){return 0}var b=a-this.minx;if(b<c.getExtraWidth()){a+=c.getExtraWidth()-b}c.x=a;a+=(d*Math.sqrt(c.duration*8));this.nextminx=c.x+c.getMinWidth();if(this.i!==this.ii-1){this.nextminx+=c.minspacing}if(this.nextminx>a){a=this.nextminx;this.spacingunits=0}else{this.spacingunits=Math.sqrt(c.duration*8)}this.nextx=a;this.staff.highest=Math.max(c.top,this.staff.highest);this.staff.lowest=Math.min(c.bottom,this.staff.lowest);return c.x};ABCJS.write.VoiceElement.prototype.shiftRight=function(a){var b=this.children[this.i];if(!b){return}b.x+=a;this.nextminx+=a;this.nextx+=a};ABCJS.write.VoiceElement.prototype.draw=function(e,f){var c=this.w-1;e.y=this.staff.y;e.staffbottom=this.staff.bottom;this.barbottom=e.calcY(2);if(this.header){var d=12-(this.voicenumber+1)*(12/(this.voicetotal+1));e.paper.text((this.startx-e.paddingleft)/2+e.paddingleft,e.calcY(d),this.header).attr({"font-size":12,"font-family":"serif"})}for(var a=0,b=this.children.length;a<b;a++){this.children[a].draw(e,(this.barto||a===b-1)?f:0)}window.ABCJS.parse.each(this.beams,function(g){g.draw(e)});window.ABCJS.parse.each(this.otherchildren,function(g){g.draw(e,this.startx+10,c)})};ABCJS.write.AbsoluteElement=function(c,b,a){this.abcelem=c;this.duration=b;this.minspacing=a||0;this.x=0;this.children=[];this.heads=[];this.extra=[];this.extraw=0;this.decs=[];this.w=0;this.right=[];this.invisible=false;this.bottom=7;this.top=7};ABCJS.write.AbsoluteElement.prototype.getMinWidth=function(){return this.w};ABCJS.write.AbsoluteElement.prototype.getExtraWidth=function(){return -this.extraw};ABCJS.write.AbsoluteElement.prototype.addExtra=function(a){if(a.dx<this.extraw){this.extraw=a.dx}this.extra[this.extra.length]=a;this.addChild(a)};ABCJS.write.AbsoluteElement.prototype.addHead=function(a){if(a.dx<this.extraw){this.extraw=a.dx }this.heads[this.heads.length]=a;this.addRight(a)};ABCJS.write.AbsoluteElement.prototype.addRight=function(a){if(a.dx+a.w>this.w){this.w=a.dx+a.w}this.right[this.right.length]=a;this.addChild(a)};ABCJS.write.AbsoluteElement.prototype.addChild=function(a){a.parent=this;this.children[this.children.length]=a;this.pushTop(a.top);this.pushBottom(a.bottom)};ABCJS.write.AbsoluteElement.prototype.pushTop=function(a){this.top=Math.max(a,this.top)};ABCJS.write.AbsoluteElement.prototype.pushBottom=function(a){this.bottom=Math.min(a,this.bottom)};ABCJS.write.AbsoluteElement.prototype.draw=function(e,f){this.elemset=e.paper.set();if(this.invisible){return}e.beginGroup();for(var d=0;d<this.children.length;d++){this.elemset.push(this.children[d].draw(e,this.x,f))}this.elemset.push(e.endGroup());if(this.klass){this.setClass("mark","","#00ff00")}var c=this;this.elemset.mouseup(function(i){e.notifySelect(c)});this.abcelem.abselem=this;var h=ABCJS.write.spacing.STEP*e.scale;var g=function(){this.dy=0},b=function(j,i){i=Math.round(i/h)*h;this.translate(0,-this.dy);this.dy=i;this.translate(0,this.dy)},a=function(){var i=-Math.round(this.dy/h);c.abcelem.pitches[0].pitch+=i;c.abcelem.pitches[0].verticalPos+=i;e.notifyChange()};if(this.abcelem.el_type==="note"&&e.editable){this.elemset.drag(b,g,a)}};ABCJS.write.AbsoluteElement.prototype.isIE= /*@cc_on!@*/ false;ABCJS.write.AbsoluteElement.prototype.setClass=function(d,e,b){this.elemset.attr({fill:b});if(!this.isIE){for(var c=0;c<this.elemset.length;c++){if(this.elemset[c][0].setAttribute){var a=this.elemset[c][0].getAttribute("class");if(!a){a=""}a=a.replace(e,"");a=a.replace(d,"");if(d.length>0){if(a.length>0&&a.charAt(a.length-1)!==" "){a+=" "}a+=d}this.elemset[c][0].setAttribute("class",a)}}}};ABCJS.write.AbsoluteElement.prototype.highlight=function(){this.setClass("note_selected","","#ff0000")};ABCJS.write.AbsoluteElement.prototype.unhighlight=function(){this.setClass("","note_selected","#000000")};ABCJS.write.RelativeElement=function(f,b,a,e,d){d=d||{};this.x=0;this.c=f;this.dx=b;this.w=a;this.pitch=e;this.scalex=d.scalex||1;this.scaley=d.scaley||1;this.type=d.type||"symbol";this.pitch2=d.pitch2;this.linewidth=d.linewidth;this.attributes=d.attributes;this.top=e+((d.extreme==="above")?7:0);this.bottom=e-((d.extreme==="below")?7:0)};ABCJS.write.RelativeElement.prototype.draw=function(b,a,c){this.x=a+this.dx;switch(this.type){case"symbol":if(this.c===null){return null}this.graphelem=b.printSymbol(this.x,this.pitch,this.c,this.scalex,this.scaley);break;case"debug":this.graphelem=b.debugMsg(this.x,this.c);break;case"debugLow":this.graphelem=b.printLyrics(this.x,this.c);break;case"text":this.graphelem=b.printText(this.x,this.pitch,this.c);break;case"bar":this.graphelem=b.printStem(this.x,this.linewidth,b.calcY(this.pitch),(c)?c:b.calcY(this.pitch2));break;case"stem":this.graphelem=b.printStem(this.x,this.linewidth,b.calcY(this.pitch),b.calcY(this.pitch2));break;case"ledger":this.graphelem=b.printStaveLine(this.x,this.x+this.w,this.pitch);break}if(this.scalex!==1&&this.graphelem){this.graphelem.scale(this.scalex,this.scaley,this.x,b.calcY(this.pitch))}if(this.attributes){this.graphelem.attr(this.attributes)}return this.graphelem};ABCJS.write.EndingElem=function(c,b,a){this.text=c;this.anchor1=b;this.anchor2=a};ABCJS.write.EndingElem.prototype.draw=function(c,d,b){var a;if(this.anchor1){d=this.anchor1.x+this.anchor1.w;a=ABCJS.write.sprintf("M %f %f L %f %f",d,c.y,d,c.y+10);c.printPath({path:a,stroke:"#000000",fill:"#000000"});c.printText(d+5,18.5,this.text).attr({"font-size":"10px"})}if(this.anchor2){b=this.anchor2.x;a=ABCJS.write.sprintf("M %f %f L %f %f",b,c.y,b,c.y+10);c.printPath({path:a,stroke:"#000000",fill:"#000000"})}a=ABCJS.write.sprintf("M %f %f L %f %f",d,c.y,b,c.y);c.printPath({path:a,stroke:"#000000",fill:"#000000"})};ABCJS.write.TieElem=function(d,b,a,c){this.anchor1=d;this.anchor2=b;this.above=a;this.force=c};ABCJS.write.TieElem.prototype.draw=function(c,e,a){var d;var b;if(this.startlimitelem){e=this.startlimitelem.x+this.startlimitelem.w}if(this.endlimitelem){a=this.endlimitelem.x}if(!this.force&&this.anchor2&&this.anchor2.pitch===this.anchor2.top){this.above=true}if(this.anchor1){e=this.anchor1.x;d=this.above?this.anchor1.highestVert:this.anchor1.pitch;if(!this.anchor2){b=this.above?this.anchor1.highestVert:this.anchor1.pitch}}if(this.anchor2){a=this.anchor2.x;b=this.above?this.anchor2.highestVert:this.anchor2.pitch;if(!this.anchor1){d=this.above?this.anchor2.highestVert:this.anchor2.pitch}}c.drawArc(e,a,d,b,this.above)};ABCJS.write.DynamicDecoration=function(a,b){this.anchor=a;this.dec=b};ABCJS.write.DynamicDecoration.prototype.draw=function(d,f,a){var e=d.layouter.minY-7;var c=1;var b=1;d.printSymbol(this.anchor.x,e,this.dec,c,b)};ABCJS.write.CrescendoElem=function(c,b,a){this.anchor1=c;this.anchor2=b;this.dir=a};ABCJS.write.CrescendoElem.prototype.draw=function(b,c,a){if(this.dir==="<"){this.drawLine(b,0,-4);this.drawLine(b,0,4)}else{this.drawLine(b,-4,0);this.drawLine(b,4,0)}};ABCJS.write.CrescendoElem.prototype.drawLine=function(d,c,b){var e=d.layouter.minY-7;var a=ABCJS.write.sprintf("M %f %f L %f %f",this.anchor1.x,d.calcY(e)+c-4,this.anchor2.x,d.calcY(e)+b-4);d.printPath({path:a,stroke:"#000000"})};ABCJS.write.TripletElem=function(d,c,b,a){this.anchor1=c;this.anchor2=b;this.above=a;this.number=d};ABCJS.write.TripletElem.prototype.draw=function(d,g,c){if(this.anchor1&&this.anchor2){var f=this.above?16:-1;if(this.anchor1.parent.beam&&this.anchor1.parent.beam===this.anchor2.parent.beam){var b=this.anchor1.parent.beam;this.above=b.asc;f=b.pos}else{this.drawLine(d,d.calcY(f))}var e=this.anchor1.x+this.anchor2.x;var a=0;if(b){if(this.above){e+=(this.anchor2.w+this.anchor1.w);a=4}else{a=-4}}else{e+=this.anchor2.w}d.printText(e/2,f+a,this.number,"middle").attr({"font-size":"10px","font-style":"italic"})}};ABCJS.write.TripletElem.prototype.drawLine=function(c,e){var b;var d=this.anchor1.x;b=ABCJS.write.sprintf("M %f %f L %f %f",d,e,d,e+5);c.printPath({path:b,stroke:"#000000"});var a=this.anchor2.x+this.anchor2.w;b=ABCJS.write.sprintf("M %f %f L %f %f",a,e,a,e+5);c.printPath({path:b,stroke:"#000000"});b=ABCJS.write.sprintf("M %f %f L %f %f",d,e,(d+a)/2-5,e);c.printPath({path:b,stroke:"#000000"});b=ABCJS.write.sprintf("M %f %f L %f %f",(d+a)/2+5,e,a,e);c.printPath({path:b,stroke:"#000000"})};ABCJS.write.BeamElem=function(a,b){this.isflat=(b);this.isgrace=(a&&a==="grace");this.forceup=(a&&a==="up");this.forcedown=(a&&a==="down");this.elems=[];this.total=0;this.dy=(this.asc)?ABCJS.write.spacing.STEP*1.2:-ABCJS.write.spacing.STEP*1.2;if(this.isgrace){this.dy=this.dy*0.4}this.allrests=true};ABCJS.write.BeamElem.prototype.add=function(a){var b=a.abcelem.averagepitch;if(b===undefined){return}this.allrests=this.allrests&&a.abcelem.rest;a.beam=this;this.elems.push(a);this.total+=b;if(!this.min||a.abcelem.minpitch<this.min){this.min=a.abcelem.minpitch}if(!this.max||a.abcelem.maxpitch>this.max){this.max=a.abcelem.maxpitch}};ABCJS.write.BeamElem.prototype.average=function(){try{return this.total/this.elems.length }catch(a){return 0}};ABCJS.write.BeamElem.prototype.draw=function(a){if(this.elems.length===0||this.allrests){return}this.drawBeam(a);this.drawStems(a)};ABCJS.write.BeamElem.prototype.calcDir=function(){var a=this.average();this.asc=(this.forceup||this.isgrace||a<6)&&(!this.forcedown);return this.asc};ABCJS.write.BeamElem.prototype.drawBeam=function(i){var b=this.average();var h=(this.isgrace)?5:7;this.calcDir();var a=this.asc?5:8;this.pos=Math.round(this.asc?Math.max(b+h,this.max+a):Math.min(b-h,this.min-a));var f=this.elems[0].abcelem.averagepitch-this.elems[this.elems.length-1].abcelem.averagepitch;if(this.isflat){f=0}var e=this.elems.length/2;if(f>e){f=e}if(f<-e){f=-e}this.starty=i.calcY(this.pos+Math.floor(f/2));this.endy=i.calcY(this.pos+Math.floor(-f/2));var d=this.elems[0].heads[(this.asc)?0:this.elems[0].heads.length-1];var g=this.elems[this.elems.length-1].heads[(this.asc)?0:this.elems[this.elems.length-1].heads.length-1];this.startx=d.x;if(this.asc){this.startx+=d.w-0.6}this.endx=g.x;if(this.asc){this.endx+=g.w}if(this.asc&&this.pos<6){this.starty=i.calcY(6);this.endy=i.calcY(6)}else{if(!this.asc&&this.pos>6){this.starty=i.calcY(6);this.endy=i.calcY(6)}}var c="M"+this.startx+" "+this.starty+" L"+this.endx+" "+this.endy+"L"+this.endx+" "+(this.endy+this.dy)+" L"+this.startx+" "+(this.starty+this.dy)+"z";i.printPath({path:c,stroke:"none",fill:"#000000"})};ABCJS.write.BeamElem.prototype.drawStems=function(r){var a=[];r.beginGroup();for(var g=0,q=this.elems.length;g<q;g++){if(this.elems[g].abcelem.rest){continue}var m=this.elems[g].heads[(this.asc)?0:this.elems[g].heads.length-1];var e=(this.isgrace)?1/3:1/5;var b=m.pitch+((this.asc)?e:-e);var o=r.calcY(b);var p=m.x+((this.asc)?m.w:0);var l=this.getBarYAt(p);var s=(this.asc)?-0.6:0.6;r.printStem(p,s,o,l);var n=(this.asc)?1.5*ABCJS.write.spacing.STEP:-1.5*ABCJS.write.spacing.STEP;if(this.isgrace){n=n*2/3}for(var c=ABCJS.write.getDurlog(this.elems[g].duration);c<-3;c++){if(a[-4-c]){a[-4-c].single=false}else{a[-4-c]={x:p+((this.asc)?-0.6:0),y:l+n*(-4-c+1),durlog:c,single:true}}}for(var f=a.length-1;f>=0;f--){if(g===q-1||ABCJS.write.getDurlog(this.elems[g+1].duration)>(-f-4)){var k=p;var h=l+n*(f+1);if(a[f].single){k=(g===0)?p+5:p-5;h=this.getBarYAt(k)+n*(f+1)}var d="M"+a[f].x+" "+a[f].y+" L"+k+" "+h+"L"+k+" "+(h+this.dy)+" L"+a[f].x+" "+(a[f].y+this.dy)+"z";r.printPath({path:d,stroke:"none",fill:"#000000"});a=a.slice(0,f)}}}r.endGroup()};ABCJS.write.BeamElem.prototype.getBarYAt=function(a){return this.starty+(this.endy-this.starty)/(this.endx-this.startx)*(a-this.startx)};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.write){window.ABCJS.write={}}ABCJS.write.getDuration=function(a){var b=0;if(a.duration){b=a.duration}return b};ABCJS.write.getDurlog=function(a){return Math.floor(Math.log(a)/Math.log(2))};ABCJS.write.Layout=function(b,a){this.glyphs=b;this.isBagpipes=a;this.chartable={rest:{0:"rests.whole",1:"rests.half",2:"rests.quarter",3:"rests.8th",4:"rests.16th",5:"rests.32nd",6:"rests.64th",7:"rests.128th"},note:{"-1":"noteheads.dbl",0:"noteheads.whole",1:"noteheads.half",2:"noteheads.quarter",3:"noteheads.quarter",4:"noteheads.quarter",5:"noteheads.quarter",6:"noteheads.quarter"},uflags:{3:"flags.u8th",4:"flags.u16th",5:"flags.u32nd",6:"flags.u64th"},dflags:{3:"flags.d8th",4:"flags.d16th",5:"flags.d32nd",6:"flags.d64th"}};this.slurs={};this.ties=[];this.slursbyvoice={};this.tiesbyvoice={};this.endingsbyvoice={};this.s=0;this.v=0;this.stafflines=5};ABCJS.write.Layout.prototype.getCurrentVoiceId=function(){return"s"+this.s+"v"+this.v};ABCJS.write.Layout.prototype.pushCrossLineElems=function(){this.slursbyvoice[this.getCurrentVoiceId()]=this.slurs;this.tiesbyvoice[this.getCurrentVoiceId()]=this.ties;this.endingsbyvoice[this.getCurrentVoiceId()]=this.partstartelem};ABCJS.write.Layout.prototype.popCrossLineElems=function(){this.slurs=this.slursbyvoice[this.getCurrentVoiceId()]||{};this.ties=this.tiesbyvoice[this.getCurrentVoiceId()]||[];this.partstartelem=this.endingsbyvoice[this.getCurrentVoiceId()]};ABCJS.write.Layout.prototype.getElem=function(){if(this.abcline.length<=this.pos){return null}return this.abcline[this.pos]};ABCJS.write.Layout.prototype.getNextElem=function(){if(this.abcline.length<=this.pos+1){return null}return this.abcline[this.pos+1]};ABCJS.write.Layout.prototype.printABCLine=function(a){this.minY=2;this.staffgroup=new ABCJS.write.StaffGroupElement();for(this.s=0;this.s<a.length;this.s++){this.printABCStaff(a[this.s])}return this.staffgroup};ABCJS.write.Layout.prototype.printABCStaff=function(a){var b="";if(a.bracket){b+="bracket "+a.bracket+" "}if(a.brace){b+="brace "+a.brace+" "}for(this.v=0;this.v<a.voices.length;this.v++){this.voice=new ABCJS.write.VoiceElement(this.v,a.voices.length);if(this.v===0){this.voice.barfrom=(a.connectBarLines==="start"||a.connectBarLines==="continue");this.voice.barto=(a.connectBarLines==="continue"||a.connectBarLines==="end")}else{this.voice.duplicate=true}if(a.title&&a.title[this.v]){this.voice.header=a.title[this.v]}this.voice.addChild(this.printClef(a.clef));this.voice.addChild(this.printKeySignature(a.key));if(a.meter){this.voice.addChild(this.printTimeSignature(a.meter))}this.printABCVoice(a.voices[this.v]);this.staffgroup.addVoice(this.voice,this.s,this.stafflines)}};ABCJS.write.Layout.prototype.printABCVoice=function(b){this.popCrossLineElems();this.stemdir=(this.isBagpipes)?"down":null;this.abcline=b;if(this.partstartelem){this.partstartelem=new ABCJS.write.EndingElem("",null,null);this.voice.addOther(this.partstartelem)}for(var a in this.slurs){if(this.slurs.hasOwnProperty(a)){this.slurs[a]=new ABCJS.write.TieElem(null,null,this.slurs[a].above,this.slurs[a].force);this.voice.addOther(this.slurs[a])}}for(var c=0;c<this.ties.length;c++){this.ties[c]=new ABCJS.write.TieElem(null,null,this.ties[c].above,this.ties[c].force);this.voice.addOther(this.ties[c])}for(this.pos=0;this.pos<this.abcline.length;this.pos++){var d=this.printABCElement();for(c=0;c<d.length;c++){this.voice.addChild(d[c])}}this.pushCrossLineElems()};ABCJS.write.Layout.prototype.printABCElement=function(){var d=[];var b=this.getElem();switch(b.el_type){case"note":d=this.printBeam();break;case"bar":d[0]=this.printBarLine(b);if(this.voice.duplicate){d[0].invisible=true}break;case"meter":d[0]=this.printTimeSignature(b);if(this.voice.duplicate){d[0].invisible=true}break;case"clef":d[0]=this.printClef(b);if(this.voice.duplicate){d[0].invisible=true}break;case"key":d[0]=this.printKeySignature(b);if(this.voice.duplicate){d[0].invisible=true}break;case"stem":this.stemdir=b.direction;break;case"part":var a=new ABCJS.write.AbsoluteElement(b,0,0);a.addChild(new ABCJS.write.RelativeElement(b.title,0,0,18,{type:"text",attributes:{"font-weight":"bold","font-size":"16px","font-family":"serif"}}));d[0]=a;break;default:var c=new ABCJS.write.AbsoluteElement(b,0,0);c.addChild(new ABCJS.write.RelativeElement("element type "+b.el_type,0,0,0,{type:"debug"}));d[0]=c}return d};ABCJS.write.Layout.prototype.printBeam=function(){var e=[]; if(this.getElem().startBeam&&!this.getElem().endBeam){var f=new ABCJS.write.BeamElem(this.stemdir);var b=this.pos;var c;while(this.getElem()){c=this.printNote(this.getElem(),true,true);f.add(c);if(this.getElem().endBeam){break}this.pos++}var a=f.calcDir();this.pos=b;f=new ABCJS.write.BeamElem(a?"up":"down");var d=this.stemdir;this.stemdir=a?"up":"down";while(this.getElem()){c=this.printNote(this.getElem(),true);e.push(c);f.add(c);if(this.getElem().endBeam){break}this.pos++}this.stemdir=d;this.voice.addOther(f)}else{e[0]=this.printNote(this.getElem())}return e};ABCJS.write.sortPitch=function(c){var a;do{a=true;for(var d=0;d<c.pitches.length-1;d++){if(c.pitches[d].pitch>c.pitches[d+1].pitch){a=false;var b=c.pitches[d];c.pitches[d]=c.pitches[d+1];c.pitches[d+1]=b}}}while(!a)};ABCJS.write.Layout.prototype.printNote=function(K,d,Q){var o=null;var a=null;this.roomtaken=0;this.roomtakenright=0;var C=0;var S="";var A=null;var q=[];var H,M,l;var b,P,O,e;var r=ABCJS.write.getDuration(K);var v=Math.floor(Math.log(r)/Math.log(2));var U=0;for(var f=Math.pow(2,v),N=f/2;f<r;U++,f+=N,N/=2){}var g=new ABCJS.write.AbsoluteElement(K,r,1);if(K.rest){var k=7;if(this.stemdir==="down"){k=3}if(this.stemdir==="up"){k=11}switch(K.rest.type){case"rest":S=this.chartable.rest[-v];K.averagepitch=k;K.minpitch=k;K.maxpitch=k;break;case"invisible":case"spacer":S=""}if(!Q){o=this.printNoteHead(g,S,{verticalPos:k},null,0,-this.roomtaken,null,U,0,1)}if(o){g.addHead(o)}this.roomtaken+=this.accidentalshiftx;this.roomtakenright=Math.max(this.roomtakenright,this.dotshiftx)}else{ABCJS.write.sortPitch(K);var n=0;for(H=0,l=K.pitches.length;H<l;H++){n+=K.pitches[H].verticalPos}K.averagepitch=n/K.pitches.length;K.minpitch=K.pitches[0].verticalPos;this.minY=Math.min(K.minpitch,this.minY);K.maxpitch=K.pitches[K.pitches.length-1].verticalPos;var T=(K.averagepitch>=6)?"down":"up";if(this.stemdir){T=this.stemdir}for(H=(T==="down")?K.pitches.length-2:1;(T==="down")?H>=0:H<K.pitches.length;H=(T==="down")?H-1:H+1){var w=K.pitches[(T==="down")?H+1:H-1];var D=K.pitches[H];var E=(T==="down")?w.pitch-D.pitch:D.pitch-w.pitch;if(E<=1&&!w.printer_shift){D.printer_shift=(E)?"different":"same";if(D.pitch>11||D.pitch<1){q.push(D.pitch-(D.pitch%2))}if(T==="down"){this.roomtaken=this.glyphs.getSymbolWidth(this.chartable.note[-v])+2}else{C=this.glyphs.getSymbolWidth(this.chartable.note[-v])+2}}}this.accidentalSlot=[];for(H=0;H<K.pitches.length;H++){if(!d){if((T==="down"&&H!==0)||(T==="up"&&H!==l-1)){A=null}else{A=this.chartable[(T==="down")?"dflags":"uflags"][-v]}S=this.chartable.note[-v]}else{S="noteheads.quarter"}K.pitches[H].highestVert=K.pitches[H].verticalPos;var j=(this.stemdir==="up"||T==="up")&&H===0;var I=(this.stemdir==="down"||T==="down")&&H===l-1;if(!Q&&(j||I)){if(K.startSlur||l===1){K.pitches[H].highestVert=K.pitches[l-1].verticalPos;if(this.stemdir==="up"||T==="up"){K.pitches[H].highestVert+=6}}if(K.startSlur){if(!K.pitches[H].startSlur){K.pitches[H].startSlur=[]}for(M=0;M<K.startSlur.length;M++){K.pitches[H].startSlur.push(K.startSlur[M])}}if(!Q&&K.endSlur){K.pitches[H].highestVert=K.pitches[l-1].verticalPos;if(this.stemdir==="up"||T==="up"){K.pitches[H].highestVert+=6}if(!K.pitches[H].endSlur){K.pitches[H].endSlur=[]}for(M=0;M<K.endSlur.length;M++){K.pitches[H].endSlur.push(K.endSlur[M])}}}if(!Q){o=this.printNoteHead(g,S,K.pitches[H],T,0,-this.roomtaken,A,U,C,1)}if(o){g.addHead(o)}this.roomtaken+=this.accidentalshiftx;this.roomtakenright=Math.max(this.roomtakenright,this.dotshiftx)}if(!d&&v<=-1){P=(T==="down")?K.minpitch-7:K.minpitch+1/3;if(P>6&&!this.stemdir){P=6}O=(T==="down")?K.maxpitch-1/3:K.maxpitch+7;if(O<6&&!this.stemdir){O=6}e=(T==="down"||g.heads.length===0)?0:g.heads[0].w;b=(T==="down")?1:-1;g.addExtra(new ABCJS.write.RelativeElement(null,e,0,P,{type:"stem",pitch2:O,linewidth:b}));this.minY=Math.min(P,this.minY);this.minY=Math.min(O,this.minY)}}if(K.lyric!==undefined){var J="";window.ABCJS.parse.each(K.lyric,function(c){J+=c.syllable+c.divider+"\n"});g.addRight(new ABCJS.write.RelativeElement(J,0,J.length*5,0,{type:"debugLow"}))}if(!Q&&K.gracenotes!==undefined){var u=3/5;var h=null;if(K.gracenotes.length>1){h=new ABCJS.write.BeamElem("grace",this.isBagpipes)}var R=[];for(M=K.gracenotes.length-1;M>=0;M--){this.roomtaken+=10;R[M]=this.roomtaken;if(K.gracenotes[M].accidental){this.roomtaken+=7}}for(M=0;M<K.gracenotes.length;M++){var t=K.gracenotes[M].verticalPos;A=(h)?null:this.chartable.uflags[(this.isBagpipes)?5:3];a=this.printNoteHead(g,"noteheads.quarter",K.gracenotes[M],"up",-R[M],-R[M],A,0,0,u);g.addExtra(a);if(K.gracenotes[M].acciaccatura){var z=K.gracenotes[M].verticalPos+7*u;var L=h?5:6;g.addRight(new ABCJS.write.RelativeElement("flags.ugrace",-R[M]+L,0,z,{scalex:u,scaley:u}))}if(h){var m={heads:[a],abcelem:{averagepitch:t,minpitch:t,maxpitch:t},duration:(this.isBagpipes)?1/32:1/16};h.add(m)}else{P=t+1/3*u;O=t+7*u;e=a.dx+a.w;b=-0.6;g.addExtra(new ABCJS.write.RelativeElement(null,e,0,P,{type:"stem",pitch2:O,linewidth:b}))}if(M===0&&!this.isBagpipes&&!(K.rest&&(K.rest.type==="spacer"||K.rest.type==="invisible"))){this.voice.addOther(new ABCJS.write.TieElem(a,o,false,true))}}if(h){this.voice.addOther(h)}}if(!Q&&K.decoration){var s=this.printDecoration(K.decoration,K.maxpitch,(o)?o.w:0,g,this.roomtaken,T,K.minpitch);if(s){g.klass="mark"}}if(K.barNumber){g.addChild(new ABCJS.write.RelativeElement(K.barNumber,-10,0,0,{type:"debug"}))}for(M=K.maxpitch;M>11;M--){if(M%2===0&&!K.rest){g.addChild(new ABCJS.write.RelativeElement(null,-2,this.glyphs.getSymbolWidth(S)+4,M,{type:"ledger"}))}}for(M=K.minpitch;M<1;M++){if(M%2===0&&!K.rest){g.addChild(new ABCJS.write.RelativeElement(null,-2,this.glyphs.getSymbolWidth(S)+4,M,{type:"ledger"}))}}for(M=0;M<q.length;M++){var B=this.glyphs.getSymbolWidth(S);if(T==="down"){B=-B}g.addChild(new ABCJS.write.RelativeElement(null,B-2,this.glyphs.getSymbolWidth(S)+4,q[M],{type:"ledger"}))}if(K.chord!==undefined){for(M=0;M<K.chord.length;M++){var G=0;var F=16;switch(K.chord[M].position){case"left":this.roomtaken+=7;G=-this.roomtaken;F=K.averagepitch;g.addExtra(new ABCJS.write.RelativeElement(K.chord[M].name,G,this.glyphs.getSymbolWidth(K.chord[M].name[0])+4,F,{type:"text"}));break;case"right":this.roomtakenright+=4;G=this.roomtakenright;F=K.averagepitch;g.addRight(new ABCJS.write.RelativeElement(K.chord[M].name,G,this.glyphs.getSymbolWidth(K.chord[M].name[0])+4,F,{type:"text"}));break;case"below":F=-3;g.addChild(new ABCJS.write.RelativeElement(K.chord[M].name,G,0,F,{type:"text"}));break;default:g.addChild(new ABCJS.write.RelativeElement(K.chord[M].name,G,0,F,{type:"text"}))}}}if(K.startTriplet){this.triplet=new ABCJS.write.TripletElem(K.startTriplet,o,null,true);if(!Q){this.voice.addOther(this.triplet)}}if(K.endTriplet&&this.triplet){this.triplet.anchor2=o;this.triplet=null}return g};ABCJS.write.Layout.prototype.printNoteHead=function(m,z,A,o,h,e,u,p,x,B){var k=A.verticalPos;var d;var v;this.accidentalshiftx=0;this.dotshiftx=0;if(z===undefined){m.addChild(new ABCJS.write.RelativeElement("pitch is undefined",0,0,0,{type:"debug"})) }else{if(z===""){d=new ABCJS.write.RelativeElement(null,0,0,k)}else{var n=h;if(A.printer_shift){var r=(A.printer_shift==="same")?1:0;n=(o==="down")?-this.glyphs.getSymbolWidth(z)*B+r:this.glyphs.getSymbolWidth(z)*B-r}d=new ABCJS.write.RelativeElement(z,n,this.glyphs.getSymbolWidth(z)*B,k,{scalex:B,scaley:B,extreme:((o==="down")?"below":"above")});if(u){var g=k+((o==="down")?-7:7)*B;if(B===1&&(o==="down")?(g>6):(g<6)){g=6}var q=(o==="down")?h:h+d.w-0.6;m.addRight(new ABCJS.write.RelativeElement(u,q,this.glyphs.getSymbolWidth(u)*B,g,{scalex:B,scaley:B}))}this.dotshiftx=d.w+x-2+5*p;for(;p>0;p--){var a=(1-Math.abs(k)%2);m.addRight(new ABCJS.write.RelativeElement("dots.dot",d.w+x-2+5*p,this.glyphs.getSymbolWidth("dots.dot"),k+a))}}}if(d){d.highestVert=A.highestVert}if(A.accidental){var b;switch(A.accidental){case"quartersharp":b="accidentals.halfsharp";break;case"dblsharp":b="accidentals.dblsharp";break;case"sharp":b="accidentals.sharp";break;case"quarterflat":b="accidentals.halfflat";break;case"flat":b="accidentals.flat";break;case"dblflat":b="accidentals.dblflat";break;case"natural":b="accidentals.nat"}var l=false;var w=e;for(var s=0;s<this.accidentalSlot.length;s++){if(k-this.accidentalSlot[s][0]>=6){this.accidentalSlot[s][0]=k;w=this.accidentalSlot[s][1];l=true;break}}if(l===false){w-=(this.glyphs.getSymbolWidth(b)*B+2);this.accidentalSlot.push([k,w]);this.accidentalshiftx=(this.glyphs.getSymbolWidth(b)*B+2)}m.addExtra(new ABCJS.write.RelativeElement(b,w,this.glyphs.getSymbolWidth(b),k,{scalex:B,scaley:B}))}if(A.endTie){if(this.ties[0]){this.ties[0].anchor2=d;this.ties=this.ties.slice(1,this.ties.length)}}if(A.startTie){var t=new ABCJS.write.TieElem(d,null,(this.stemdir==="down"||o==="down")&&this.stemdir!=="up",(this.stemdir==="down"||this.stemdir==="up"));this.ties[this.ties.length]=t;this.voice.addOther(t)}if(A.endSlur){for(v=0;v<A.endSlur.length;v++){var y=A.endSlur[v];var f;if(this.slurs[y]){f=this.slurs[y].anchor2=d;delete this.slurs[y]}else{f=new ABCJS.write.TieElem(null,d,o==="down",(this.stemdir==="up"||o==="down")&&this.stemdir!=="down",this.stemdir);this.voice.addOther(f)}if(this.startlimitelem){f.startlimitelem=this.startlimitelem}}}if(A.startSlur){for(v=0;v<A.startSlur.length;v++){var y=A.startSlur[v].label;var f=new ABCJS.write.TieElem(d,null,(this.stemdir==="down"||o==="down")&&this.stemdir!=="up",false);this.slurs[y]=f;this.voice.addOther(f)}}return d};ABCJS.write.Layout.prototype.printDecoration=function(l,k,t,n,a,r,f){var q;var u;var j;var x;var s=[];var y=(k>9)?k+3:12;var h;var o=false;var m=this.minY-4;var w;a=a||0;if(k===5){y=14}var g=false;for(w=0;w<l.length;w++){if(l[w]==="staccato"){h=(r==="down")?k+2:f-2;switch(h){case 2:case 4:case 6:case 8:case 10:if(r==="up"){h--}else{h++}break}if(k>9){y++}var c=t/2;if(this.glyphs.getSymbolAlign("scripts.staccato")!=="center"){c-=(this.glyphs.getSymbolWidth(q)/2)}n.addChild(new ABCJS.write.RelativeElement("scripts.staccato",c,this.glyphs.getSymbolWidth("scripts.staccato"),h))}if(l[w]==="slide"&&n.heads[0]){h=n.heads[0].pitch;var d=new ABCJS.write.RelativeElement("",-a-15,0,h-1);var b=new ABCJS.write.RelativeElement("",-a-5,0,h+1);n.addChild(d);n.addChild(b);this.voice.addOther(new ABCJS.write.TieElem(d,b,false))}}for(w=0;w<l.length;w++){o=false;switch(l[w]){case"trill":q="scripts.trill";break;case"roll":q="scripts.roll";break;case"irishroll":q="scripts.roll";break;case"marcato":q="scripts.umarcato";break;case"marcato2":q="scriopts.dmarcato";break;case"turn":q="scripts.turn";break;case"uppermordent":q="scripts.prall";break;case"mordent":case"lowermordent":q="scripts.mordent";break;case"staccato":case"slide":continue;case"downbow":q="scripts.downbow";break;case"upbow":q="scripts.upbow";break;case"fermata":q="scripts.ufermata";break;case"invertedfermata":o=true;q="scripts.dfermata";break;case"breath":q=",";break;case"accent":q="scripts.sforzato";break;case"tenuto":q="scripts.tenuto";break;case"coda":q="scripts.coda";break;case"segno":q="scripts.segno";break;case"/":u=["flags.ugrace",1];continue;case"//":u=["flags.ugrace",2];continue;case"///":u=["flags.ugrace",3];continue;case"////":u=["flags.ugrace",4];continue;case"p":case"mp":case"pp":case"ppp":case"pppp":case"f":case"ff":case"fff":case"ffff":case"sfz":case"mf":var v=new ABCJS.write.DynamicDecoration(n,l[w]);this.voice.addOther(v);continue;case"mark":g=true;continue;case"diminuendo(":ABCJS.write.Layout.prototype.startDiminuendoX=n;j=undefined;continue;case"diminuendo)":j={start:ABCJS.write.Layout.prototype.startDiminuendoX,stop:n};ABCJS.write.Layout.prototype.startDiminuendoX=undefined;continue;case"crescendo(":ABCJS.write.Layout.prototype.startCrescendoX=n;x=undefined;continue;case"crescendo)":x={start:ABCJS.write.Layout.prototype.startCrescendoX,stop:n};ABCJS.write.Layout.prototype.startCrescendoX=undefined;continue;default:s[s.length]=l[w];continue}if(o){h=m;m-=4}else{h=y;y+=3}var c=t/2;if(this.glyphs.getSymbolAlign(q)!=="center"){c-=(this.glyphs.getSymbolWidth(q)/2)}n.addChild(new ABCJS.write.RelativeElement(q,c,this.glyphs.getSymbolWidth(q),h))}if(u){h=(r)?k+1:k+9;c=t/2;c+=(r)?-5:3;for(var e=0;e<u[1];e++){h-=1;n.addChild(new ABCJS.write.RelativeElement(u[0],c,this.glyphs.getSymbolWidth(u[0]),h))}}if(j){var p=new ABCJS.write.CrescendoElem(j.start,j.stop,">");this.voice.addOther(p)}if(x){var z=new ABCJS.write.CrescendoElem(x.start,x.stop,"<");this.voice.addOther(z)}if(s.length>0){n.addChild(new ABCJS.write.RelativeElement(s.join(","),0,0,0,{type:"debug"}))}return g};ABCJS.write.Layout.prototype.printBarLine=function(c){var i=new ABCJS.write.AbsoluteElement(c,0,10);var d=null;var j=0;var a=(c.type==="bar_right_repeat"||c.type==="bar_dbl_repeat");var e=(c.type!=="bar_left_repeat"&&c.type!=="bar_thick_thin"&&c.type!=="bar_invisible");var f=(c.type==="bar_right_repeat"||c.type==="bar_dbl_repeat"||c.type==="bar_left_repeat"||c.type==="bar_thin_thick"||c.type==="bar_thick_thin");var g=(c.type==="bar_left_repeat"||c.type==="bar_thick_thin"||c.type==="bar_thin_thin"||c.type==="bar_dbl_repeat");var b=(c.type==="bar_left_repeat"||c.type==="bar_dbl_repeat");if(a||b){for(var h in this.slurs){if(this.slurs.hasOwnProperty(h)){this.slurs[h].endlimitelem=i}}this.startlimitelem=i}if(a){i.addRight(new ABCJS.write.RelativeElement("dots.dot",j,1,7));i.addRight(new ABCJS.write.RelativeElement("dots.dot",j,1,5));j+=6}if(e){d=new ABCJS.write.RelativeElement(null,j,1,2,{type:"bar",pitch2:10,linewidth:0.6});i.addRight(d)}if(c.type==="bar_invisible"){d=new ABCJS.write.RelativeElement(null,j,1,2,{type:"none",pitch2:10,linewidth:0.6});i.addRight(d)}if(c.decoration){this.printDecoration(c.decoration,12,(f)?3:1,i,0,"down",2)}if(f){j+=4;d=new ABCJS.write.RelativeElement(null,j,4,2,{type:"bar",pitch2:10,linewidth:4});i.addRight(d);j+=5}if(this.partstartelem&&c.endEnding){this.partstartelem.anchor2=d;this.partstartelem=null}if(g){j+=3;d=new ABCJS.write.RelativeElement(null,j,1,2,{type:"bar",pitch2:10,linewidth:0.6});i.addRight(d)}if(b){j+=3;i.addRight(new ABCJS.write.RelativeElement("dots.dot",j,1,7)); i.addRight(new ABCJS.write.RelativeElement("dots.dot",j,1,5))}if(c.startEnding){this.partstartelem=new ABCJS.write.EndingElem(c.startEnding,d,null);this.voice.addOther(this.partstartelem)}return i};ABCJS.write.Layout.prototype.printClef=function(e){var g="clefs.G";var c=0;var f=4;var d=new ABCJS.write.AbsoluteElement(e,0,10);switch(e.type){case"treble":break;case"tenor":g="clefs.C";f=8;break;case"alto":g="clefs.C";f=6;break;case"bass":g="clefs.F";f=8;break;case"treble+8":c=1;break;case"tenor+8":g="clefs.C";f=8;break;case"bass+8":g="clefs.F";f=8;break;case"alto+8":g="clefs.C";f=6;break;case"treble-8":c=-1;break;case"tenor-8":g="clefs.C";f=8;break;case"bass-8":g="clefs.F";f=8;break;case"alto-8":g="clefs.C";f=6;break;case"none":g="";break;case"perc":g="clefs.perc";f=6;break;default:d.addChild(new ABCJS.write.RelativeElement("clef="+e.type,0,0,0,{type:"debug"}))}if(e.verticalPos){f=e.verticalPos}var b=10;if(g!==""){d.addRight(new ABCJS.write.RelativeElement(g,b,this.glyphs.getSymbolWidth(g),f))}if(c!==0){var h=2/3;var a=(this.glyphs.getSymbolWidth(g)-this.glyphs.getSymbolWidth("8")*h)/2;d.addRight(new ABCJS.write.RelativeElement("8",b+a,this.glyphs.getSymbolWidth("8")*h,(c>0)?16:-2,{scalex:h,scaley:h}))}if(e.stafflines===0){this.stafflines=0}else{this.stafflines=e.stafflines}return d};ABCJS.write.Layout.prototype.printKeySignature=function(c){var b=new ABCJS.write.AbsoluteElement(c,0,10);var a=0;if(c.accidentals){window.ABCJS.parse.each(c.accidentals,function(e){var d=(e.acc==="sharp")?"accidentals.sharp":(e.acc==="natural")?"accidentals.nat":"accidentals.flat";b.addRight(new ABCJS.write.RelativeElement(d,a,this.glyphs.getSymbolWidth(d),e.verticalPos));a+=this.glyphs.getSymbolWidth(d)+2},this)}this.startlimitelem=b;return b};ABCJS.write.Layout.prototype.printTimeSignature=function(c){var b=new ABCJS.write.AbsoluteElement(c,0,20);if(c.type==="specified"){for(var a=0;a<c.value.length;a++){if(a!==0){b.addRight(new ABCJS.write.RelativeElement("+",a*20-9,this.glyphs.getSymbolWidth("+"),7))}if(c.value[a].den){b.addRight(new ABCJS.write.RelativeElement(c.value[a].num,a*20,this.glyphs.getSymbolWidth(c.value[a].num.charAt(0))*c.value[a].num.length,9));b.addRight(new ABCJS.write.RelativeElement(c.value[a].den,a*20,this.glyphs.getSymbolWidth(c.value[a].den.charAt(0))*c.value[a].den.length,5))}else{b.addRight(new ABCJS.write.RelativeElement(c.value[a].num,a*20,this.glyphs.getSymbolWidth(c.value[a].num.charAt(0))*c.value[a].num.length,7))}}}else{if(c.type==="common_time"){b.addRight(new ABCJS.write.RelativeElement("timesig.common",0,this.glyphs.getSymbolWidth("timesig.common"),7))}else{if(c.type==="cut_time"){b.addRight(new ABCJS.write.RelativeElement("timesig.cut",0,this.glyphs.getSymbolWidth("timesig.cut"),7))}}}this.startlimitelem=b;return b};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.write){window.ABCJS.write={}}ABCJS.write.spacing=function(){};ABCJS.write.spacing.FONTEM=360;ABCJS.write.spacing.FONTSIZE=30;ABCJS.write.spacing.STEP=ABCJS.write.spacing.FONTSIZE*93/720;ABCJS.write.spacing.SPACE=10;ABCJS.write.spacing.TOPNOTE=20;ABCJS.write.spacing.STAVEHEIGHT=100;ABCJS.write.Printer=function(b,a){a=a||{};this.y=0;this.paper=b;this.space=3*ABCJS.write.spacing.SPACE;this.glyphs=new ABCJS.write.Glyphs();this.listeners=[];this.selected=[];this.ingroup=false;this.scale=a.scale||1;this.staffwidth=a.staffwidth||740;this.paddingtop=a.paddingtop||15;this.paddingbottom=a.paddingbottom||30;this.paddingright=a.paddingright||50;this.paddingleft=a.paddingleft||15;this.editable=a.editable||false};ABCJS.write.Printer.prototype.notifySelect=function(b){this.clearSelection();this.selected=[b];b.highlight();for(var a=0;a<this.listeners.length;a++){this.listeners[a].highlight(b.abcelem)}};ABCJS.write.Printer.prototype.notifyChange=function(b){for(var a=0;a<this.listeners.length;a++){this.listeners[a].modelChanged()}};ABCJS.write.Printer.prototype.clearSelection=function(){for(var a=0;a<this.selected.length;a++){this.selected[a].unhighlight()}this.selected=[]};ABCJS.write.Printer.prototype.addSelectListener=function(a){this.listeners[this.listeners.length]=a};ABCJS.write.Printer.prototype.rangeHighlight=function(b,d){this.clearSelection();for(var i=0;i<this.staffgroups.length;i++){var f=this.staffgroups[i].voices;for(var g=0;g<f.length;g++){var a=f[g].children;for(var c=0;c<a.length;c++){var h=a[c].abcelem.startChar;var e=a[c].abcelem.endChar;if((d>h&&b<e)||((d===b)&&d===e)){this.selected[this.selected.length]=a[c];a[c].highlight()}}}}};ABCJS.write.Printer.prototype.beginGroup=function(){this.path=[];this.lastM=[0,0];this.ingroup=true};ABCJS.write.Printer.prototype.addPath=function(c){c=c||[];if(c.length===0){return}c[0][0]="m";c[0][1]-=this.lastM[0];c[0][2]-=this.lastM[1];this.lastM[0]+=c[0][1];this.lastM[1]+=c[0][2];this.path.push(c[0]);for(var a=1,b=c.length;a<b;a++){if(c[a][0]==="m"){this.lastM[0]+=c[a][1];this.lastM[1]+=c[a][2]}this.path.push(c[a])}};ABCJS.write.Printer.prototype.endGroup=function(){this.ingroup=false;if(this.path.length===0){return null}var a=this.paper.path().attr({path:this.path,stroke:"none",fill:"#000000"});if(this.scale!==1){a.scale(this.scale,this.scale,0,0)}return a};ABCJS.write.Printer.prototype.printStaveLine=function(x1,x2,pitch){var isIE= /*@cc_on!@*/ false;var dy=0.35;var fill="#000000";if(isIE){dy=1;fill="#666666"}var y=this.calcY(pitch);var pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x1,y-dy,x2,y-dy,x2,y+dy,x1,y+dy);var ret=this.paper.path().attr({path:pathString,stroke:"none",fill:fill}).toBack();if(this.scale!==1){ret.scale(this.scale,this.scale,0,0)}return ret};ABCJS.write.Printer.prototype.printStem=function(x,dx,y1,y2){if(dx<0){var tmp=y2;y2=y1;y1=tmp}var isIE= /*@cc_on!@*/ false;var fill="#000000";if(isIE&&dx<1){dx=1;fill="#666666"}if(~~x===x){x+=0.05}var pathArray=[["M",x,y1],["L",x,y2],["L",x+dx,y2],["L",x+dx,y1],["z"]];if(!isIE&&this.ingroup){this.addPath(pathArray)}else{var ret=this.paper.path().attr({path:pathArray,stroke:"none",fill:fill}).toBack();if(this.scale!==1){ret.scale(this.scale,this.scale,0,0)}return ret}};ABCJS.write.Printer.prototype.printText=function(a,e,d,c){c=c||"start";var b=this.paper.text(a,this.calcY(e),d).attr({"text-anchor":c,"font-size":12});if(this.scale!==1){b.scale(this.scale,this.scale,0,0)}return b};ABCJS.write.Printer.prototype.printSymbol=function(j,d,c,g,f){var b;if(!c){return null}if(c.length>0&&c.indexOf(".")<0){var h=this.paper.set();var k=0;for(var e=0;e<c.length;e++){var a=this.glyphs.getYCorr(c.charAt(e));b=this.glyphs.printSymbol(j+k,this.calcY(d+a),c.charAt(e),this.paper);if(b){h.push(b);k+=this.glyphs.getSymbolWidth(c.charAt(e))}else{this.debugMsg(j,"no symbol:"+c)}}if(this.scale!==1){h.scale(this.scale,this.scale,0,0)}return h}else{var a=this.glyphs.getYCorr(c);if(this.ingroup){this.addPath(this.glyphs.getPathForSymbol(j,this.calcY(d+a),c,g,f))}else{b=this.glyphs.printSymbol(j,this.calcY(d+a),c,this.paper);if(b){if(this.scale!==1){b.scale(this.scale,this.scale,0,0)}return b}else{this.debugMsg(j,"no symbol:"+c) }}return null}};ABCJS.write.Printer.prototype.printPath=function(b){var a=this.paper.path().attr(b);if(this.scale!==1){a.scale(this.scale,this.scale,0,0)}return a};ABCJS.write.Printer.prototype.drawArc=function(n,m,q,p,o){n=n+6;m=m+4;q=q+((o)?1.5:-1.5);p=p+((o)?1.5:-1.5);var c=this.calcY(q);var b=this.calcY(p);var h=m-n;var g=b-c;var f=Math.sqrt(h*h+g*g);var e=h/f;var d=g/f;var u=f/3.5;var i=((o)?-1:1)*Math.min(25,Math.max(4,u));var l=n+u*e-i*d;var t=c+u*d+i*e;var j=m-u*e-i*d;var r=b-u*d+i*e;var a=2;var k=ABCJS.write.sprintf("M %f %f C %f %f %f %f %f %f C %f %f %f %f %f %f z",n,c,l,t,j,r,m,b,j-a*d,r+a*e,l-a*d,t+a*e,n,c);var s=this.paper.path().attr({path:k,stroke:"none",fill:"#000000"});if(this.scale!==1){s.scale(this.scale,this.scale,0,0)}return s};ABCJS.write.Printer.prototype.debugMsg=function(a,b){return this.paper.text(a,this.y,b).scale(this.scale,this.scale,0,0)};ABCJS.write.Printer.prototype.debugMsgLow=function(a,b){return this.paper.text(a,this.calcY(this.layouter.minY-7),b).attr({"font-family":"serif","font-size":12,"text-anchor":"begin"}).scale(this.scale,this.scale,0,0)};ABCJS.write.Printer.prototype.printLyrics=function(a,c){var b=this.paper.text(a,this.calcY(this.layouter.minY-7),c).attr({"font-family":"Times New Roman","font-weight":"bold","font-size":14,"text-anchor":"begin"}).scale(this.scale,this.scale,0,0);b[0].setAttribute("class","abc-lyric");return b};ABCJS.write.Printer.prototype.calcY=function(a){return this.y+((ABCJS.write.spacing.TOPNOTE-a)*ABCJS.write.spacing.STEP)};ABCJS.write.Printer.prototype.printStave=function(a,d,b){if(b===1){this.printStaveLine(a,d,6);return}for(var c=0;c<b;c++){this.printStaveLine(a,d,(c+1)*2)}};ABCJS.write.Printer.prototype.printABC=function(a){if(a[0]===undefined){a=[a]}this.y=0;for(var b=0;b<a.length;b++){this.printTune(a[b])}};ABCJS.write.Printer.prototype.printTempo=function(s,j,p,g,e,i){if(s.preString){var n=j.text(i,g+20,s.preString).attr({"text-anchor":"start"});i+=(n.getBBox().width+10)}if(s.duration){var f=0.75;var u=14.5;var a=s.duration[0];var m=new ABCJS.write.AbsoluteElement(s,a,1);var t=Math.floor(Math.log(a)/Math.log(2));var q=0;for(var l=Math.pow(2,t),h=l/2;l<a;q++,l+=h,h/=2){}var w=p.chartable.note[-t];var v=p.chartable.uflags[-t];var o=p.printNoteHead(m,w,{verticalPos:u},"up",0,0,v,q,0,f);m.addHead(o);if(a<1){var d=u+1/3*f;var b=u+7*f;var k=o.dx+o.w;var r=-0.6;m.addExtra(new ABCJS.write.RelativeElement(null,k,0,d,{type:"stem",pitch2:b,linewidth:r}))}m.x=i;m.draw(e,null);i+=(m.w+5);n=j.text(i,g+20,"= "+s.bpm).attr({"text-anchor":"start"});i+=n.getBBox().width+10}if(s.postString){j.text(i,g+20,s.postString).attr({"text-anchor":"start"})}g+=15;return g};ABCJS.write.Printer.prototype.printTune=function(abctune){this.layouter=new ABCJS.write.Layout(this.glyphs,abctune.formatting.bagpipes);this.layouter.printer=this;if(abctune.media==="print"){var m=abctune.formatting.topmargin===undefined?54:abctune.formatting.topmargin;this.y+=m}else{this.y+=this.paddingtop}if(abctune.formatting.staffwidth){this.width=abctune.formatting.staffwidth}else{this.width=this.staffwidth}this.width+=this.paddingleft;if(abctune.formatting.scale){this.scale=abctune.formatting.scale}this.paper.text(this.width/2,this.y,abctune.metaText.title).attr({"font-size":20,"font-family":"serif"});this.y+=20;if(abctune.lines[0]&&abctune.lines[0].subtitle){this.printSubtitleLine(abctune.lines[0]);this.y+=20}if(abctune.metaText.rhythm){this.paper.text(this.paddingleft,this.y,abctune.metaText.rhythm).attr({"text-anchor":"start","font-style":"italic","font-family":"serif","font-size":12});!(abctune.metaText.author||abctune.metaText.origin||abctune.metaText.composer)&&(this.y+=15)}if(abctune.metaText.author){this.paper.text(this.width,this.y,abctune.metaText.author).attr({"text-anchor":"end","font-style":"italic","font-family":"serif","font-size":12});this.y+=15}if(abctune.metaText.origin){this.paper.text(this.width,this.y,"("+abctune.metaText.origin+")").attr({"text-anchor":"end","font-style":"italic","font-family":"serif","font-size":12});this.y+=15}if(abctune.metaText.composer){this.paper.text(this.width,this.y,abctune.metaText.composer).attr({"text-anchor":"end","font-style":"italic","font-family":"serif","font-size":12});this.y+=15}if(abctune.metaText.tempo&&!abctune.metaText.tempo.suppress){this.y=this.printTempo(abctune.metaText.tempo,this.paper,this.layouter,this.y,this,50)}this.staffgroups=[];var maxwidth=this.width;for(var line=0;line<abctune.lines.length;line++){var abcline=abctune.lines[line];if(abcline.staff){var staffgroup=this.layouter.printABCLine(abcline.staff);var newspace=this.space;for(var it=0;it<3;it++){staffgroup.layout(newspace,this);if(line&&line===abctune.lines.length-1&&staffgroup.w/this.width<0.66&&!abctune.formatting.stretchlast){break}var relspace=staffgroup.spacingunits*newspace;var constspace=staffgroup.w-relspace;if(staffgroup.spacingunits>0){newspace=(this.width-constspace)/staffgroup.spacingunits;if(newspace*staffgroup.minspace>50){newspace=50/staffgroup.minspace}}}staffgroup.draw(this,this.y);if(staffgroup.w>maxwidth){maxwidth=staffgroup.w}this.staffgroups[this.staffgroups.length]=staffgroup;this.y=staffgroup.y+staffgroup.height;this.y+=ABCJS.write.spacing.STAVEHEIGHT*0.2}else{if(abcline.subtitle&&line!==0){this.printSubtitleLine(abcline);this.y+=20}else{if(abcline.text){if(typeof abcline.text==="string"){this.paper.text(100,this.y,"TEXT: "+abcline.text)}else{var str="";for(var i=0;i<abcline.text.length;i++){str+=" FONT "+abcline.text[i].text}this.paper.text(100,this.y,"TEXT: "+str)}this.y+=20}}}}var extraText="";if(abctune.metaText.partOrder){extraText+="Part Order: "+abctune.metaText.partOrder+"\n"}if(abctune.metaText.notes){extraText+="Notes:\n"+abctune.metaText.notes+"\n"}if(abctune.metaText.book){extraText+="Book: "+abctune.metaText.book+"\n"}if(abctune.metaText.source){extraText+="Source: "+abctune.metaText.source+"\n"}if(abctune.metaText.transcription){extraText+="Transcription: "+abctune.metaText.transcription+"\n"}if(abctune.metaText.discography){extraText+="Discography: "+abctune.metaText.discography+"\n"}if(abctune.metaText.history){extraText+="History: "+abctune.metaText.history+"\n"}if(abctune.metaText.unalignedWords){extraText+="Words:\n";for(var j=0;j<abctune.metaText.unalignedWords.length;j++){if(typeof abctune.metaText.unalignedWords[j]==="string"){extraText+=abctune.metaText.unalignedWords[j]+"\n"}else{for(var k=0;k<abctune.metaText.unalignedWords[j].length;k++){extraText+=" FONT "+abctune.metaText.unalignedWords[j][k].text}extraText+="\n"}}}var text2=this.paper.text(this.paddingleft,this.y+25,extraText).attr({"text-anchor":"start","font-family":"serif","font-size":13});var height=text2.getBBox().height;text2.translate(0,height/2);this.y+=25+height;var sizetoset={w:maxwidth*this.scale+this.paddingright,h:this.y*this.scale+this.paddingbottom};this.paper.setSize(sizetoset.w,sizetoset.h);var isIE= /*@cc_on!@*/ false;if(isIE){this.paper.canvas.parentNode.style.width=sizetoset.w+"px";this.paper.canvas.parentNode.style.height=""+sizetoset.h+"px" }else{this.paper.canvas.parentNode.setAttribute("style","width:"+sizetoset.w+"px")}};ABCJS.write.Printer.prototype.printSubtitleLine=function(a){this.paper.text(this.width/2,this.y,a.subtitle).attr({"font-size":16}).scale(this.scale,this.scale,0,0)};if(!window.ABCJS){window.ABCJS={}}if(!window.ABCJS.write){window.ABCJS.write={}}ABCJS.write.sprintf=function(){var g=0,e,h=arguments[g++],k=[],d,j,l,b;while(h){if(d=/^[^\x25]+/.exec(h)){k.push(d[0])}else{if(d=/^\x25{2}/.exec(h)){k.push("%")}else{if(d=/^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(h)){if(((e=arguments[d[1]||g++])==null)||(e==undefined)){throw ("Too few arguments.")}if(/[^s]/.test(d[7])&&(typeof(e)!="number")){throw ("Expecting number but found "+typeof(e))}switch(d[7]){case"b":e=e.toString(2);break;case"c":e=String.fromCharCode(e);break;case"d":e=parseInt(e);break;case"e":e=d[6]?e.toExponential(d[6]):e.toExponential();break;case"f":e=d[6]?parseFloat(e).toFixed(d[6]):parseFloat(e);break;case"o":e=e.toString(8);break;case"s":e=((e=String(e))&&d[6]?e.substring(0,d[6]):e);break;case"u":e=Math.abs(e);break;case"x":e=e.toString(16);break;case"X":e=e.toString(16).toUpperCase();break}e=(/[def]/.test(d[7])&&d[2]&&e>0?"+"+e:e);l=d[3]?d[3]=="0"?"0":d[3].charAt(1):" ";b=d[5]-String(e).length;j=d[5]?str_repeat(l,b):"";k.push(d[4]?e+j:j+e)}else{throw ("Huh ?!")}}}h=h.substring(d[0].length)}return k.join("")};if(!window.ABCJS){window.ABCJS={}}window.ABCJS.Plugin=function(){var b=false;try{b=abcjs_is_user_script}catch(a){}this.show_midi=!b||this.$.browser.mozilla;this.hide_abc=false;this.render_before=false;this.midi_options={};this.render_options={};this.render_classname="abcrendered";this.text_classname="abctext";this.auto_render_threshold=20;this.show_text="show score for: "};window.ABCJS.Plugin.prototype.start=function(e){this.$=e;var a=e("body");this.errors="";var c=this.getABCContainingElements(this.$("body"));var b=this;var d=c.map(function(f,g){return b.convertToDivs(g)});this.auto_render=(d.size()<=this.auto_render_threshold);d.each(function(f,g){b.render(g,b.$(g).data("abctext"))})};window.ABCJS.Plugin.prototype.getABCContainingElements=function(d){var b=this.$();var c=false;var a=this;this.$(d).contents().each(function(){if(this.nodeType==3&&!c){if(this.nodeValue.match(/^\s*X:/m)){if(this.parentNode.tagName.toLowerCase()!=="textarea"){b=b.add(a.$(d));c=true}}}else{if(this.nodeType==1&&!a.$(this).is("textarea")){b=b.add(a.getABCContainingElements(this))}}});return b};window.ABCJS.Plugin.prototype.convertToDivs=function(e){var b=this;var d=this.$(e).contents();var a="";var h=null;var g=false;var f=0;var c=this.$();d.each(function(j,k){if(k.nodeType==3&&!k.nodeValue.match(/^\s*$/)){f=0;var l=k.nodeValue;if(l.match(/^\s*X:/m)){g=true;a="";h=b.$("<div class='"+b.text_classname+"'></div>");b.$(k).before(h);if(b.hide_abc){h.hide()}}if(g){a+=l.replace(/\n+/,"");h.append(b.$(k))}}else{if(g&&b.$(k).is("br")){a+="\n";h.append(b.$(k));f++}else{if(g&&k.nodeType===1){a+="\n";h.append(b.$(k))}else{if(g){g=false;f=0;a=a.replace(/\n+/,"\n");h.data("abctext",a);c=c.add(h)}}}}});if(g){a=a.replace(/\n+$/,"\n").replace(/^\n+/,"\n");h.data("abctext",a);c=c.add(h)}return c.get()};window.ABCJS.Plugin.prototype.render=function(c,k){var h=this.$("<div class='"+this.render_classname+"'></div>");if(this.render_before){this.$(c).before(h)}else{this.$(c).after(h)}var l=this;try{var a=new ABCJS.TuneBook(k);var f=new ABCJS.parse.Parse();f.parse(a.tunes[0].abc);var i=f.getTune();var b=function(){try{var o=Raphael(h.get(0),800,400);var m=new ABCJS.write.Printer(o,l.render_options);m.printABC(i)}catch(e){h.remove();h=this.$("<div class='"+l.render_classname+"'></div>");o=Raphael(h.get(0),800,400);m=new ABCJS.write.Printer(o);m.printABC(i);if(l.render_before){this.$(c).before(h)}else{this.$(c).after(h)}}if(ABCJS.MidiWriter&&l.show_midi){var n=new ABCJS.midi.MidiWriter(h.get(0),l.midi_options);n.writeABC(i)}};var g="<a class='abcshow' href='#'>"+this.show_text+(i.metaText.title||"untitled")+"</a>";if(this.auto_render){b()}else{var d=this.$(g);d.click(function(){b();d.hide();return false});h.before(d)}}catch(j){this.errors+=j}};window.ABCJS.plugin=new window.ABCJS.Plugin();$(document).ready(function(){var b=true;try{b=abcjs_plugin_autostart}catch(a){}if(b){jQuery(document).ready(ABCJS.plugin.start(jQuery))}})();
information/blendle-frontend-react-source/app/modules/premiumSignup/containers/Publications.js
BramscoChill/BlendleParser
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import AltContainer from 'alt-container'; import { get } from 'lodash'; import Analytics from 'instances/analytics'; import { track } from 'helpers/premiumOnboardingEvents'; import SignUpActions from 'actions/SignUpActions'; import FavoriteProvidersActions from 'actions/FavoriteProvidersActions'; import SignUpStore from 'stores/SignUpStore'; import FavoriteProvidersStore from 'stores/FavoriteProvidersStore'; import AuthStore from 'stores/AuthStore'; import AuthActions from 'actions/AuthActions'; import Publications from 'modules/premiumSignup/components/Publications'; import ChannelsStore from 'stores/ChannelsStore'; function formatPublications(publications) { return publications .filter(issue => issue._links.page_preview || issue._links.cover_image) .map((issue) => { const image = issue._links.page_preview || issue._links.cover_image; return { issue, image, key: issue.provider.id, width: image.width, height: image.height, }; }); } class PublicationsContainer extends Component { static propTypes = { params: PropTypes.object, route: PropTypes.object, isOnboarding: PropTypes.bool, location: PropTypes.object, }; componentDidMount() { SignUpActions.fetchPublicationsByChannelPreferences(ChannelsStore.getState().selectedChannels); FavoriteProvidersActions.fetchFavoriteProviders(AuthStore.getState().user.id); // Update user again to make sure we have the active subscriptions, which we use to determine // the href prop of the footer button AuthActions.update(AuthStore.getState().user); } componentWillUnmount() { const favoriteProviders = FavoriteProvidersStore.getState().favorites; track(Analytics, 'Signup/Publications Selected', { provider_uids: favoriteProviders }); } _renderPublications(signUpState) { const isDeeplinkSignup = !!get(this.props, 'params.itemId', null); return ( <Publications imageList={formatPublications(signUpState.publications)} selected={signUpState.favorites} isDeeplinkSignUp={isDeeplinkSignup} isOnboarding={this.props.isOnboarding} /> ); } render() { return <AltContainer store={SignUpStore} render={this._renderPublications.bind(this)} />; } } export default PublicationsContainer; // WEBPACK FOOTER // // ./src/js/app/modules/premiumSignup/containers/Publications.js
ajax/libs/material-ui/4.9.2/esm/FilledInput/FilledInput.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import InputBase from '../InputBase'; import withStyles from '../styles/withStyles'; export var styles = function styles(theme) { var light = theme.palette.type === 'light'; var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)'; var backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'; return { /* Styles applied to the root element. */ root: { position: 'relative', backgroundColor: backgroundColor, borderTopLeftRadius: theme.shape.borderRadius, borderTopRightRadius: theme.shape.borderRadius, transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), '&:hover': { backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)', // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: backgroundColor } }, '&$focused': { backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)' }, '&$disabled': { backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)' } }, /* Styles applied to the root element if color secondary. */ colorSecondary: { '&$underline:after': { borderBottomColor: theme.palette.secondary.main } }, /* Styles applied to the root element if `disableUnderline={false}`. */ underline: { '&:after': { borderBottom: "2px solid ".concat(theme.palette.primary.main), left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), pointerEvents: 'none' // Transparent to the hover style. }, '&$focused:after': { transform: 'scaleX(1)' }, '&$error:after': { borderBottomColor: theme.palette.error.main, transform: 'scaleX(1)' // error is always underlined in red }, '&:before': { borderBottom: "1px solid ".concat(bottomLineColor), left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '"\\00a0"', position: 'absolute', right: 0, transition: theme.transitions.create('border-bottom-color', { duration: theme.transitions.duration.shorter }), pointerEvents: 'none' // Transparent to the hover style. }, '&:hover:before': { borderBottom: "1px solid ".concat(theme.palette.text.primary) }, '&$disabled:before': { borderBottomStyle: 'dotted' } }, /* Pseudo-class applied to the root element if the component is focused. */ focused: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `startAdornment` is provided. */ adornedStart: { paddingLeft: 12 }, /* Styles applied to the root element if `endAdornment` is provided. */ adornedEnd: { paddingRight: 12 }, /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Styles applied to the `input` element if `margin="dense"`. */ marginDense: {}, /* Styles applied to the root element if `multiline={true}`. */ multiline: { padding: '27px 12px 10px', '&$marginDense': { paddingTop: 23, paddingBottom: 6 } }, /* Styles applied to the `input` element. */ input: { padding: '27px 12px 10px', '&:-webkit-autofill': { WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null, WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null, borderTopLeftRadius: 'inherit', borderTopRightRadius: 'inherit' } }, /* Styles applied to the `input` element if `margin="dense"`. */ inputMarginDense: { paddingTop: 23, paddingBottom: 6 }, /* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */ inputHiddenLabel: { paddingTop: 18, paddingBottom: 19, '&$inputMarginDense': { paddingTop: 10, paddingBottom: 11 } }, /* Styles applied to the `input` element if `multiline={true}`. */ inputMultiline: { padding: 0 }, /* Styles applied to the `input` element if `startAdornment` is provided. */ inputAdornedStart: { paddingLeft: 0 }, /* Styles applied to the `input` element if `endAdornment` is provided. */ inputAdornedEnd: { paddingRight: 0 } }; }; var FilledInput = React.forwardRef(function FilledInput(props, ref) { var disableUnderline = props.disableUnderline, classes = props.classes, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$inputComponent = props.inputComponent, inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent, _props$multiline = props.multiline, multiline = _props$multiline === void 0 ? false : _props$multiline, _props$type = props.type, type = _props$type === void 0 ? 'text' : _props$type, other = _objectWithoutProperties(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]); return React.createElement(InputBase, _extends({ classes: _extends({}, classes, { root: clsx(classes.root, !disableUnderline && classes.underline), underline: null }), fullWidth: fullWidth, inputComponent: inputComponent, multiline: multiline, ref: ref, type: type }, other)); }); process.env.NODE_ENV !== "production" ? FilledInput.propTypes = { /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element will be focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the wrapper element. */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary']), /** * The default `input` element value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the `input` element will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the input will indicate an error. This is normally obtained via context from * FormControl. */ error: PropTypes.bool, /** * If `true`, the input will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the native input. * Either a string to use a DOM element or a component. */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense', 'none']), /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the value is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the input before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element will be required. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maximum number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any } : void 0; FilledInput.muiName = 'Input'; export default withStyles(styles, { name: 'MuiFilledInput' })(FilledInput);
blueocean-material-icons/src/js/components/svg-icons/editor/show-chart.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const EditorShowChart = (props) => ( <SvgIcon {...props}> <path d="M3.5 18.49l6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z"/> </SvgIcon> ); EditorShowChart.displayName = 'EditorShowChart'; EditorShowChart.muiName = 'SvgIcon'; export default EditorShowChart;
node_modules/babel-preset-react-hmre/test/Test.js
kaizensauce/campari-app
import React from 'react' export default class Test extends React.Component { render() { return ( <div>Winning?</div> ) } }
Examples/TicTacToe/TicTacToeApp.js
slongwang/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * 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 NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK 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. * * @providesModule TicTacToeApp * @flow */ 'use strict'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, TouchableHighlight, View, } = React; class Board { grid: Array<Array<number>>; turn: number; constructor() { var size = 3; var grid = Array(size); for (var i = 0; i < size; i++) { var row = Array(size); for (var j = 0; j < size; j++) { row[j] = 0; } grid[i] = row; } this.grid = grid; this.turn = 1; } mark(row: number, col: number, player: number): Board { this.grid[row][col] = player; return this; } hasMark(row: number, col: number): boolean { return this.grid[row][col] !== 0; } winner(): ?number { for (var i = 0; i < 3; i++) { if (this.grid[i][0] !== 0 && this.grid[i][0] === this.grid[i][1] && this.grid[i][0] === this.grid[i][2]) { return this.grid[i][0]; } } for (var i = 0; i < 3; i++) { if (this.grid[0][i] !== 0 && this.grid[0][i] === this.grid[1][i] && this.grid[0][i] === this.grid[2][i]) { return this.grid[0][i]; } } if (this.grid[0][0] !== 0 && this.grid[0][0] === this.grid[1][1] && this.grid[0][0] === this.grid[2][2]) { return this.grid[0][0]; } if (this.grid[0][2] !== 0 && this.grid[0][2] === this.grid[1][1] && this.grid[0][2] === this.grid[2][0]) { return this.grid[0][2]; } return null; } tie(): boolean { for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { if (this.grid[i][j] === 0) { return false; } } } return this.winner() === null; } } var Cell = React.createClass({ cellStyle() { switch (this.props.player) { case 1: return styles.cellX; case 2: return styles.cellO; default: return null; } }, textStyle() { switch (this.props.player) { case 1: return styles.cellTextX; case 2: return styles.cellTextO; default: return {}; } }, textContents() { switch (this.props.player) { case 1: return 'X'; case 2: return 'O'; default: return ''; } }, render() { return ( <TouchableHighlight onPress={this.props.onPress} underlayColor="transparent" activeOpacity={0.5}> <View style={[styles.cell, this.cellStyle()]}> <Text style={[styles.cellText, this.textStyle()]}> {this.textContents()} </Text> </View> </TouchableHighlight> ); } }); var GameEndOverlay = React.createClass({ render() { var board = this.props.board; var tie = board.tie(); var winner = board.winner(); if (!winner && !tie) { return <View />; } var message; if (tie) { message = 'It\'s a tie!'; } else { message = (winner === 1 ? 'X' : 'O') + ' wins!'; } return ( <View style={styles.overlay}> <Text style={styles.overlayMessage}>{message}</Text> <TouchableHighlight onPress={this.props.onRestart} underlayColor="transparent" activeOpacity={0.5}> <View style={styles.newGame}> <Text style={styles.newGameText}>New Game</Text> </View> </TouchableHighlight> </View> ); } }); var TicTacToeApp = React.createClass({ getInitialState() { return { board: new Board(), player: 1 }; }, restartGame() { this.setState(this.getInitialState()); }, nextPlayer(): number { return this.state.player === 1 ? 2 : 1; }, handleCellPress(row: number, col: number) { if (this.state.board.hasMark(row, col)) { return; } this.setState({ board: this.state.board.mark(row, col, this.state.player), player: this.nextPlayer(), }); }, render() { var rows = this.state.board.grid.map((cells, row) => <View key={'row' + row} style={styles.row}> {cells.map((player, col) => <Cell key={'cell' + col} player={player} onPress={this.handleCellPress.bind(this, row, col)} /> )} </View> ); return ( <View style={styles.container}> <Text style={styles.title}>EXTREME T3</Text> <View style={styles.board}> {rows} </View> <GameEndOverlay board={this.state.board} onRestart={this.restartGame} /> </View> ); } }); var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white' }, title: { fontFamily: 'Chalkduster', fontSize: 39, marginBottom: 20, }, board: { padding: 5, backgroundColor: '#47525d', borderRadius: 10, }, row: { flexDirection: 'row', }, // CELL cell: { width: 80, height: 80, borderRadius: 5, backgroundColor: '#7b8994', margin: 5, flex: 1, justifyContent: 'center', alignItems: 'center', }, cellX: { backgroundColor: '#72d0eb', }, cellO: { backgroundColor: '#7ebd26', }, // CELL TEXT cellText: { borderRadius: 5, fontSize: 50, fontFamily: 'AvenirNext-Bold', }, cellTextX: { color: '#19a9e5', }, cellTextO: { color: '#b9dc2f', }, // GAME OVER overlay: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, backgroundColor: 'rgba(221, 221, 221, 0.5)', flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, overlayMessage: { fontSize: 40, marginBottom: 20, marginLeft: 20, marginRight: 20, fontFamily: 'AvenirNext-DemiBold', textAlign: 'center', }, newGame: { backgroundColor: '#887766', padding: 20, borderRadius: 5, }, newGameText: { color: 'white', fontSize: 20, fontFamily: 'AvenirNext-DemiBold', }, }); AppRegistry.registerComponent('TicTacToeApp', () => TicTacToeApp); module.exports = TicTacToeApp;
ajax/libs/angular.js/0.9.16/angular-scenario.js
jdh8/cdnjs
/*! * 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( window, undefined ) { // 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 ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { 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 ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? 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] ) { 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 = buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); if ( elem ) { // 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: $("TAG") } else if ( !context && /^\w+$/.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // 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 jQuery( 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.4.2", // 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.slice(num)[ 0 ] : 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 = jQuery(); 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(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( 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 || jQuery(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() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // 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 object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // 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 ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 13 ); } // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); } // Reset the list of functions readyList = null; } // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { return jQuery.ready(); } // 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 toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, 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 || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwnProperty.call(obj, "constructor") && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwnProperty.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 ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, 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 ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, trim: function( text ) { return (text || "").replace( rtrim, "" ); }, // 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) if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( 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 = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { if ( !inv !== !callback( elems[ i ], i ) ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); 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; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // 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( error ) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } 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 || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function function access( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { 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; } function now() { return (new Date).getTime(); } (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.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 insted) style: /red/.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: div.getElementsByTagName("input")[0].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: document.createElement("select").appendChild( document.createElement("option") ).selected, parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null, // Will be defined later deleteExpando: true, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null }; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; document.body.removeChild( div ).style.display = 'none'; div = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, expando:expando, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, "object": true, "applet": true }, data: function( elem, name, data ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache; if ( !id && typeof name === "string" && data === undefined ) { return null; } // Compute a unique ID for the element if ( !id ) { id = ++uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { elem[ expando ] = id; thisCache = cache[ id ] = jQuery.extend(true, {}, name); } else if ( !cache[ id ] ) { elem[ expando ] = id; cache[ id ] = {}; } thisCache = cache[ id ]; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } // Completely remove the data cache delete cache[ id ]; } } }); jQuery.fn.extend({ data: function( key, value ) { if ( typeof key === "undefined" && this.length ) { return jQuery.data( this[0] ); } 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 ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { jQuery.data( this, key, value ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // 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); }); } } }); 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( i, elem ) { 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", [] ); } }); var rclass = /[\n\t]/g, rspace = /\s+/, rreturn = /\r/g, rspecialurl = /href|src|style/, rtype = /(button|input)/i, rfocusable = /(button|input|object|select|textarea)/i, rclickable = /^(a|area)$/i, rradiocheck = /radio|checkbox/; jQuery.fn.extend({ attr: function( name, value ) { return access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split(rspace); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var 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) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), 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].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( value === undefined ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { return (elem.attributes.value || {}).specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var 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 ]; if ( option.selected ) { // Get the specifc value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Typecast each time if the value is a Function and the appended // value is therefore different each time. if ( typeof val === "number" ) { val += ""; } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // 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/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // Using attr for specific style information is now deprecated. Use style instead. return jQuery.style( elem, name, value ); } }); var rnamespaces = /\.(.*)$/, fcleanup = function( nm ) { return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { return "\\" + ch; }); }; /* * 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; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { elem = window; } 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 = elemData.events || {}, eventHandle = elemData.handle, eventHandle; if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? 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; 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 global triggering 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; } var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = 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 ( var 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 ( var 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 ) { 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 ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var target = event.target, old, isClick = jQuery.nodeName(target, "a") && type === "click", special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ type ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + type ]; if ( old ) { target[ "on" + type ] = null; } jQuery.event.triggered = true; target[ type ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( old ) { target[ "on" + type ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace, events; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); } var events = jQuery.data(this, "events"), handlers = events[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace.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, arguments ); 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 originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ 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 ) { event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either } // 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 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); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { event.which = 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, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); }, remove: function( handleObj ) { var remove = true, type = handleObj.origType.replace(rnamespaces, ""); jQuery.each( jQuery.data(this, "events").live || [], function() { if ( type === this.origType.replace(rnamespaces, "") ) { remove = false; return false; } }); if ( remove ) { jQuery.event.remove( this, handleObj.origType, liveHandler ); } } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( this.setInterval ) { this.onbeforeunload = eventHandle; } return false; }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; var removeEvent = document.removeEventListener ? function( elem, type, handle ) { elem.removeEventListener( type, handle, false ); } : function( elem, type, handle ) { elem.detachEvent( "on" + type, handle ); }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[ 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) 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 parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // 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 ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { return 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 formElems = /textarea|input|select/i, changeFilters, getVal = function( elem ) { var type = 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 ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !formElems.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"; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return 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 = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return 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/focus[in] is not needed anymore 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 formElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return formElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { this.addEventListener( orig, handler, true ); }, teardown: function() { this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : 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] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, 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; })); }, 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 ( jQuery.isFunction( data ) ) { fn = data; 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 ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler context.each(function(){ jQuery.event.add( this, liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); }); } else { // unbind live handler context.unbind( liveConvert( type, selector ), fn ); } } return this; } }); function liveHandler( event ) { var stop, elems = [], selectors = [], args = arguments, related, match, handleObj, elem, j, i, l, data, events = jQuery.data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } 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++ ) { for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( match[i].selector === handleObj.selector ) { elem = match[i].elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) { stop = false; break; } } return stop; } function liveConvert( type, selector ) { return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); } 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( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { window.attachEvent("onunload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, 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; // 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 || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } 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]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var 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 ) { var 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 ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var 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.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; 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(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, 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|)\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(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.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 isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var 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 doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); 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]); return m ? [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){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; 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]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // 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; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } 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 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){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, 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 || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + 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; 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, function(all, num){ return "\\" + (num - 0 + 1); })); } 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 ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return a.compareDocumentPosition ? -1 : 1; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return a.ownerDocument ? -1 : 1; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Utility function for retreiving the text value of an array of DOM nodes function getText( 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 += 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(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; 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 ); root = form = null; // release memory in IE })(); (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); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); 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 && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); } (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]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; 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 ) { elem = elem[dir]; var match = false; 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; } } } var contains = document.compareDocumentPosition ? function(a, b){ return !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var 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 tmpSet = [], later = "", match, 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 = getText; jQuery.isXMLDoc = isXML; jQuery.contains = contains; return; window.Sizzle = Sizzle; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, slice = Array.prototype.slice; // Implement the identical functionality for filter and not var winnow = function( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) === 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; }); }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var 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 ( var n = length; n < ret.length; n++ ) { for ( var 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 && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { if ( jQuery.isArray( selectors ) ) { var ret = [], cur = this[0], match, matches = {}, selector; if ( cur && selectors.length ) { for ( var i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.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 }); delete matches[selector]; } } cur = cur.parentNode; } } return ret; } var pos = jQuery.expr.match.POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; return this.map(function( i, cur ) { while ( cur && cur.ownerDocument && cur !== context ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { return cur; } cur = cur.parentNode; } return null; }); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // 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 || this.context ) : jQuery.makeArray( 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 ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return 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; } }); var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<script|<object|<embed|<option|<style/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) fcloseTag = function( all, front, tag ) { return rselfClosing.test( tag ) ? all : front + "></" + tag + ">"; }, 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( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(/=([^="'>\s]+\/)>/g, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, 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, fcloseTag); 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), old = self.html(); self.empty().append(function(){ return value.call( this, i, old ); }); }); } 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.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, value = args[0], scripts = [], fragment, parent; // 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 = 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; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(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(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } function buildFragment( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) 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 && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( 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.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { 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 = []; 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" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, fcloseTag); // 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 ( var 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; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( var 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 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { removeEvent( elem, type, data.handle ); } } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); // exclude the following css properties to add px var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); }; jQuery.extend({ style: function( elem, name, value ) { // don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // ignore negative width and height values #1599 if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { value = undefined; } var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } name = name.replace(rdashAlpha, fcamelCase); if ( set ) { style[ name ] = value; } return style[ name ]; }, css: function( elem, name, force, extra ) { if ( name === "width" || name === "height" ) { var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; function getWH() { val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; } else { val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; } }); } if ( elem.offsetWidth !== 0 ) { getWH(); } else { jQuery.swap( elem, props, getWH ); } return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { var ret, style = elem.style, filter; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { ret = ropacity.test(elem.currentStyle.filter || "") ? (parseFloat(RegExp.$1) / 100) + "" : ""; return ret === "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } if ( !force && style && style[ name ] ) { ret = style[ name ]; } else if ( getComputedStyle ) { // Only "float" is needed here if ( rfloat.test( name ) ) { name = "float"; } name = name.replace( rupper, "-$1" ).toLowerCase(); var defaultView = elem.ownerDocument.defaultView; if ( !defaultView ) { return null; } var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) { ret = computedStyle.getPropertyValue( name ); } // We should always get a number back from opacity if ( name === "opacity" && ret === "" ) { ret = "1"; } } else if ( elem.currentStyle ) { var camelCase = name.replace(rdashAlpha, fcamelCase); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // 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 var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = camelCase === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, // 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 ( var name in options ) { elem.style[ name ] = old[ name ]; } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = now(), rscript = /<script(.|\s)*?\/script>/gi, rselectTextarea = /select|textarea/i, rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, jsre = /=\?(&|$)/, rquery = /\?/, rts = /(\?|&)_=.*?(&|$)/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, // Keep a copy of the old load method _load = jQuery.fn.load; jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" ) { return _load.call( this, url ); // 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 = null; // 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: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // 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(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); 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 }; }) : { name: elem.name, value: val }; }).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.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7 (can't request local files), // so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); var jsonp, status, data, callbackContext = origSettings && origSettings.context || s, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // 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 ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data || origSettings && origSettings.contentType ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { trigger("ajaxSend", [xhr, s]); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { complete(); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(err) { status = "parsererror"; errMsg = err; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { success(); } } else { jQuery.handleError(s, xhr, status, errMsg); } // Fire the complete handlers complete(); if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { oldAbort.call( xhr ); } onreadystatechange( "abort" ); }; } catch(e) { } // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, data, status, xhr ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [xhr, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, xhr, status); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || // Opera returns 0 when status is 304 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } // Opera returns 0 when status is 304 return xhr.status === 304 || xhr.status === 0; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = []; // 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 ) { // 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] ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); function buildParams( prefix, obj ) { if ( jQuery.isArray(obj) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || /\[\]$/.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 ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v ); }); } else { // Serialize scalar item. add( prefix, obj ); } } function add( 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); } } }); var elemdisplay = {}, rfxtypes = /toggle|show|hide/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, callback ) { if ( speed || speed === 0) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var nodeName = this[i].nodeName, display; if ( elemdisplay[ nodeName ] ) { display = elemdisplay[ nodeName ]; } else { var elem = jQuery("<" + nodeName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) { display = "block"; } elem.remove(); elemdisplay[ nodeName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; } return this; } }, hide: function( speed, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) { jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ) { 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); } return this; }, fadeTo: function( speed, to, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { var opt = jQuery.extend({}, optall), p, hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = p.replace(rdashAlpha, fcamelCase); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( ( p === "height" || p === "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = 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 ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; 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; } }); // 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" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, callback ) { return this.animate( props, speed, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? 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 : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( 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; if ( !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 ); // Set display property to block for height/width animations if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { this.elem.style.display = "block"; } }, // Get the current size cur: function( force ) { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(jQuery.fx.tick, 13); } }, // 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 = now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display var old = jQuery.data(this.elem, "olddisplay"); this.elem.style.display = old ? old : this.options.display; if ( jQuery.css(this.elem, "display") === "none" ) { this.elem.style.display = "block"; } } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style(this.elem, p, this.options.orig[p]); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.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() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, 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; }; } function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } if ( "getBoundingClientRect" in document.documentElement ) { 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 ); } var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.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 offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, 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 && /^t(able|d|h)$/i.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.curCSS(body, "marginTop", true) ) || 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 ); body = container = innerDiv = checkDiv = table = td = null; 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.curCSS(body, "marginTop", true) ) || 0; left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } var props = { top: (options.top - curOffset.top) + curTop, 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 = /^body|html$/i.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.curCSS(elem, "marginTop", true) ) || 0; offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 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 && (!/^body|html$/i.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 = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // 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; } }); } else { 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 ]; } }; }); function getWindow( elem ) { return ("scrollTo" in elem && elem.document) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create 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() { return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? jQuery.css( this[0], type, false, 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 ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater 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 size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window); /** * The MIT License * * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// if (typeof document.getAttribute == $undefined) document.getAttribute = function() {}; /** * @workInProgress * @ngdoc function * @name angular.lowercase * @function * * @description Converts string to lowercase * @param {string} string String to be lowercased. * @returns {string} Lowercased string. */ var lowercase = function (string){ return isString(string) ? string.toLowerCase() : string; }; /** * @workInProgress * @ngdoc function * @name angular.uppercase * @function * * @description Converts string to uppercase. * @param {string} string String to be uppercased. * @returns {string} Uppercased string. */ var uppercase = function (string){ return isString(string) ? string.toUpperCase() : string; }; var manualLowercase = function (s) { return isString(s) ? s.replace(/[A-Z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) | 32); }) : s; }; var manualUppercase = function (s) { return isString(s) ? s.replace(/[a-z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) & ~32); }) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods with // correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) { return String.fromCharCode(code); } var $$element = '$element', $$update = '$update', $$scope = '$scope', $$validate = '$validate', $angular = 'angular', $array = 'array', $boolean = 'boolean', $console = 'console', $date = 'date', $display = 'display', $element = 'element', $function = 'function', $length = 'length', $name = 'name', $none = 'none', $noop = 'noop', $null = 'null', $number = 'number', $object = 'object', $string = 'string', $value = 'value', $selected = 'selected', $undefined = 'undefined', NG_EXCEPTION = 'ng-exception', NG_VALIDATION_ERROR = 'ng-validation-error', NOOP = 'noop', PRIORITY_FIRST = -99999, PRIORITY_WATCH = -1000, PRIORITY_LAST = 99999, PRIORITY = {'FIRST': PRIORITY_FIRST, 'LAST': PRIORITY_LAST, 'WATCH':PRIORITY_WATCH}, Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, error = window[$console] ? bind(window[$console], window[$console]['error'] || noop) : noop, /** @name angular */ angular = window[$angular] || (window[$angular] = {}), /** @name angular.markup */ angularTextMarkup = extensionMap(angular, 'markup'), /** @name angular.attrMarkup */ angularAttrMarkup = extensionMap(angular, 'attrMarkup'), /** @name angular.directive */ angularDirective = extensionMap(angular, 'directive'), /** @name angular.widget */ angularWidget = extensionMap(angular, 'widget', lowercase), /** @name angular.validator */ angularValidator = extensionMap(angular, 'validator'), /** @name angular.fileter */ angularFilter = extensionMap(angular, 'filter'), /** @name angular.formatter */ angularFormatter = extensionMap(angular, 'formatter'), /** @name angular.service */ angularService = extensionMap(angular, 'service'), angularCallbacks = extensionMap(angular, 'callbacks'), nodeName_, rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/, DATE_ISOSTRING_LN = 24; /** * @workInProgress * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection. The collection can either * be an object or an array. The `iterator` function is invoked with `iterator(value, key)`, where * `value` is the value of an object property or an array element and `key` is the object property * key or array element index. Optionally, `context` can be specified for the iterator function. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {function()} iterator Iterator function. * @param {Object} context Object to become context (`this`) for the iterator function. * @returns {Objet|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) iterator.call(context, obj[key], key); } } return obj; } function forEachSorted(obj, iterator, context) { var keys = []; for (var key in obj) keys.push(key); keys.sort(); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } /** * @workInProgress * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) to * `dst`. You can specify multiple `src` objects. * * @param {Object} dst The destination object. * @param {...Object} src The source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function inherit(parent, extra) { return extend(new (extend(function(){}, {prototype:parent}))(), extra); } /** * @workInProgress * @ngdoc function * @name angular.noop * @function * * @description * Empty function that performs no operation whatsoever. This function is useful when writing code * in the functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} /** * @workInProgress * @ngdoc function * @name angular.identity * @function * * @description * A function that does nothing except for returning its first argument. This function is useful * when writing code in the functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} function valueFn(value) {return function(){ return value; };} function extensionMap(angular, name, transform) { var extPoint; return angular[name] || (extPoint = angular[name] = function (name, fn, prop){ name = (transform || identity)(name); if (isDefined(fn)) { extPoint[name] = extend(fn, prop || {}); } return extPoint[name]; }); } /** * @workInProgress * @ngdoc function * @name angular.isUndefined * @function * * @description * Checks if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){ return typeof value == $undefined; } /** * @workInProgress * @ngdoc function * @name angular.isDefined * @function * * @description * Checks if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){ return typeof value != $undefined; } /** * @workInProgress * @ngdoc function * @name angular.isObject * @function * * @description * Checks if a reference is an `Object`. Unlike in JavaScript `null`s are not considered to be * objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){ return value!=null && typeof value == $object;} /** * @workInProgress * @ngdoc function * @name angular.isString * @function * * @description * Checks if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){ return typeof value == $string;} /** * @workInProgress * @ngdoc function * @name angular.isNumber * @function * * @description * Checks if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){ return typeof value == $number;} /** * @workInProgress * @ngdoc function * @name angular.isDate * @function * * @description * Checks if value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return value instanceof Date; } /** * @workInProgress * @ngdoc function * @name angular.isArray * @function * * @description * Checks if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return value instanceof Array; } /** * @workInProgress * @ngdoc function * @name angular.isFunction * @function * * @description * Checks if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){ return typeof value == $function;} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isBoolean(value) { return typeof value == $boolean;} function isTextNode(node) { return nodeName_(node) == '#text'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * HTML class which is the only class which can be used in ng:bind to inline HTML for security reasons. * @constructor * @param html raw (unsafe) html * @param {string=} option if set to 'usafe' then get method will return raw (unsafe/unsanitized) html */ function HTML(html, option) { this.html = html; this.get = lowercase(option) == 'unsafe' ? valueFn(html) : function htmlSanitize() { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML' ) ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function isVisible(element) { var rect = element[0].getBoundingClientRect(), width = (rect.width || (rect.right||0 - rect.left||0)), height = (rect.height || (rect.bottom||0 - rect.top||0)); return width>0 && height>0; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @ngdoc function * @name angular.Object.size * @function * * @description * Determines the number of elements in an array, number of properties of an object or string * length. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {Object|Array|string} obj Object, array or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object or an array. * * @example * <doc:example> * <doc:source> * Number of items in array: {{ [1,2].$size() }}<br/> * Number of items in object: {{ {a:1, b:2, c:3}.$size() }}<br/> * </doc:source> * <doc:scenario> * it('should print correct sizes for an array and an object', function() { * expect(binding('[1,2].$size()')).toBe('2'); * expect(binding('{a:1, b:2, c:3}.$size()')).toBe('3'); * }); * </doc:scenario> * </doc:example> */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return true; } return false; } function indexOf(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.Object.copy * @function * * @description * Creates a deep copy of `source`. * * If `source` is an object or an array, all of its members will be copied into the `destination` * object. * * If `destination` is not provided and `source` is an object or an array, a copy is created & * returned, otherwise the `source` is returned. * * If `destination` is provided, all of its properties will be deleted. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {*} source The source to be used to make a copy. * Can be any type including primitives, `null` and `undefined`. * @param {(Object|Array)=} destination Optional destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination` if `destination` was specified. * * @example * <doc:example> * <doc:source> Salutation: <input type="text" name="master.salutation" value="Hello" /><br/> Name: <input type="text" name="master.name" value="world"/><br/> <button ng:click="form = master.$copy()">copy</button> <hr/> The master object is <span ng:hide="master.$equals(form)">NOT</span> equal to the form object. <pre>master={{master}}</pre> <pre>form={{form}}</pre> * </doc:source> * <doc:scenario> it('should print that initialy the form object is NOT equal to master', function() { expect(element('.doc-example-live input[name=master.salutation]').val()).toBe('Hello'); expect(element('.doc-example-live input[name=master.name]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); it('should make form and master equal when the copy button is clicked', function() { element('.doc-example-live button').click(); expect(element('.doc-example-live span').css('display')).toBe('none'); }); * </doc:scenario> * </doc:example> */ function copy(source, destination){ if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * @ngdoc function * @name angular.Object.equals * @function * * @description * Determines if two objects or value are equivalent. * * To be equivalent, they must pass `==` comparison or be of the same type and have all their * properties pass `==` comparison. During property comparision properties of `function` type and * properties with name starting with `$` are ignored. * * Supports values types, arrays and objects. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. * * @example * <doc:example> * <doc:source> Salutation: <input type="text" name="greeting.salutation" value="Hello" /><br/> Name: <input type="text" name="greeting.name" value="world"/><br/> <hr/> The <code>greeting</code> object is <span ng:hide="greeting.$equals({salutation:'Hello', name:'world'})">NOT</span> equal to <code>{salutation:'Hello', name:'world'}</code>. <pre>greeting={{greeting}}</pre> * </doc:source> * <doc:scenario> it('should print that initialy greeting is equal to the hardcoded value object', function() { expect(element('.doc-example-live input[name=greeting.salutation]').val()).toBe('Hello'); expect(element('.doc-example-live input[name=greeting.name]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('none'); }); it('should say that the objects are not equal when the form is modified', function() { input('greeting.name').enter('kitty'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); * </doc:scenario> * </doc:example> */ function equals(o1, o2) { if (o1 == o2) return true; if (o1 === null || o2 === null) return false; var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2 && t1 == 'object') { if (o1 instanceof Array) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else { keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } return false; } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function isRenderableElement(element) { var name = element && element[0] && element[0].nodeName; return name && name.charAt(0) != '#' && !includes(['TR', 'COL', 'COLGROUP', 'TBODY', 'THEAD', 'TFOOT'], name); } function elementError(element, type, error) { var parent; while (!isRenderableElement(element)) { parent = element.parent(); if (parent.length) { element = element.parent(); } else { return; } } if (element[0]['$NG_ERROR'] !== error) { element[0]['$NG_ERROR'] = error; if (error) { element.addClass(type); element.attr(type, error.message || error); } else { element.removeClass(type); element.removeAttr(type); } } } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index, array2.length)); } /** * @workInProgress * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for `fn`). * Optional `args` can be supplied which are prebound to the function, also known as * [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? slice.call(arguments, 2, arguments.length) : []; if (typeof fn == $function && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0, arguments.length))) : fn.apply(self, curryArgs); }: function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions and so they can not be bound (but they don't need to be) return fn; } } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } function merge(src, dst) { for ( var key in src) { var value = dst[key]; var type = typeof value; if (type == $undefined) { dst[key] = fromJson(toJson(src[key])); } else if (type == 'object' && value.constructor != array && key.substring(0, 1) != "$") { merge(src[key], value); } } } /** @name angular.compile */ function compile(element) { return new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget) .compile(element); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = unescape(key_value[0]); obj[key] = isDefined(key_value[1]) ? unescape(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(escape(key) + (value === true ? '' : '=' + escape(value))); }); return parts.length ? parts.join('&') : ''; } /** * we need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:autobind * @element script * * @TODO ng:autobind is not a directive!! it should be documented as bootstrap parameter in a * separate bootstrap section. * @TODO rename to ng:autobind to ng:autoboot * * @description * * `ng:autobind` with no parameters tells angular to compile and manage the whole page. * * `ng:autobind="[root element ID]"` tells angular to compile and manage part of the docucment, * starting at "root element ID". * * For details on bootstrapping angular, see {@link guide/dev_guide.bootstrap Initializing Angular} * in the Angular Developer Guide. */ function angularInit(config, document){ var autobind = config.autobind; if (autobind) { var element = isString(autobind) ? document.getElementById(autobind) : document, scope = compile(element)(createScope({'$config':config})), $browser = scope.$service('$browser'); if (config.css) $browser.addCss(config.base_url + config.css); else if(msie<8) $browser.addJs(config.base_url + config.ie_compat, config.ie_compat_id); } } function angularJsConfig(document, config) { bindJQuery(); var scripts = document.getElementsByTagName("script"), match; config = extend({ ie_compat_id: 'ng-ie-compat' }, config); for(var j = 0; j < scripts.length; j++) { match = (scripts[j].src || "").match(rngScript); if (match) { config.base_url = match[1]; config.ie_compat = match[1] + 'angular-ie-compat' + (match[2] || '') + '.js'; extend(config, parseKeyValue(match[6])); eachAttribute(jqLite(scripts[j]), function(value, name){ if (/^ng:/.exec(name)) { name = name.substring(3).replace(/-/g, '_'); value = value || true; config[name] = value; } }); } } return config; } function bindJQuery(){ // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope }); } else { jqLite = jqLiteWrap; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { var error = new Error("Argument '" + (name||'?') + "' is " + (reason || "required")); if (window.console) window.console.log(error.stack); throw error; } } function assertArgFn(arg, name) { assertArg(isFunction(arg, name, 'not a function')); } var array = [].constructor; /** * @workInProgress * @ngdoc function * @name angular.toJson * @function * * @description * Serializes the input into a JSON formated string. * * @param {Object|Array|Date|string|number} obj Input to jsonify. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : null, []); return buf.join(''); } /** * @workInProgress * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a string in the JSON format. * * @param {string} json JSON string to deserialize. * @param {boolean} [useNative=false] Use native JSON parser if available * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json, useNative) { if (!isString(json)) return json; var obj, p, expression; try { if (useNative && window.JSON && window.JSON.parse) { obj = JSON.parse(json); return transformDates(obj); } p = parser(json, true); expression = p.primary(); p.assertAllConsumed(); return expression(); } catch (e) { error("fromJson error: ", json, e); throw e; } // TODO make forEach optionally recursive and remove this function function transformDates(obj) { if (isString(obj) && obj.length === DATE_ISOSTRING_LN) { return angularString.toDate(obj); } else if (isArray(obj) || isObject(obj)) { forEach(obj, function(val, name) { obj[name] = transformDates(val); }); } return obj; } } angular['toJson'] = toJson; angular['fromJson'] = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angular['String']['quoteUnicode'](obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angular['String']['quoteUnicode'](obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isDate(obj)) { buf.push(angular['String']['quoteUnicode'](angular['Date']['toString'](obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (obj[k] === undefined) continue; keys.push(k); } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (typeof value != $function) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angular['String']['quote'](key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } } /** * Template provides directions an how to bind to a given element. * It contains a list of init functions which need to be called to * bind to a new instance of elements. It also provides a list * of child paths which contain child templates */ function Template(priority) { this.paths = []; this.children = []; this.inits = []; this.priority = priority; this.newScope = false; } Template.prototype = { attach: function(element, scope) { var inits = {}; this.collectInits(element, inits, scope); forEachSorted(inits, function(queue){ forEach(queue, function(fn) {fn();}); }); }, collectInits: function(element, inits, scope) { var queue = inits[this.priority], childScope = scope; if (!queue) { inits[this.priority] = queue = []; } if (this.newScope) { childScope = createScope(scope); scope.$onEval(childScope.$eval); element.data($$scope, childScope); } forEach(this.inits, function(fn) { queue.push(function() { childScope.$tryEval(function(){ return childScope.$service(fn, childScope, element); }, element); }); }); var i, childNodes = element[0].childNodes, children = this.children, paths = this.paths, length = paths.length; for (i = 0; i < length; i++) { children[i].collectInits(jqLite(childNodes[paths[i]]), inits, childScope); } }, addInit:function(init) { if (init) { this.inits.push(init); } }, addChild: function(index, template) { if (template) { this.paths.push(index); this.children.push(template); } }, empty: function() { return this.inits.length === 0 && this.paths.length === 0; } }; /////////////////////////////////// //Compiler ////////////////////////////////// /** * @workInProgress * @ngdoc function * @name angular.compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link angular.scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup}, * {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it * executes coresponding markup, attrMarkup, widget or directive template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link angular.widget.@ng:repeat repeater} many-times, in which case each call results in a view * that is a DOM clone of the original template. * <pre> //copile the entire window.document and give me the scope bound to this template. var rootSscope = angular.compile(window.document)(); //compile a piece of html var rootScope2 = angular.compile(''<div ng:click="clicked = true">click me</div>')(); //compile a piece of html and retain reference to both the dom and scope var template = angular.element('<div ng:click="clicked = true">click me</div>'), scoope = angular.compile(view)(); //at this point template was transformed into a view </pre> * * * @param {string|DOMElement} element Element or HTML to compile into a template function. * @returns {function([scope][, cloneAttachFn])} a template function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link angular.scope Scope} to bind to. If none specified, then a new * root scope is created. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the approriate place. The `cloneAttachFn` is * called as: <br/> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the template function returns the scope to which the element is bound to. It is either * the same scope as the one passed into the template function, or if none were provided it's the * newly create scope. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var view = angular.element('<p>{{total}}</p>'), * scope = angular.compile(view)(); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var original = angular.element('<p>{{total}}</p>'), * scope = someParentScope.$new(), * clone; * * angular.compile(original)(scope, function(clonedElement, scope) { * clone = clonedElement; * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * Compiler Methods For Widgets and Directives: * * The following methods are available for use when you write your own widgets, directives, * and markup. (Recall that the compile function's this is a reference to the compiler.) * * `compile(element)` - returns linker - * Invoke a new instance of the compiler to compile a DOM element and return a linker function. * You can apply the linker function to the original element or a clone of the original element. * The linker function returns a scope. * * * `comment(commentText)` - returns element - Create a comment element. * * * `element(elementName)` - returns element - Create an element by name. * * * `text(text)` - returns element - Create a text element. * * * `descend([set])` - returns descend state (true or false). Get or set the current descend * state. If true the compiler will descend to children elements. * * * `directives([set])` - returns directive state (true or false). Get or set the current * directives processing state. The compiler will process directives only when directives set to * true. * * For information on how the compiler works, see the * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide. */ function Compiler(markup, attrMarkup, directives, widgets){ this.markup = markup; this.attrMarkup = attrMarkup; this.directives = directives; this.widgets = widgets; } Compiler.prototype = { compile: function(templateElement) { templateElement = jqLite(templateElement); var index = 0, template, parent = templateElement.parent(); if (parent && parent[0]) { parent = parent[0]; for(var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i] == templateElement[0]) { index = i; } } } template = this.templatize(templateElement, index, 0) || new Template(); return function(scope, cloneConnectFn){ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var element = cloneConnectFn ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!! : templateElement; scope = scope || createScope(); element.data($$scope, scope); scope.$element = element; (cloneConnectFn||noop)(element, scope); template.attach(element, scope); scope.$eval(); return scope; }; }, /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:eval-order * * @description * Normally the view is updated from top to bottom. This usually is * not a problem, but under some circumstances the values for data * is not available until after the full view is computed. If such * values are needed before they are computed the order of * evaluation can be change using ng:eval-order * * @element ANY * @param {integer|string=} [priority=0] priority integer, or FIRST, LAST constant * * @example * try changing the invoice and see that the Total will lag in evaluation * @example <doc:example> <doc:source> <div>TOTAL: without ng:eval-order {{ items.$sum('total') | currency }}</div> <div ng:eval-order='LAST'>TOTAL: with ng:eval-order {{ items.$sum('total') | currency }}</div> <table ng:init="items=[{qty:1, cost:9.99, desc:'gadget'}]"> <tr> <td>QTY</td> <td>Description</td> <td>Cost</td> <td>Total</td> <td></td> </tr> <tr ng:repeat="item in items"> <td><input name="item.qty"/></td> <td><input name="item.desc"/></td> <td><input name="item.cost"/></td> <td>{{item.total = item.qty * item.cost | currency}}</td> <td><a href="" ng:click="items.$remove(item)">X</a></td> </tr> <tr> <td colspan="3"><a href="" ng:click="items.$add()">add</a></td> <td>{{ items.$sum('total') | currency }}</td> </tr> </table> </doc:source> <doc:scenario> it('should check ng:format', function(){ expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99'); expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$9.99'); input('item.qty').enter('2'); expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99'); expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$19.98'); }); </doc:scenario> </doc:example> */ templatize: function(element, elementIndex, priority){ var self = this, widget, fn, directiveFns = self.directives, descend = true, directives = true, elementName = nodeName_(element), elementNamespace = elementName.indexOf(':') > 0 ? lowercase(elementName).replace(':', '-') : '', template, selfApi = { compile: bind(self, self.compile), descend: function(value){ if(isDefined(value)) descend = value; return descend;}, directives: function(value){ if(isDefined(value)) directives = value; return directives;}, scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;} }; try { priority = element.attr('ng:eval-order') || priority || 0; } catch (e) { // for some reason IE throws error under some weird circumstances. so just assume nothing priority = priority || 0; } element.addClass(elementNamespace); if (isString(priority)) { priority = PRIORITY[uppercase(priority)] || parseInt(priority, 10); } template = new Template(priority); eachAttribute(element, function(value, name){ if (!widget) { if (widget = self.widgets('@' + name)) { element.addClass('ng-attr-widget'); widget = bind(selfApi, widget, value, element); } } }); if (!widget) { if (widget = self.widgets(elementName)) { if (elementNamespace) element.addClass('ng-widget'); widget = bind(selfApi, widget, element); } } if (widget) { descend = false; directives = false; var parent = element.parent(); template.addInit(widget.call(selfApi, element)); if (parent && parent[0]) { element = jqLite(parent[0].childNodes[elementIndex]); } } if (descend){ // process markup for text nodes only for(var i=0, child=element[0].childNodes; i<child.length; i++) { if (isTextNode(child[i])) { forEach(self.markup, function(markup){ if (i<child.length) { var textNode = jqLite(child[i]); markup.call(selfApi, textNode.text(), textNode, element); } }); } } } if (directives) { // Process attributes/directives eachAttribute(element, function(value, name){ forEach(self.attrMarkup, function(markup){ markup.call(selfApi, value, name, element); }); }); eachAttribute(element, function(value, name){ fn = directiveFns[name]; if (fn) { element.addClass('ng-directive'); template.addInit((directiveFns[name]).call(selfApi, value, element)); } }); } // Process non text child nodes if (descend) { eachNode(element, function(child, i){ template.addChild(i, self.templatize(child, i, priority)); }); } return template.empty() ? null : template; } }; function eachNode(element, fn){ var i, chldNodes = element[0].childNodes || [], chld; for (i = 0; i < chldNodes.length; i++) { if(!isTextNode(chld = chldNodes[i])) { fn(jqLite(chld), i); } } } function eachAttribute(element, fn){ var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {}; for (i = 0; i < attrs.length; i++) { attr = attrs[i]; name = attr.name; value = attr.value; if (msie && name == 'href') { value = decodeURIComponent(element[0].getAttribute(name, 2)); } attrValue[name] = value; } forEachSorted(attrValue, fn); } function getter(instance, path, unboundFn) { if (!path) return instance; var element = path.split('.'); var key; var lastInstance = instance; var len = element.length; for ( var i = 0; i < len; i++) { key = element[i]; if (!key.match(/^[\$\w][\$\w\d]*$/)) throw "Expression '" + path + "' is not a valid expression for accesing variables."; if (instance) { lastInstance = instance; instance = instance[key]; } if (isUndefined(instance) && key.charAt(0) == '$') { var type = angular['Global']['typeOf'](lastInstance); type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; var fn = type ? type[[key.substring(1)]] : undefined; if (fn) { instance = bind(lastInstance, fn, lastInstance); return instance; } } } if (!unboundFn && isFunction(instance)) { return bind(lastInstance, instance); } return instance; } function setter(instance, path, value){ var element = path.split('.'); for ( var i = 0; element.length > 1; i++) { var key = element.shift(); var newInstance = instance[key]; if (!newInstance) { newInstance = {}; instance[key] = newInstance; } instance = newInstance; } instance[element.shift()] = value; return value; } /////////////////////////////////// var scopeId = 0, getterFnCache = {}, compileCache = {}, JS_KEYWORDS = {}; forEach( ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," + "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," + "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," + "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," + "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/), function(key){ JS_KEYWORDS[key] = true;} ); function getterFn(path){ var fn = getterFnCache[path]; if (fn) return fn; var code = 'var l, fn, t;\n'; forEach(path.split('.'), function(key) { key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key; code += 'if(!s) return s;\n' + 'l=s;\n' + 's=s' + key + ';\n' + 'if(typeof s=="function" && !(s instanceof RegExp)) s = function(){ return l'+key+'.apply(l, arguments); };\n'; if (key.charAt(1) == '$') { // special code for super-imposed functions var name = key.substr(2); code += 'if(!s) {\n' + ' t = angular.Global.typeOf(l);\n' + ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' + ' if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n' + '}\n'; } }); code += 'return s;'; fn = Function('s', code); fn["toString"] = function(){ return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// function expressionCompile(exp){ if (typeof exp === $function) return exp; var fn = compileCache[exp]; if (!fn) { var p = parser(exp); var fnSelf = p.statements(); p.assertAllConsumed(); fn = compileCache[exp] = extend( function(){ return fnSelf(this);}, {fnSelf: fnSelf}); } return fn; } function errorHandlerFor(element, error) { elementError(element, NG_EXCEPTION, isDefined(error) ? formatError(error) : error); } /** * @workInProgress * @ngdoc overview * @name angular.scope * * @description * Scope is a JavaScript object and the execution context for expressions. You can think about * scopes as JavaScript objects that have extra APIs for registering watchers. A scope is the * context in which model (from the model-view-controller design pattern) exists. * * Angular scope objects provide the following methods: * * * {@link angular.scope.$become $become()} - * * {@link angular.scope.$bind $bind()} - * * {@link angular.scope.$eval $eval()} - * * {@link angular.scope.$get $get()} - * * {@link angular.scope.$new $new()} - * * {@link angular.scope.$onEval $onEval()} - * * {@link angular.scope.$service $service()} - * * {@link angular.scope.$set $set()} - * * {@link angular.scope.$tryEval $tryEval()} - * * {@link angular.scope.$watch $watch()} - * * For more information about how angular scope objects work, see {@link guide/dev_guide.scopes * Angular Scope Objects} in the angular Developer Guide. */ function createScope(parent, providers, instanceCache) { function Parent(){} parent = Parent.prototype = (parent || {}); var instance = new Parent(); var evalLists = {sorted:[]}; var $log, $exceptionHandler; extend(instance, { 'this': instance, $id: (scopeId++), $parent: parent, /** * @workInProgress * @ngdoc function * @name angular.scope.$bind * @function * * @description * Binds a function `fn` to the current scope. See: {@link angular.bind}. <pre> var scope = angular.scope(); var fn = scope.$bind(function(){ return this; }); expect(fn()).toEqual(scope); </pre> * * @param {function()} fn Function to be bound. */ $bind: bind(instance, bind, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$get * @function * * @description * Returns the value for `property_chain` on the current scope. Unlike in JavaScript, if there * are any `undefined` intermediary properties, `undefined` is returned instead of throwing an * exception. * <pre> var scope = angular.scope(); expect(scope.$get('person.name')).toEqual(undefined); scope.person = {}; expect(scope.$get('person.name')).toEqual(undefined); scope.person.name = 'misko'; expect(scope.$get('person.name')).toEqual('misko'); </pre> * * @param {string} property_chain String representing name of a scope property. Optionally * properties can be chained with `.` (dot), e.g. `'person.name.first'` * @returns {*} Value for the (nested) property. */ $get: bind(instance, getter, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$set * @function * * @description * Assigns a value to a property of the current scope specified via `property_chain`. Unlike in * JavaScript, if there are any `undefined` intermediary properties, empty objects are created * and assigned in to them instead of throwing an exception. * <pre> var scope = angular.scope(); expect(scope.person).toEqual(undefined); scope.$set('person.name', 'misko'); expect(scope.person).toEqual({name:'misko'}); expect(scope.person.name).toEqual('misko'); </pre> * * @param {string} property_chain String representing name of a scope property. Optionally * properties can be chained with `.` (dot), e.g. `'person.name.first'` * @param {*} value Value to assign to the scope property. */ $set: bind(instance, setter, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$eval * @function * * @description * Without the `exp` parameter triggers an eval cycle for this scope and its child scopes. * * With the `exp` parameter, compiles the expression to a function and calls it with `this` set * to the current scope and returns the result. In other words, evaluates `exp` as angular * expression in the context of the current scope. * * # Example <pre> var scope = angular.scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(){ return this.a + this.b; })).toEqual(3); scope.$onEval('sum = a+b'); expect(scope.sum).toEqual(undefined); scope.$eval(); expect(scope.sum).toEqual(3); </pre> * * @param {(string|function())=} exp An angular expression to be compiled to a function or a js * function. * * @returns {*} The result of calling compiled `exp` with `this` set to the current scope. */ $eval: function(exp) { var type = typeof exp; var i, iSize; var j, jSize; var queue; var fn; if (type == $undefined) { for ( i = 0, iSize = evalLists.sorted.length; i < iSize; i++) { for ( queue = evalLists.sorted[i], jSize = queue.length, j= 0; j < jSize; j++) { instance.$tryEval(queue[j].fn, queue[j].handler); } } } else if (type === $function) { return exp.call(instance); } else if (type === 'string') { return expressionCompile(exp).call(instance); } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$tryEval * @function * * @description * Evaluates the expression in the context of the current scope just like * {@link angular.scope.$eval} with expression parameter, but also wraps it in a try/catch * block. * * If an exception is thrown then `exceptionHandler` is used to handle the exception. * * # Example <pre> var scope = angular.scope(); scope.error = function(){ throw 'myerror'; }; scope.$exceptionHandler = function(e) {this.lastException = e; }; expect(scope.$eval('error()')); expect(scope.lastException).toEqual('myerror'); this.lastException = null; expect(scope.$eval('error()'), function(e) {this.lastException = e; }); expect(scope.lastException).toEqual('myerror'); var body = angular.element(window.document.body); expect(scope.$eval('error()'), body); expect(body.attr('ng-exception')).toEqual('"myerror"'); expect(body.hasClass('ng-exception')).toEqual(true); </pre> * * @param {string|function()} expression Angular expression to evaluate. * @param {(function()|DOMElement)=} exceptionHandler Function to be called or DOMElement to be * decorated. * @returns {*} The result of `expression` evaluation. */ $tryEval: function (expression, exceptionHandler) { var type = typeof expression; try { if (type == $function) { return expression.call(instance); } else if (type == 'string'){ return expressionCompile(expression).call(instance); } } catch (e) { if ($log) $log.error(e); if (isFunction(exceptionHandler)) { exceptionHandler(e); } else if (exceptionHandler) { errorHandlerFor(exceptionHandler, e); } else if (isFunction($exceptionHandler)) { $exceptionHandler(e); } } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$watch * @function * * @description * Registers `listener` as a callback to be executed every time the `watchExp` changes. Be aware * that the callback gets, by default, called upon registration, this can be prevented via the * `initRun` parameter. * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', 'counter = counter + 1'); expect(scope.counter).toEqual(1); scope.$eval(); expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$eval(); expect(scope.counter).toEqual(2); </pre> * * @param {function()|string} watchExp Expression that should be evaluated and checked for * change during each eval cycle. Can be an angular string expression or a function. * @param {function()|string} listener Function (or angular string expression) that gets called * every time the value of the `watchExp` changes. The function will be called with two * parameters, `newValue` and `oldValue`. * @param {(function()|DOMElement)=} [exceptionHanlder=angular.service.$exceptionHandler] Handler * that gets called when `watchExp` or `listener` throws an exception. If a DOMElement is * specified as handler, the element gets decorated by angular with the information about the * exception. * @param {boolean=} [initRun=true] Flag that prevents the first execution of the listener upon * registration. * */ $watch: function(watchExp, listener, exceptionHandler, initRun) { var watch = expressionCompile(watchExp), last = watch.call(instance); listener = expressionCompile(listener); function watcher(firstRun){ var value = watch.call(instance), // we have to save the value because listener can call ourselves => inf loop lastValue = last; if (firstRun || lastValue !== value) { last = value; instance.$tryEval(function(){ return listener.call(instance, value, lastValue); }, exceptionHandler); } } instance.$onEval(PRIORITY_WATCH, watcher); if (isUndefined(initRun)) initRun = true; if (initRun) watcher(true); }, /** * @workInProgress * @ngdoc function * @name angular.scope.$onEval * @function * * @description * Evaluates the `expr` expression in the context of the current scope during each * {@link angular.scope.$eval eval cycle}. * * # Example <pre> var scope = angular.scope(); scope.counter = 0; scope.$onEval('counter = counter + 1'); expect(scope.counter).toEqual(0); scope.$eval(); expect(scope.counter).toEqual(1); </pre> * * @param {number} [priority=0] Execution priority. Lower priority numbers get executed first. * @param {string|function()} expr Angular expression or function to be executed. * @param {(function()|DOMElement)=} [exceptionHandler=angular.service.$exceptionHandler] Handler * function to call or DOM element to decorate when an exception occurs. * */ $onEval: function(priority, expr, exceptionHandler){ if (!isNumber(priority)) { exceptionHandler = expr; expr = priority; priority = 0; } var evalList = evalLists[priority]; if (!evalList) { evalList = evalLists[priority] = []; evalList.priority = priority; evalLists.sorted.push(evalList); evalLists.sorted.sort(function(a,b){return a.priority-b.priority;}); } evalList.push({ fn: expressionCompile(expr), handler: exceptionHandler }); }, /** * @workInProgress * @ngdoc function * @name angular.scope.$become * @function * @deprecated This method will be removed before 1.0 * * @description * Modifies the scope to act like an instance of the given class by: * * - copying the class's prototype methods * - applying the class's initialization function to the scope instance (without using the new * operator) * * That makes the scope be a `this` for the given class's methods — effectively an instance of * the given class with additional (scope) stuff. A scope can later `$become` another class. * * `$become` gets used to make the current scope act like an instance of a controller class. * This allows for use of a controller class in two ways. * * - as an ordinary JavaScript class for standalone testing, instantiated using the new * operator, with no attached view. * - as a controller for an angular model stored in a scope, "instantiated" by * `scope.$become(ControllerClass)`. * * Either way, the controller's methods refer to the model variables like `this.name`. When * stored in a scope, the model supports data binding. When bound to a view, {{name}} in the * HTML template refers to the same variable. */ $become: function(Class) { if (isFunction(Class)) { instance.constructor = Class; forEach(Class.prototype, function(fn, name){ instance[name] = bind(instance, fn); }); instance.$service.apply(instance, concat([Class, instance], arguments, 1)); //TODO: backwards compatibility hack, remove when we don't depend on init methods if (isFunction(Class.prototype.init)) { instance.init(); } } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$new * @function * * @description * Creates a new {@link angular.scope scope}, that: * * - is a child of the current scope * - will {@link angular.scope.$become $become} of type specified via `constructor` * * @param {function()} constructor Constructor function of the type the new scope should assume. * @returns {Object} The newly created child scope. * */ $new: function(constructor) { var child = createScope(instance); child.$become.apply(instance, concat([constructor], arguments, 1)); instance.$onEval(child.$eval); return child; } }); if (!parent.$root) { instance.$root = instance; instance.$parent = instance; /** * @workInProgress * @ngdoc function * @name angular.scope.$service * @function * * @description * Provides access to angular's dependency injector and * {@link angular.service registered services}. In general the use of this api is discouraged, * except for tests and components that currently don't support dependency injection (widgets, * filters, etc). * * @param {string} serviceId String ID of the service to return. * @returns {*} Value, object or function returned by the service factory function if any. */ (instance.$service = createInjector(instance, providers, instanceCache))(); } $log = instance.$service('$log'); $exceptionHandler = instance.$service('$exceptionHandler'); return instance; } /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an inject function that can be used for dependency injection. * (See {@link guide/dev_guide.di dependency injection}) * * The inject function can be used for retrieving service instances or for calling any function * which has the $inject property so that the services can be automatically provided. Angular * creates an injection function automatically for the root scope and it is available as * {@link angular.scope.$service $service}. * * @param {Object=} [providerScope={}] provider's `this` * @param {Object.<string, function()>=} [providers=angular.service] Map of provider (factory) * function. * @param {Object.<string, function()>=} [cache={}] Place where instances are saved for reuse. Can * also be used to override services speciafied by `providers` (useful in tests). * @returns * {function()} Injector function: `function(value, scope, args...)`: * * * `value` - `{string|array|function}` * * `scope(optional=rootScope)` - optional function "`this`" when `value` is type `function`. * * `args(optional)` - optional set of arguments to pass to function after injection arguments. * (also known as curry arguments or currying). * * #Return value of `function(value, scope, args...)` * The injector function return value depended on the type of `value` argument: * * * `string`: return an instance for the injection key. * * `array` of keys: returns an array of instances for those keys. (see `string` above.) * * `function`: look at `$inject` property of function to determine instances to inject * and then call the function with instances and `scope`. Any additional arguments * (`args`) are appended to the function arguments. * * `none`: initialize eager providers. * */ function createInjector(providerScope, providers, cache) { providers = providers || angularService; cache = cache || {}; providerScope = providerScope || {}; return function inject(value, scope, args){ var returnValue, provider; if (isString(value)) { if (!(value in cache)) { provider = providers[value]; if (!provider) throw "Unknown provider for '"+value+"'."; cache[value] = inject(provider, providerScope); } returnValue = cache[value]; } else if (isArray(value)) { returnValue = []; forEach(value, function(name) { returnValue.push(inject(name)); }); } else if (isFunction(value)) { returnValue = inject(injectionArgs(value)); returnValue = value.apply(scope, concat(returnValue, arguments, 2)); } else if (isObject(value)) { forEach(providers, function(provider, name){ if (provider.$eager) inject(name); if (provider.$creation) throw new Error("Failed to register service '" + name + "': $creation property is unsupported. Use $eager:true or see release notes."); }); } else { returnValue = inject(providerScope); } return returnValue; }; } function injectService(services, fn) { return extend(fn, {$inject:services}); } function injectUpdateView(fn) { return injectService(['$updateView'], fn); } function angularServiceInject(name, fn, inject, eager) { angularService(name, fn, {$inject:inject, $eager:eager}); } /** * @returns the $inject property of function. If not found the * the $inject is computed by looking at the toString of function and * extracting all arguments which start with $ or end with _ as the * injection names. */ var FN_ARGS = /^function\s*[^\(]*\(([^\)]*)\)/; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(((\$?).+?)(_?))\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function injectionArgs(fn) { assertArgFn(fn); if (!fn.$inject) { var args = fn.$inject = []; var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, name, injectName, $, _){ assertArg(args, name, 'after non-injectable arg'); if ($ || _) args.push(injectName); else args = null; // once we reach an argument which is not injectable then ignore }); }); } return fn.$inject; } var OPERATORS = { 'null':function(self){return null;}, 'true':function(self){return true;}, 'false':function(self){return false;}, $undefined:noop, '+':function(self, a,b){return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, a,b){return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, a,b){return a*b;}, '/':function(self, a,b){return a/b;}, '%':function(self, a,b){return a%b;}, '^':function(self, a,b){return a^b;}, '=':noop, '==':function(self, a,b){return a==b;}, '!=':function(self, a,b){return a!=b;}, '<':function(self, a,b){return a<b;}, '>':function(self, a,b){return a>b;}, '<=':function(self, a,b){return a<=b;}, '>=':function(self, a,b){return a>=b;}, '&&':function(self, a,b){return a&&b;}, '||':function(self, a,b){return a||b;}, '&':function(self, a,b){return a&b;}, // '|':function(self, a,b){return a|b;}, '|':function(self, a,b){return b(self, a);}, '!':function(self, a){return !a;} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, parseStringsForObjects){ var dateParseLength = parseStringsForObjects ? DATE_ISOSTRING_LN : -1, tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function(){return number;}}); } function readIdent() { var ident = ""; var start = index; var fn; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { ident += ch; } else { break; } index++; } fn = OPERATORS[ident]; tokens.push({ index:start, text:ident, json: fn, fn:fn||extend(getterFn(ident), { assign:function(self, value){ return setter(self, ident, value); } }) }); } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({index:start, text:rawString, string:string, json:true, fn:function(){ return (string.length == dateParseLength) ? angular['String']['toDate'](string) : string; }}); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json){ var ZERO = valueFn(0), tokens = lex(text, json), assignment = _assignment, assignable = logicalOR, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain, functionIdent = _functionIdent, pipeFunction = _pipeFunction; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = assignable = filterChain = functionIdent = pipeFunction = function (){ throwError("is not valid json", {text:text, index:0}); }; } return { assertAllConsumed: assertAllConsumed, assignable: assignable, primary: primary, statements: statements, validator: validator, formatter: formatter, filter: filter, //TODO: delete me, since having watch in UI is logic in UI. (leftover form getangular) watch: watch }; /////////////////////////////////// function throwError(msg, token) { throw Error("Parse Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { index = token.index; throwError("is not valid json", token); } tokens.shift(); this.currentToken = token; return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self) { return fn(self, right(self)); }; } function binaryFn(left, fn, right) { return function(self) { return fn(self, left(self), right(self)); }; } function hasTokens () { return tokens.length > 0; } function assertAllConsumed(){ if (tokens.length !== 0) { throwError("is extra token not part of expression", tokens[0]); } } function statements(){ var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { return function (self){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self); } return value; }; } } } function _filterChain(){ var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter(){ return pipeFunction(angularFilter); } function validator(){ return pipeFunction(angularValidator); } function formatter(){ var token = expect(); var formatter = angularFormatter[token.text]; var argFns = []; if (!formatter) throwError('is not a valid formatter.', token); while(true) { if ((token = expect(':'))) { argFns.push(expression()); } else { return valueFn({ format:invokeFn(formatter.format), parse:invokeFn(formatter.parse) }); } } function invokeFn(fn){ return function(self, input){ var args = [input]; for ( var i = 0; i < argFns.length; i++) { args.push(argFns[i](self)); } return fn.apply(self, args); }; } } function _pipeFunction(fnScope){ var fn = functionIdent(fnScope); var argsFn = []; var token; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } return fn.apply(self, args); }; return function(){ return fnInvoke; }; } } } function expression(){ return assignment(); } function _assignment(){ var left = logicalOR(); var right; var token; if (token = expect('=')) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self){ return left.assign(self, right(self)); }; } else { return left; } } function logicalOR(){ var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND(){ var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality(){ var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational(){ var left = additive(); var token; if (token = expect('<', '>', '<=', '>=')) { left = binaryFn(left, token.fn, relational()); } return left; } function additive(){ var left = multiplicative(); var token; while(token = expect('+','-')) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative(){ var left = unary(); var token; while(token = expect('*','/','%')) { left = binaryFn(left, token.fn, unary()); } return left; } function unary(){ var token; if (expect('+')) { return primary(); } else if (token = expect('-')) { return binaryFn(ZERO, token.fn, unary()); } else if (token = expect('!')) { return unaryFn(token.fn, unary()); } else { return primary(); } } function _functionIdent(fnScope) { var token = expect(); var element = token.text.split('.'); var instance = fnScope; var key; for ( var i = 0; i < element.length; i++) { key = element[i]; if (instance) instance = instance[key]; } if (typeof instance != $function) { throwError("should be a function", token); } return instance; } function primary() { var primary; if (expect('(')) { var expression = filterChain(); consume(')'); primary = expression; } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next; while (next = expect('(', '[', '.')) { if (next.text === '(') { primary = functionCall(primary); } else if (next.text === '[') { primary = objectIndex(primary); } else if (next.text === '.') { primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field); return extend(function (self){ return getter(object(self)); }, { assign:function(self, value){ return setter(object(self), field, value); } }); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function (self){ var o = obj(self); var i = indexFn(self); return (o) ? o[i] : undefined; }, { assign:function(self, value){ return obj(self)[indexFn(self)] = value; } }); } function _functionCall(fn) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function (self){ var args = []; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } var fnPtr = fn(self) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(self, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function (self){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function (self){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self); object[keyValue.key] = value; } return object; }; } //TODO: delete me, since having watch in UI is logic in UI. (leftover form getangular) function watch () { var decl = []; while(hasTokens()) { decl.push(watchDecl()); if (!expect(';')) { assertAllConsumed(); } } assertAllConsumed(); return function (self){ for ( var i = 0; i < decl.length; i++) { var d = decl[i](self); self.addListener(d.name, d.fn); } }; } function watchDecl () { var anchorName = expect().text; consume(":"); var expressionFn; if (peekToken().text == '{') { consume("{"); expressionFn = statements(); consume("}"); } else { expressionFn = expression(); } return function(self) { return {name:anchorName, fn:expressionFn}; }; } } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && template.match(new RegExp(":" + param + "\\W"))) { urlParams[param] = true; } }); } Route.prototype = { url: function(params) { var self = this, url = this.template, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; forEachSorted(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(xhr) { this.xhr = xhr; } ResourceFactory.DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; ResourceFactory.prototype = { route: function(url, paramDefaults, actions){ var self = this; var route = new Route(url); actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; forEach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name){ var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; Resource[name] = function (a1, a2, a3) { var params = {}; var data; var callback = noop; switch(arguments.length) { case 3: callback = a3; case 2: if (isFunction(a2)) { callback = a2; //fallthrough } else { params = a1; data = a2; break; } case 1: if (isFunction(a1)) callback = a1; else if (isPostOrPut) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-3 arguments [params, data, callback], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); self.xhr( action.method, route.url(extend({}, action.params || {}, extractParams(data), params)), data, function(status, response, clear) { if (200 <= status && status < 300) { if (response) { if (action.isArray) { value.length = 0; forEach(response, function(item){ value.push(new Resource(item)); }); } else { copy(response, value); } } (callback||noop)(value); } else { throw {status: status, response:response, message: status + ": " + response}; } }, action.verifyCache); return value; }; Resource.bind = function(additionalParamDefaults){ return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2){ var params = extractParams(this); var callback = noop; switch(arguments.length) { case 2: params = a1; callback = a2; case 1: if (typeof a1 == $function) callback = a1; else params = a1; case 0: break; default: throw "Expected between 1-2 arguments [params, callback], got " + arguments.length + " arguments."; } var data = isPostOrPut ? this : undefined; Resource[name].call(this, params, data, callback); }; }); return Resource; } }; ////////////////////////////// // Browser ////////////////////////////// var XHR = window.XMLHttpRequest || function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; // default xhr headers var XHR_HEADERS = { DEFAULT: { "Accept": "application/json, text/plain, */*", "X-Requested-With": "XMLHttpRequest" }, POST: {'Content-Type': 'application/x-www-form-urlencoded'} }; /** * @private * @name Browser * * @description * Constructor for the object exposed as $browser service. * * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} body jQuery wrapped document.body. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. */ function Browser(window, document, body, XHR, $log) { var self = this, location = window.location, setTimeout = window.setTimeout; self.isMock = false; ////////////////////////////////////////////////////////////// // XHR API ////////////////////////////////////////////////////////////// var idCounter = 0; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; /** * Executes the `fn` function (supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, slice.call(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @workInProgress * @ngdoc method * @name angular.service.$browser#xhr * @methodOf angular.service.$browser * * @param {string} method Requested method (get|post|put|delete|head|json) * @param {string} url Requested url * @param {?string} post Post data to send (null if nothing to post) * @param {function(number, string)} callback Function that will be called on response * @param {object=} header additional HTTP headers to send with XHR. * Standard headers are: * <ul> * <li><tt>Content-Type</tt>: <tt>application/x-www-form-urlencoded</tt></li> * <li><tt>Accept</tt>: <tt>application/json, text/plain, &#42;/&#42;</tt></li> * <li><tt>X-Requested-With</tt>: <tt>XMLHttpRequest</tt></li> * </ul> * * @description * Send ajax request */ self.xhr = function(method, url, post, callback, headers) { outstandingRequestCount ++; if (lowercase(method) == 'json') { var callbackId = ("angular_" + Math.random() + '_' + (idCounter++)).replace(/\d\./, ''); var script = jqLite('<script>') .attr({type: 'text/javascript', src: url.replace('JSON_CALLBACK', callbackId)}); window[callbackId] = function(data){ window[callbackId] = undefined; script.remove(); completeOutstandingRequest(callback, 200, data); }; body.append(script); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(extend({}, XHR_HEADERS.DEFAULT, XHR_HEADERS[uppercase(method)] || {}, headers || {}), function(value, key) { if (value) xhr.setRequestHeader(key, value); }); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // normalize IE bug (http://bugs.jquery.com/ticket/1450) var status = xhr.status == 1223 ? 204 : xhr.status || 200; completeOutstandingRequest(callback, status, xhr.responseText); } }; xhr.send(post || ''); } }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#notifyWhenNoOutstandingRequests * @methodOf angular.service.$browser * * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#poll * @methodOf angular.service.$browser */ self.poll = function() { forEach(pollFns, function(pollFn){ pollFn(); }); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addPollFn * @methodOf angular.service.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (!pollTimeout) self.startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#startPoller * @methodOf angular.service.$browser * * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ self.startPoller = function(interval, setTimeout) { (function check(){ self.poll(); pollTimeout = setTimeout(check, interval); })(); }; ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// /** * @workInProgress * @ngdoc method * @name angular.service.$browser#setUrl * @methodOf angular.service.$browser * * @param {string} url New url * * @description * Sets browser's url */ self.setUrl = function(url) { var existingURL = location.href; if (!existingURL.match(/#/)) existingURL += '#'; if (!url.match(/#/)) url += '#'; location.href = url; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#getUrl * @methodOf angular.service.$browser * * @description * Get current browser's url * * @returns {string} Browser's url */ self.getUrl = function() { return location.href; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#onHashChange * @methodOf angular.service.$browser * * @description * Detects if browser support onhashchange events and register a listener otherwise registers * $browser poller. The `listener` will then get called when the hash changes. * * The listener gets called with either HashChangeEvent object or simple object that also contains * `oldURL` and `newURL` properties. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.service.$location $location service} to monitor hash changes in angular apps. * * @param {function(event)} listener Listener function to be called when url hash changes. * @return {function()} Returns the registered listener fn - handy if the fn is anonymous. */ self.onHashChange = function(listener) { // IE8 comp mode returns true, but doesn't support hashchange event var dm = window.document.documentMode; if ('onhashchange' in window && (isUndefined(dm) || dm >= 8)) { jqLite(window).bind('hashchange', listener); } else { var lastBrowserUrl = self.getUrl(); self.addPollFn(function() { if (lastBrowserUrl != self.getUrl()) { listener(); lastBrowserUrl = self.getUrl(); } }); } return listener; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var rawDocument = document[0]; var lastCookies = {}; var lastCookieString = ''; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#cookies * @methodOf angular.service.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function (name, value) { var cookieLength, cookieArray, cookie, i, keyValue, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#defer * @methodOf angular.service.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed via * `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { outstandingRequestCount++; setTimeout(function() { completeOutstandingRequest(fn); }, delay || 0); }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// var hoverListener = noop; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#hover * @methodOf angular.service.$browser * * @description * Set hover listener. * * @param {function(Object, boolean)} listener Function that will be called when a hover event * occurs. */ self.hover = function(listener) { hoverListener = listener; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#bind * @methodOf angular.service.$browser * * @description * Register hover function to real browser */ self.bind = function() { document.bind("mouseover", function(event){ hoverListener(jqLite(msie ? event.srcElement : event.target), true); return true; }); document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){ hoverListener(jqLite(event.target), false); return true; }); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addCss * @methodOf angular.service.$browser * * @param {string} url Url to css file * @description * Adds a stylesheet tag to the head. */ self.addCss = function(url) { var link = jqLite(rawDocument.createElement('link')); link.attr('rel', 'stylesheet'); link.attr('type', 'text/css'); link.attr('href', url); body.append(link); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addJs * @methodOf angular.service.$browser * * @param {string} url Url to js file * @param {string=} dom_id Optional id for the script tag * * @description * Adds a script tag to the head. */ self.addJs = function(url, dom_id) { var script = jqLite(rawDocument.createElement('script')); script.attr('type', 'text/javascript'); script.attr('src', url); if (dom_id) script.attr('id', dom_id); body.append(script); }; } /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Empty Elements - HTML 4.01 var emptyElements = makeMap("area,br,col,hr,img"); // Block Elements - HTML 4.01 var blockElements = makeMap("address,blockquote,center,dd,del,dir,div,dl,dt,"+ "hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul"); // Inline Elements - HTML 4.01 var inlineElements = makeMap("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,"+ "ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var"); // Elements that you can, intentionally, leave open // (and which close themselves) var closeSelfElements = makeMap("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,href,longdesc,src,usemap"); var validAttrs = extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function(){ return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( closeSelfElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = emptyElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { var value = doubleQuotedValue || singleQoutedValue || unqoutedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent || ''; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); forEach(attrs, function(value, key){ var lkey=lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @workInProgress * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as [jQuery](http://jquery.com) element. * `angular.element` is either an alias for [jQuery](http://api.jquery.com/jQuery/) function if * jQuery is loaded or a function that wraps the element or string in angular's jQuery lite * implementation. * * Real jQuery always takes precedence (as long as it was loaded before `DOMContentEvent`) * * Angular's jQuery lite implementation is a tiny API-compatible subset of jQuery which allows * angular to manipulate DOM. The jQuery lite implements only a subset of jQuery api, with the * focus on the most commonly needed functionality and minimal footprint. For this reason only a * limited number of jQuery methods, arguments and invocation styles are supported. * * NOTE: All element references in angular are always wrapped with jQuery (lite) and are never * raw DOM references. * * ## Angular's jQuery lite implements these functions: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [hasClass()](http://api.jquery.com/hasClass/) * - [parent()](http://api.jquery.com/parent/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [trigger()](http://api.jquery.com/trigger/) * * ## Additionally these methods extend the jQuery and are available in both jQuery and jQuery lite * version: * *- `scope()` - retrieves the current angular scope of the element. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return (jqId++); } function getStyle(element) { var current = {}, style = element[0].style, value, name, i; if (typeof style.length == 'number') { for(i = 0; i < style.length; i++) { name = style[i]; current[name] = style[name]; } } else { for (name in style) { value = style[name]; if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false') current[name] = value; } } return current; } if (msie) { extend(JQLite.prototype, { text: function(value) { var e = this[0]; // NodeType == 3 is text node if (e.nodeType == 3) { if (isDefined(value)) e.nodeValue = value; return e.nodeValue; } else { if (isDefined(value)) e.innerText = value; return e.innerText; } } }); } ///////////////////////////////////////////// function jqLiteWrap(element) { if (isString(element) && element.charAt(0) != '<') { throw new Error('selectors not implemented'); } return new JQLite(element); } function JQLite(element) { if (element instanceof JQLite) { return element; } else if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteRemoveData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { forEach(cache.bind || {}, function(fn, type){ removeEventListenerFn(element, type, fn); }); delete jqCache[cacheId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteData(element, key, value) { var cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : null; } } function JQLiteHasClass(element, selector, _) { // the argument '_' is important, since it makes the function have 3 arguments, which // is neede for delegate function to realize the this is a getter. var className = " " + selector + " "; return ((" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1); } function JQLiteRemoveClass(element, selector) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + selector + " ", "") ); } function JQLiteAddClass(element, selector ) { if (!JQLiteHasClass(element, selector)) { element.className = trim(element.className + ' ' + selector); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. jqLiteWrap(window).bind('load', trigger); // fallback to window.onload for others }, toString: function(){ var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// forEach({ data: JQLiteData, scope: function(element) { var scope; while (element && !(scope = jqLite(element).data($$scope))) { element = element.parentNode; } return scope; }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { if (isDefined(value)) { element.style[name] = value; } else { return element.style[name]; } }, attr: function(element, name, value){ if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined return element.getAttribute(name, 2); } }, text: extend((msie < 9) ? function(element, value) { // NodeType == 3 is text node if (element.nodeType == 3) { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } else { if (isUndefined(value)) return element.innerText; element.innerText = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; if ((fn.length == 2 ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { for (key in arg1) { fn(this[i], key, arg1[key]); } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function(element, type, fn){ var bind = JQLiteData(element, 'bind'), eventHandler; if (!bind) JQLiteData(element, 'bind', bind = {}); forEach(type.split(' '), function(type){ eventHandler = bind[type]; if (!eventHandler) { bind[type] = eventHandler = function(event) { if (!event.preventDefault) { event.preventDefault = function(){ event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } forEach(eventHandler.fns, function(fn){ fn.call(element, event); }); }; eventHandler.fns = []; addEventListenerFn(element, type, eventHandler); } eventHandler.fns.push(fn); }); }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); var angularGlobal = { 'typeOf':function(obj){ if (obj === null) return $null; var type = typeof obj; if (type == $object) { if (obj instanceof Array) return $array; if (isDate(obj)) return $date; if (obj.nodeType == 1) return $element; } return type; } }; /** * @ngdoc overview * @name angular.Object * @function * * @description * A namespace for utility functions used to work with JavaScript objects. These functions are * exposed in two ways: * * __* Angular expressions:__ Functions are bound to all objects and augment the Object type. The * names of these methods are prefixed with the '$' character in order to minimize naming collisions. * To call a method, invoke the function without the first argument, e.g, `myObject.$foo(param2)`. * * __* JavaScript code:__ Functions don't augment the Object type and must be invoked as functions of * `angular.Object` as `angular.Object.foo(myObject, param2)`. * * * {@link angular.Object.copy angular.Object.copy()} - Creates a deep copy of the source parameter * * {@link angular.Object.equals angular.Object.equals()} - Determines if two objects or values are * equivalent * * {@link angular.Object.size angular.Object.size()} - Determines the number of elements in * strings, arrays, and objects. */ var angularCollection = { 'copy': copy, 'size': size, 'equals': equals }; var angularObject = { 'extend': extend }; /** * @ngdoc overview * @name angular.Array * * @description * A namespace for utility functions for the manipulation of JavaScript Array objects. * * These functions are exposed in two ways: * * * __Angular expressions:__ Functions are bound to the Array objects and augment the Array type as * array methods. The names of these methods are prefixed with $ character to minimize naming * collisions. To call a method, invoke myArrayObject.$foo(params). * * Because Array type is a subtype of the Object type, all angular.Object functions augment * theArray type in angular expressions as well. * * * __JavaScript code:__ Functions don't augment the Array type and must be invoked as functions of * `angular.Array` as `angular.Array.foo(myArrayObject, params)`. * * The following APIs are built-in to the angular Array object: * * * {@link angular.Array.add angular.Array.add()} - Optionally adds a new element to an array. * * {@link angular.Array.count angular.Array.count()} - Determines the number of elements in an * array. * * {@link angular.Array.filter angular.Array.filter()} - Returns a subset of items as a new array. * * {@link angular.Array.indexOf angular.Array.indexOf()} - Determines the index of an array value. * * {@link angular.Array.limitTo angular.Array.limitTo()} - Creates a new array off the front or * back of an existing array. * * {@link angular.Array.orderBy angular.Array.orderBy()} - Orders array elements * * {@link angular.Array.remove angular.Array.remove()} - Removes array elements * * {@link angular.Array.sum angular.Array.sum()} - Sums the number elements in an array */ var angularArray = { /** * @ngdoc function * @name angular.Array.indexOf * @function * * @description * Determines the index of `value` in `array`. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Array to search. * @param {*} value Value to search for. * @returns {number} The position of the element in `array`. The position is 0-based. `-1` is returned if the value can't be found. * * @example <doc:example> <doc:source> <div ng:init="books = ['Moby Dick', 'Great Gatsby', 'Romeo and Juliet']"></div> <input name='bookName' value='Romeo and Juliet'> <br> Index of '{{bookName}}' in the list {{books}} is <em>{{books.$indexOf(bookName)}}</em>. </doc:source> <doc:scenario> it('should correctly calculate the initial index', function() { expect(binding('books.$indexOf(bookName)')).toBe('2'); }); it('should recalculate', function() { input('bookName').enter('foo'); expect(binding('books.$indexOf(bookName)')).toBe('-1'); input('bookName').enter('Moby Dick'); expect(binding('books.$indexOf(bookName)')).toBe('0'); }); </doc:scenario> </doc:example> */ 'indexOf': indexOf, /** * @ngdoc function * @name angular.Array.sum * @function * * @description * This function calculates the sum of all numbers in `array`. If the `expressions` is supplied, * it is evaluated once for each element in `array` and then the sum of these values is returned. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The source array. * @param {(string|function())=} expression Angular expression or a function to be evaluated for each * element in `array`. The array element becomes the `this` during the evaluation. * @returns {number} Sum of items in the array. * * @example <doc:example> <doc:source> <table ng:init="invoice= {items:[{qty:10, description:'gadget', cost:9.95}]}"> <tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr> <tr ng:repeat="item in invoice.items"> <td><input name="item.qty" value="1" size="4" ng:required ng:validate="integer"></td> <td><input name="item.description"></td> <td><input name="item.cost" value="0.00" ng:required ng:validate="number" size="6"></td> <td>{{item.qty * item.cost | currency}}</td> <td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td> </tr> <tr> <td><a href ng:click="invoice.items.$add()">add item</a></td> <td></td> <td>Total:</td> <td>{{invoice.items.$sum('qty*cost') | currency}}</td> </tr> </table> </doc:source> <doc:scenario> //TODO: these specs are lame because I had to work around issues #164 and #167 it('should initialize and calculate the totals', function() { expect(repeater('.doc-example-live table tr', 'item in invoice.items').count()).toBe(3); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(1)). toEqual(['$99.50']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); }); it('should add an entry and recalculate', function() { element('.doc-example-live a:contains("add item")').click(); using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20'); using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100'); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(2)). toEqual(['$2,000.00']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50'); }); </doc:scenario> </doc:example> */ 'sum':function(array, expression) { var fn = angular['Function']['compile'](expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, /** * @ngdoc function * @name angular.Array.remove * @function * * @description * Modifies `array` by removing an element from it. The element will be looked up using the * {@link angular.Array.indexOf indexOf} function on the `array` and only the first instance of * the element will be removed. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Array from which an element should be removed. * @param {*} value Element to be removed. * @returns {*} The removed element. * * @example <doc:example> <doc:source> <ul ng:init="tasks=['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']"> <li ng:repeat="task in tasks"> {{task}} [<a href="" ng:click="tasks.$remove(task)">X</a>] </li> </ul> <hr/> tasks = {{tasks}} </doc:source> <doc:scenario> it('should initialize the task list with for tasks', function() { expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(4); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']); }); it('should initialize the task list with for tasks', function() { element('.doc-example-live ul li a:contains("X"):first').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(3); element('.doc-example-live ul li a:contains("X"):last').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(2); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Read Documentation', 'Check out demos']); }); </doc:scenario> </doc:example> */ 'remove':function(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, /** * @ngdoc function * @name angular.Array.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input name="searchText"/> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(searchText)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input name="search.$"/> <br> Name only <input name="search.name"/><br> Phone only <input name="search.phone"/><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(search)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function(){ var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function(){ var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case $function: predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, /** * @workInProgress * @ngdoc function * @name angular.Array.add * @function * * @description * `add` is a function similar to JavaScript's `Array#push` method, in that it appends a new * element to an array. The difference is that the value being added is optional and defaults to * an empty object. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array expand. * @param {*=} [value={}] The value to be added. * @returns {Array} The expanded array. * * @TODO simplify the example. * * @example * This example shows how an initially empty array can be filled with objects created from user * input via the `$add` method. <doc:example> <doc:source> [<a href="" ng:click="people.$add()">add empty</a>] [<a href="" ng:click="people.$add({name:'John', sex:'male'})">add 'John'</a>] [<a href="" ng:click="people.$add({name:'Mary', sex:'female'})">add 'Mary'</a>] <ul ng:init="people=[]"> <li ng:repeat="person in people"> <input name="person.name"> <select name="person.sex"> <option value="">--chose one--</option> <option>male</option> <option>female</option> </select> [<a href="" ng:click="people.$remove(person)">X</a>] </li> </ul> <pre>people = {{people}}</pre> </doc:source> <doc:scenario> beforeEach(function() { expect(binding('people')).toBe('people = []'); }); it('should create an empty record when "add empty" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); expect(binding('people')).toBe('people = [{\n "name":"",\n "sex":null}]'); }); it('should create a "John" record when "add \'John\'" is clicked', function() { element('.doc-example-live a:contains("add \'John\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"John",\n "sex":"male"}]'); }); it('should create a "Mary" record when "add \'Mary\'" is clicked', function() { element('.doc-example-live a:contains("add \'Mary\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"Mary",\n "sex":"female"}]'); }); it('should delete a record when "X" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); element('.doc-example-live li a:contains("X"):first').click(); expect(binding('people')).toBe('people = []'); }); </doc:scenario> </doc:example> */ 'add':function(array, value) { array.push(isUndefined(value)? {} : value); return array; }, /** * @ngdoc function * @name angular.Array.count * @function * * @description * Determines the number of elements in an array. Optionally it will count only those elements * for which the `condition` evaluates to `true`. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array to count elements in. * @param {(function()|string)=} condition A function to be evaluated or angular expression to be * compiled and evaluated. The element that is currently being iterated over, is exposed to * the `condition` as `this`. * @returns {number} Number of elements in the array (for which the condition evaluates to true). * * @example <doc:example> <doc:source> <pre ng:init="items = [{name:'knife', points:1}, {name:'fork', points:3}, {name:'spoon', points:1}]"></pre> <ul> <li ng:repeat="item in items"> {{item.name}}: points= <input type="text" name="item.points"/> <!-- id="item{{$index}} --> </li> </ul> <p>Number of items which have one point: <em>{{ items.$count('points==1') }}</em></p> <p>Number of items which have more than one point: <em>{{items.$count('points&gt;1')}}</em></p> </doc:source> <doc:scenario> it('should calculate counts', function() { expect(binding('items.$count(\'points==1\')')).toEqual(2); expect(binding('items.$count(\'points>1\')')).toEqual(1); }); it('should recalculate when updated', function() { using('.doc-example-live li:first-child').input('item.points').enter('23'); expect(binding('items.$count(\'points==1\')')).toEqual(1); expect(binding('items.$count(\'points>1\')')).toEqual(2); }); </doc:scenario> </doc:example> */ 'count':function(array, condition) { if (!condition) return array.length; var fn = angular['Function']['compile'](condition), count = 0; forEach(array, function(value){ if (fn(value)) { count ++; } }); return count; }, /** * @ngdoc function * @name angular.Array.orderBy * @function * * @description * Orders `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator * - `string`: angular expression which evaluates to an object to order by, such as 'name' to * sort by a property called 'name'. Optionally prefixed with `+` or `-` to control ascending * or descending sort order (e.g. +name or -name). * - `Array`: array of function or string predicates, such that a first predicate in the array * is used for sorting, but when the items are equivalent next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]"></div> <pre>Sorting predicate = {{predicate}}</pre> <hr/> <table ng:init="predicate='-age'"> <tr> <th><a href="" ng:click="predicate = 'name'">Name</a> (<a href ng:click="predicate = '-name'">^</a>)</th> <th><a href="" ng:click="predicate = 'phone'">Phone</a> (<a href ng:click="predicate = '-phone'">^</a>)</th> <th><a href="" ng:click="predicate = 'age'">Age</a> (<a href ng:click="predicate = '-age'">^</a>)</th> <tr> <tr ng:repeat="friend in friends.$orderBy(predicate)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('Sorting predicate = -age'); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")+a:contains("^")').click(); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ //TODO: WTH is descend param for and how/when it should be used, how is it affected by +/- in // predicate? the code below is impossible to read and specs are not very good. 'orderBy':function(array, expression, descend) { expression = isArray(expression) ? expression: [expression]; expression = map(expression, function($){ var descending = false, get = $ || identity; if (isString($)) { if (($.charAt(0) == '+' || $.charAt(0) == '-')) { descending = $.charAt(0) == '-'; $ = $.substring(1); } get = expressionCompile($).fnSelf; } return reverse(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverse(comparator, descend)); function comparator(o1, o2){ for ( var i = 0; i < expression.length; i++) { var comp = expression[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverse(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }, /** * @ngdoc function * @name angular.Array.limitTo * @function * * @description * Creates a new array containing only the first, or last `limit` number of elements of the * source `array`. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the number is positive, the * first `limit` items from the source array will be copied, if the number is negative, the * last `limit` items will be copied. * @returns {Array} A new sub-array of length `limit`. * * @example <doc:example> <doc:source> <div ng:init="numbers = [1,2,3,4,5,6,7,8,9]"> Limit [1,2,3,4,5,6,7,8,9] to: <input name="limit" value="3"/> <p>Output: {{ numbers.$limitTo(limit) | json }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[name=limit]').val()).toBe('3'); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[7,8,9]'); }); </doc:scenario> </doc:example> */ limitTo: function(array, limit) { limit = parseInt(limit, 10); var out = [], i, n; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } }; var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/; var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, /** * Tries to convert input to date and if successful returns the date, otherwise returns the input. * @param {string} string * @return {(Date|string)} */ 'toDate':function(string){ var match; if (isString(string) && (match = string.match(R_ISO8061_STR))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0); return date; } return string; } }; var angularDate = { 'toString':function(date){ if (!date) return date; var isoString = date.toISOString ? date.toISOString() : ''; return (isoString.length==24) ? isoString : padNumber(date.getUTCFullYear(), 4) + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + '.' + padNumber(date.getUTCMilliseconds(), 3) + 'Z'; } }; var angularFunction = { 'compile':function(expression) { if (isFunction(expression)){ return expression; } else if (expression){ return expressionCompile(expression).fnSelf; } else { return identity; } } }; function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; forEach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal]); defineApi('Collection', [angularGlobal, angularCollection]); defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); //IE bug angular['Date']['toString'] = angularDate['toString']; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); /** * @workInProgress * @ngdoc overview * @name angular.filter * @description * * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * Following is the list of built-in angular filters: * * * {@link angular.filter.currency currency} * * {@link angular.filter.date date} * * {@link angular.filter.html html} * * {@link angular.filter.json json} * * {@link angular.filter.linky linky} * * {@link angular.filter.lowercase lowercase} * * {@link angular.filter.number number} * * {@link angular.filter.uppercase uppercase} * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @workInProgress * @ngdoc filter * @name angular.filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). * * @param {number} amount Input to filter. * @returns {string} Formated number. * * @css ng-format-negative * When the value is negative, this css class is applied to the binding making it by default red. * * @example <doc:example> <doc:source> <input type="text" name="amount" value="1234.56"/> <br/> {{amount | currency}} </doc:source> <doc:scenario> it('should init with 1234.56', function(){ expect(binding('amount | currency')).toBe('$1,234.56'); }); it('should update', function(){ input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('$-1,234.00'); expect(element('.doc-example-live .ng-binding').attr('className')). toMatch(/ng-format-negative/); }); </doc:scenario> </doc:example> */ angularFilter.currency = function(amount){ this.$element.toggleClass('ng-format-negative', amount < 0); return '$' + angularFilter['number'].apply(this, [amount, 2]); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.number * @function * * @description * Formats a number as text. * * If the input is not a number empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> Enter number: <input name='val' value='1234.56789' /><br/> Default formatting: {{val | number}}<br/> No fractions: {{val | number:0}}<br/> Negative number: {{-val | number:4}} </doc:source> <doc:scenario> it('should format numbers', function(){ expect(binding('val | number')).toBe('1,234.57'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function(){ input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.33'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ angularFilter.number = function(number, fractionSize){ if (isNaN(number) || !isFinite(number)) { return ''; } fractionSize = typeof fractionSize == $undefined ? 2 : fractionSize; var isNegative = number < 0; number = Math.abs(number); var pow = Math.pow(10, fractionSize); var text = "" + Math.round(number * pow); var whole = text.substring(0, text.length - fractionSize); whole = whole || '0'; var frc = text.substring(text.length - fractionSize); text = isNegative ? '-' : ''; for (var i = 0; i < whole.length; i++) { if ((whole.length - i)%3 === 0 && i !== 0) { text += ','; } text += whole.charAt(i); } if (fractionSize > 0) { for (var j = frc.length; j < fractionSize; j++) { frc += '0'; } text += '.' + frc.substring(0, fractionSize); } return text; }; function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), a: function(date){return date.getHours() < 12 ? 'am' : 'pm';}, Z: function(date){ var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } }; var DATE_FORMATS_SPLIT = /([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/; var NUMBER_STRING = /^\d+$/; /** * @workInProgress * @ngdoc filter * @name angular.filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year e.g. 2010 * * `'yy'`: 2 digit representation of year, padded (00-99) * * `'MM'`: Month in year, padded (01‒12) * * `'M'`: Month in year (1‒12) * * `'dd'`: Day in month, padded (01‒31) * * `'d'`: Day in month (1-31) * * `'HH'`: Hour in day, padded (00‒23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01‒12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00‒59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00‒59) * * `'s'`: Second in minute (0‒59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200‒1200) * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). * @param {string=} format Formatting rules. If not specified, Date#toLocaleDateString is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> </doc:source> <doc:scenario> it('should format date', function(){ expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(am|pm)/); }); </doc:scenario> </doc:example> */ angularFilter.date = function(date, format) { if (isString(date)) { if (NUMBER_STRING.test(date)) { date = parseInt(date, 10); } else { date = angularString.toDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } var text = date.toLocaleDateString(), fn; if (format && isString(format)) { text = ''; var parts = [], match; while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date) : value; }); } return text; }; /** * @workInProgress * @ngdoc filter * @name angular.filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * @css ng-monospace Always applied to the encapsulating element. * * @example: <doc:example> <doc:source> <input type="text" name="objTxt" value="{a:1, b:[]}" ng:eval="obj = $eval(objTxt)"/> <pre>{{ obj | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding('obj | json')).toBe('{\n "a":1,\n "b":[]}'); }); it('should update', function() { input('objTxt').enter('[1, 2, 3]'); expect(binding('obj | json')).toBe('[1,2,3]'); }); </doc:scenario> </doc:example> * */ angularFilter.json = function(object) { this.$element.addClass("ng-monospace"); return toJson(object, true); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.lowercase * @function * * @see angular.lowercase */ angularFilter.lowercase = lowercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.uppercase * @function * * @see angular.uppercase */ angularFilter.uppercase = uppercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.html * @function * * @description * Prevents the input from getting escaped by angular. By default the input is sanitized and * inserted into the DOM as is. * * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses * the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this * option is strongly discouraged and should be used only if you absolutely trust the input being * filtered and you can't get the content through the sanitizer. * * @param {string} html Html input. * @param {string=} option If 'unsafe' then do not sanitize the HTML input. * @returns {string} Sanitized or raw html. * * @example <doc:example> <doc:source> Snippet: <textarea name="snippet" cols="60" rows="3"> &lt;p style="color:blue"&gt;an html &lt;em onmouseover="this.textContent='PWN3D!'"&gt;click here&lt;/em&gt; snippet&lt;/p&gt;</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng:bind="snippet | html"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | html"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng:bind="snippet | html:'unsafe'"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet | html:'unsafe'"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should sanitize the html snippet ', function(){ expect(using('#html-filter').binding('snippet | html')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should escape snippet without any filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function(){ input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>'); expect(using('#escaped-html').binding('snippet')).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>'); }); </doc:scenario> </doc:example> */ angularFilter.html = function(html, option){ return new HTML(html, option); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plane email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example <doc:example> <doc:source> Snippet: <textarea name="snippet" cols="60" rows="3"> Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, another@somewhere.org, and one more: ftp://127.0.0.1/.</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng:bind="snippet | linky"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should linkify the snippet with urls', function(){ expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:\n' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,\n' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,\n' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function(){ input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); </doc:scenario> </doc:example> */ //TODO: externalize all regexps angularFilter.linky = function(text){ if (!text) return text; var URL = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/; var match; var raw = text; var html = []; var writer = htmlSanitizeWriter(html); var url; var i; while (match=raw.match(URL)) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2]==match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(/^mailto:/, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return new HTML(html.join('')); }; /** * @workInProgress * @ngdoc overview * @name angular.formatter * @description * * Formatters are used for translating data formats between those used in for display and those used * for storage. * * Following is the list of built-in angular formatters: * * * {@link angular.formatter.boolean boolean} - Formats user input in boolean format * * {@link angular.formatter.index index} - Manages indexing into an HTML select widget * * {@link angular.formatter.json json} - Formats user input in JSON format * * {@link angular.formatter.list list} - Formats user input string as an array * * {@link angular.formatter.number} - Formats user input strings as a number * * {@link angular.formatter.trim} - Trims extras spaces from end of user input * * For more information about how angular formatters work, and how to create your own formatters, * see {@link guide/dev_guide.templates.formatters Understanding Angular Formatters} in the angular * Developer Guide. */ function formatter(format, parse) {return {'format':format, 'parse':parse || format};} function toString(obj) { return (isDefined(obj) && obj !== null) ? "" + obj : obj; } var NUMBER = /^\s*[-+]?\d*(\.\d*)?\s*$/; angularFormatter.noop = formatter(identity, identity); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.json * * @description * Formats the user input as JSON text. * * @returns {?string} A JSON string representation of the model. * * @example <doc:example> <doc:source> <div ng:init="data={name:'misko', project:'angular'}"> <input type="text" size='50' name="data" ng:format="json"/> <pre>data={{data}}</pre> </div> </doc:source> <doc:scenario> it('should format json', function(){ expect(binding('data')).toEqual('data={\n \"name\":\"misko\",\n \"project\":\"angular\"}'); input('data').enter('{}'); expect(binding('data')).toEqual('data={\n }'); }); </doc:scenario> </doc:example> */ angularFormatter.json = formatter(toJson, function(value){ return fromJson(value || 'null'); }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.boolean * * @description * Use boolean formatter if you wish to store the data as boolean. * * @returns {boolean} Converts to `true` unless user enters (blank), `f`, `false`, `0`, `no`, `[]`. * * @example <doc:example> <doc:source> Enter truthy text: <input type="text" name="value" ng:format="boolean" value="no"/> <input type="checkbox" name="value"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format boolean', function(){ expect(binding('value')).toEqual('value=false'); input('value').enter('truthy'); expect(binding('value')).toEqual('value=true'); }); </doc:scenario> </doc:example> */ angularFormatter['boolean'] = formatter(toString, toBoolean); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.number * * @description * Use number formatter if you wish to convert the user entered string to a number. * * @returns {number} Number from the parsed string. * * @example <doc:example> <doc:source> Enter valid number: <input type="text" name="value" ng:format="number" value="1234"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format numbers', function(){ expect(binding('value')).toEqual('value=1234'); input('value').enter('5678'); expect(binding('value')).toEqual('value=5678'); }); </doc:scenario> </doc:example> */ angularFormatter.number = formatter(toString, function(obj){ if (obj == null || NUMBER.exec(obj)) { return obj===null || obj === '' ? null : 1*obj; } else { throw "Not a number"; } }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.list * * @description * Use list formatter if you wish to convert the user entered string to an array. * * @returns {Array} Array parsed from the entered string. * * @example <doc:example> <doc:source> Enter a list of items: <input type="text" name="value" ng:format="list" value=" chair ,, table"/> <input type="text" name="value" ng:format="list"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format lists', function(){ expect(binding('value')).toEqual('value=["chair","table"]'); this.addFutureAction('change to XYZ', function($window, $document, done){ $document.elements('.doc-example-live :input:last').val(',,a,b,').trigger('change'); done(); }); expect(binding('value')).toEqual('value=["a","b"]'); }); </doc:scenario> </doc:example> */ angularFormatter.list = formatter( function(obj) { return obj ? obj.join(", ") : obj; }, function(value) { var list = []; forEach((value || '').split(','), function(item){ item = trim(item); if (item) list.push(item); }); return list; } ); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.trim * * @description * Use trim formatter if you wish to trim extra spaces in user text. * * @returns {String} Trim excess leading and trailing space. * * @example <doc:example> <doc:source> Enter text with leading/trailing spaces: <input type="text" name="value" ng:format="trim" value=" book "/> <input type="text" name="value" ng:format="trim"/> <pre>value={{value|json}}</pre> </doc:source> <doc:scenario> it('should format trim', function(){ expect(binding('value')).toEqual('value="book"'); this.addFutureAction('change to XYZ', function($window, $document, done){ $document.elements('.doc-example-live :input:last').val(' text ').trigger('change'); done(); }); expect(binding('value')).toEqual('value="text"'); }); </doc:scenario> </doc:example> */ angularFormatter.trim = formatter( function(obj) { return obj ? trim("" + obj) : ""; } ); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.index * @description * Index formatter is meant to be used with `select` input widget. It is useful when one needs * to select from a set of objects. To create pull-down one can iterate over the array of object * to build the UI. However the value of the pull-down must be a string. This means that when on * object is selected form the pull-down, the pull-down value is a string which needs to be * converted back to an object. This conversion from string to on object is not possible, at best * the converted object is a copy of the original object. To solve this issue we create a pull-down * where the value strings are an index of the object in the array. When pull-down is selected the * index can be used to look up the original user object. * * @inputType select * @param {array} array to be used for selecting an object. * @returns {object} object which is located at the selected position. * * @example <doc:example> <doc:source> <script> function DemoCntl(){ this.users = [ {name:'guest', password:'guest'}, {name:'user', password:'123'}, {name:'admin', password:'abc'} ]; } </script> <div ng:controller="DemoCntl"> User: <select name="currentUser" ng:format="index:users"> <option ng:repeat="user in users" value="{{$index}}">{{user.name}}</option> </select> <select name="currentUser" ng:format="index:users"> <option ng:repeat="user in users" value="{{$index}}">{{user.name}}</option> </select> user={{currentUser.name}}<br/> password={{currentUser.password}}<br/> </doc:source> <doc:scenario> it('should retrieve object by index', function(){ expect(binding('currentUser.password')).toEqual('guest'); select('currentUser').option('2'); expect(binding('currentUser.password')).toEqual('abc'); }); </doc:scenario> </doc:example> */ angularFormatter.index = formatter( function(object, array){ return '' + indexOf(array || [], object); }, function(index, array){ return (array||[])[index]; } ); /** * @workInProgress * @ngdoc overview * @name angular.validator * @description * * Most of the built-in angular validators are used to check user input against defined types or * patterns. You can easily create your own custom validators as well. * * Following is the list of built-in angular validators: * * * {@link angular.validator.asynchronous asynchronous()} - Provides asynchronous validation via a * callback function. * * {@link angular.validator.date date()} - Checks user input against default date format: * "MM/DD/YYYY" * * {@link angular.validator.email email()} - Validates that user input is a well-formed email * address. * * {@link angular.validator.integer integer()} - Validates that user input is an integer * * {@link angular.validator.json json()} - Validates that user input is valid JSON * * {@link angular.validator.number number()} - Validates that user input is a number * * {@link angular.validator.phone phone()} - Validates that user input matches the pattern * "1(123)123-1234" * * {@link angular.validator.regexp regexp()} - Restricts valid input to a specified regular * expression pattern * * {@link angular.validator.url url()} - Validates that user input is a well-formed URL. * * For more information about how angular validators work, and how to create your own validators, * see {@link guide/dev_guide.templates.validators Understanding Angular Validators} in the angular * Developer Guide. */ extend(angularValidator, { 'noop': function() { return null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.regexp * @description * Use regexp validator to restrict the input to any Regular Expression. * * @param {string} value value to validate * @param {string|regexp} expression regular expression. * @param {string=} msg error message to display. * @css ng-validation-error * * @example <doc:example> <doc:source> <script> function Cntl(){ this.ssnRegExp = /^\d\d\d-\d\d-\d\d\d\d$/; } </script> Enter valid SSN: <div ng:controller="Cntl"> <input name="ssn" value="123-45-6789" ng:validate="regexp:ssnRegExp" > </div> </doc:source> <doc:scenario> it('should invalidate non ssn', function(){ var textBox = element('.doc-example-live :input'); expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); expect(textBox.val()).toEqual('123-45-6789'); input('ssn').enter('123-45-67890'); expect(textBox.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'regexp': function(value, regexp, msg) { if (!value.match(regexp)) { return msg || "Value does not match expected format " + regexp + "."; } else { return null; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.number * @description * Use number validator to restrict the input to numbers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example <doc:example> <doc:source> Enter number: <input name="n1" ng:validate="number" > <br> Enter number greater than 10: <input name="n2" ng:validate="number:10" > <br> Enter number between 100 and 200: <input name="n3" ng:validate="number:100:200" > <br> </doc:source> <doc:scenario> it('should invalidate number', function(){ var n1 = element('.doc-example-live :input[name=n1]'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('n1').enter('1.x'); expect(n1.attr('className')).toMatch(/ng-validation-error/); var n2 = element('.doc-example-live :input[name=n2]'); expect(n2.attr('className')).not().toMatch(/ng-validation-error/); input('n2').enter('9'); expect(n2.attr('className')).toMatch(/ng-validation-error/); var n3 = element('.doc-example-live :input[name=n3]'); expect(n3.attr('className')).not().toMatch(/ng-validation-error/); input('n3').enter('201'); expect(n3.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'number': function(value, min, max) { var num = 1 * value; if (num == value) { if (typeof min != $undefined && num < min) { return "Value can not be less than " + min + "."; } if (typeof min != $undefined && num > max) { return "Value can not be greater than " + max + "."; } return null; } else { return "Not a number"; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.integer * @description * Use number validator to restrict the input to integers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example <doc:example> <doc:source> Enter integer: <input name="n1" ng:validate="integer" > <br> Enter integer equal or greater than 10: <input name="n2" ng:validate="integer:10" > <br> Enter integer between 100 and 200 (inclusive): <input name="n3" ng:validate="integer:100:200" > <br> </doc:source> <doc:scenario> it('should invalidate integer', function(){ var n1 = element('.doc-example-live :input[name=n1]'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('n1').enter('1.1'); expect(n1.attr('className')).toMatch(/ng-validation-error/); var n2 = element('.doc-example-live :input[name=n2]'); expect(n2.attr('className')).not().toMatch(/ng-validation-error/); input('n2').enter('10.1'); expect(n2.attr('className')).toMatch(/ng-validation-error/); var n3 = element('.doc-example-live :input[name=n3]'); expect(n3.attr('className')).not().toMatch(/ng-validation-error/); input('n3').enter('100.1'); expect(n3.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ 'integer': function(value, min, max) { var numberError = angularValidator['number'](value, min, max); if (numberError) return numberError; if (!("" + value).match(/^\s*[\d+]*\s*$/) || value != Math.round(value)) { return "Not a whole number"; } return null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.date * @description * Use date validator to restrict the user input to a valid date * in format in format MM/DD/YYYY. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid date: <input name="text" value="1/1/2009" ng:validate="date" > </doc:source> <doc:scenario> it('should invalidate date', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('123/123/123'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'date': function(value) { var fields = /^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(value); var date = fields ? new Date(fields[3], fields[1]-1, fields[2]) : 0; return (date && date.getFullYear() == fields[3] && date.getMonth() == fields[1]-1 && date.getDate() == fields[2]) ? null : "Value is not a date. (Expecting format: 12/31/2009)."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.email * @description * Use email validator if you wist to restrict the user input to a valid email. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid email: <input name="text" ng:validate="email" value="me@example.com"> </doc:source> <doc:scenario> it('should invalidate email', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('a@b.c'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'email': function(value) { if (value.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) { return null; } return "Email needs to be in username@host.com format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.phone * @description * Use phone validator to restrict the input phone numbers. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid phone number: <input name="text" value="1(234)567-8901" ng:validate="phone" > </doc:source> <doc:scenario> it('should invalidate phone', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('+12345678'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'phone': function(value) { if (value.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)) { return null; } if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) { return null; } return "Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.url * @description * Use phone validator to restrict the input URLs. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid URL: <input name="text" value="http://example.com/abc.html" size="40" ng:validate="url" > </doc:source> <doc:scenario> it('should invalidate url', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('abc://server/path'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'url': function(value) { if (value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) { return null; } return "URL needs to be in http://server[:port]/path format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.json * @description * Use json validator if you wish to restrict the user input to a valid JSON. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> <textarea name="json" cols="60" rows="5" ng:validate="json"> {name:'abc'} </textarea> </doc:source> <doc:scenario> it('should invalidate json', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('json').enter('{name}'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'json': function(value) { try { fromJson(value); return null; } catch (e) { return e.toString(); } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.asynchronous * @description * Use asynchronous validator if the validation can not be computed * immediately, but is provided through a callback. The widget * automatically shows a spinning indicator while the validity of * the widget is computed. This validator caches the result. * * @param {string} value value to validate * @param {function(inputToValidate,validationDone)} validate function to call to validate the state * of the input. * @param {function(data)=} [update=noop] function to call when state of the * validator changes * * @paramDescription * The `validate` function (specified by you) is called as * `validate(inputToValidate, validationDone)`: * * * `inputToValidate`: value of the input box. * * `validationDone`: `function(error, data){...}` * * `error`: error text to display if validation fails * * `data`: data object to pass to update function * * The `update` function is optionally specified by you and is * called by <angular/> on input change. Since the * asynchronous validator caches the results, the update * function can be called without a call to `validate` * function. The function is called as `update(data)`: * * * `data`: data object as passed from validate function * * @css ng-input-indicator-wait, ng-validation-error * * @example <doc:example> <doc:source> <script> function MyCntl(){ this.myValidator = function (inputToValidate, validationDone) { setTimeout(function(){ validationDone(inputToValidate.length % 2); }, 500); } } </script> This input is validated asynchronously: <div ng:controller="MyCntl"> <input name="text" ng:validate="asynchronous:myValidator"> </div> </doc:source> <doc:scenario> it('should change color in delayed way', function(){ var textBox = element('.doc-example-live :input'); expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('X'); expect(textBox.attr('className')).toMatch(/ng-input-indicator-wait/); sleep(.6); expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); expect(textBox.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ /* * cache is attached to the element * cache: { * inputs : { * 'user input': { * response: server response, * error: validation error * }, * current: 'current input' * } * */ 'asynchronous': function(input, asynchronousFn, updateFn) { if (!input) return; var scope = this; var element = scope.$element; var cache = element.data('$asyncValidator'); if (!cache) { element.data('$asyncValidator', cache = {inputs:{}}); } cache.current = input; var inputState = cache.inputs[input], $invalidWidgets = scope.$service('$invalidWidgets'); if (!inputState) { cache.inputs[input] = inputState = { inFlight: true }; $invalidWidgets.markInvalid(scope.$element); element.addClass('ng-input-indicator-wait'); asynchronousFn(input, function(error, data) { inputState.response = data; inputState.error = error; inputState.inFlight = false; if (cache.current == input) { element.removeClass('ng-input-indicator-wait'); $invalidWidgets.markValid(element); } element.data($$validate)(); scope.$service('$updateView')(); }); } else if (inputState.inFlight) { // request in flight, mark widget invalid, but don't show it to user $invalidWidgets.markInvalid(scope.$element); } else { (updateFn||noop)(inputState.response); } return inputState.error; } }); /** * @workInProgress * @ngdoc service * @name angular.service.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ angularServiceInject('$cookieStore', function($store) { return { /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#get * @methodOf angular.service.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return fromJson($store[key]); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#put * @methodOf angular.service.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $store[key] = toJson(value); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#remove * @methodOf angular.service.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $store[key]; } }; }, ['$cookies']); /** * @workInProgress * @ngdoc service * @name angular.service.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ angularServiceInject('$cookies', function($browser) { var rootScope = this, cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) rootScope.$eval(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. this.$onEval(PRIORITY_LAST, push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push(){ var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!isString(value)) { if (isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }, ['$browser']); /** * @workInProgress * @ngdoc service * @name angular.service.$defer * @requires $browser * @requires $exceptionHandler * @requires $updateView * * @description * Delegates to {@link angular.service.$browser $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.service.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. */ angularServiceInject('$defer', function($browser, $exceptionHandler, $updateView) { return function(fn, delay) { $browser.defer(function() { try { fn(); } catch(e) { $exceptionHandler(e); } finally { $updateView(); } }, delay); }; }, ['$browser', '$exceptionHandler', '$updateView']); /** * @workInProgress * @ngdoc service * @name angular.service.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ angularServiceInject("$document", function(window){ return jqLite(window.document); }, ['$window']); /** * @workInProgress * @ngdoc service * @name angular.service.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overriden by * {@link angular.mock.service.$exceptionHandler mock $exceptionHandler} * * @example */ var $exceptionHandlerFactory; //reference to be used only in tests angularServiceInject('$exceptionHandler', $exceptionHandlerFactory = function($log){ return function(e) { $log.error(e); }; }, ['$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$hover * @requires $browser * @requires $document * * @description * * @example */ angularServiceInject("$hover", function(browser, document) { var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body); browser.hover(function(element, show){ if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) { if (!tooltip) { tooltip = { callout: jqLite('<div id="ng-callout"></div>'), arrow: jqLite('<div></div>'), title: jqLite('<div class="ng-title"></div>'), content: jqLite('<div class="ng-content"></div>') }; tooltip.callout.append(tooltip.arrow); tooltip.callout.append(tooltip.title); tooltip.callout.append(tooltip.content); body.append(tooltip.callout); } var docRect = body[0].getBoundingClientRect(), elementRect = element[0].getBoundingClientRect(), leftSpace = docRect.right - elementRect.right - arrowWidth; tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."); tooltip.content.text(error); if (leftSpace < width) { tooltip.arrow.addClass('ng-arrow-right'); tooltip.arrow.css({left: (width + 1)+'px'}); tooltip.callout.css({ position: 'fixed', left: (elementRect.left - arrowWidth - width - 4) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } else { tooltip.arrow.addClass('ng-arrow-left'); tooltip.callout.css({ position: 'fixed', left: (elementRect.right + arrowWidth) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } } else if (tooltip) { tooltip.callout.remove(); tooltip = null; } }); }, ['$browser', '$document'], true); /** * @workInProgress * @ngdoc service * @name angular.service.$invalidWidgets * * @description * Keeps references to all invalid widgets found during validation. * Can be queried to find whether there are any invalid widgets currently displayed. * * @example */ angularServiceInject("$invalidWidgets", function(){ var invalidWidgets = []; /** Remove an element from the array of invalid widgets */ invalidWidgets.markValid = function(element){ var index = indexOf(invalidWidgets, element); if (index != -1) invalidWidgets.splice(index, 1); }; /** Add an element to the array of invalid widgets */ invalidWidgets.markInvalid = function(element){ var index = indexOf(invalidWidgets, element); if (index === -1) invalidWidgets.push(element); }; /** Return count of all invalid widgets that are currently visible */ invalidWidgets.visible = function() { var count = 0; forEach(invalidWidgets, function(widget){ count = count + (isVisible(widget) ? 1 : 0); }); return count; }; /* At the end of each eval removes all invalid widgets that are not part of the current DOM. */ this.$onEval(PRIORITY_LAST, function() { for(var i = 0; i < invalidWidgets.length;) { var widget = invalidWidgets[i]; if (isOrphan(widget[0])) { invalidWidgets.splice(i, 1); if (widget.dealoc) widget.dealoc(); } else { i++; } } }); /** * Traverses DOM element's (widget's) parents and considers the element to be an orphant if one of * it's parents isn't the current window.document. */ function isOrphan(widget) { if (widget == window.document) return false; var parent = widget.parentNode; return !parent || isOrphan(parent); } return invalidWidgets; }); var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = /^([^\?]*)?(\?([^\?]*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp':21}; /** * @workInProgress * @ngdoc service * @name angular.service.$location * @requires $browser * * @property {string} href The full URL of the current location. * @property {string} protocol The protocol part of the URL (e.g. http or https). * @property {string} host The host name, ip address or FQDN of the current location. * @property {number} port The port number of the current location (e.g. 80, 443, 8080). * @property {string} path The path of the current location (e.g. /myapp/inbox). * @property {Object.<string|boolean>} search Map of query parameters (e.g. {user:"foo", page:23}). * @property {string} hash The fragment part of the URL of the current location (e.g. #foo). * @property {string} hashPath Similar to `path`, but located in the `hash` fragment * (e.g. ../foo#/some/path => /some/path). * @property {Object.<string|boolean>} hashSearch Similar to `search` but located in `hash` * fragment (e.g. .../foo#/some/path?hashQuery=param => {hashQuery: "param"}). * * @description * Parses the browser location url and makes it available to your application. * Any changes to the url are reflected into `$location` service and changes to * `$location` are reflected in the browser location url. * * Notice that using browser's forward/back buttons changes the $location. * * @example <doc:example> <doc:source> <div ng:init="$location = $service('$location')"> <a id="ex-test" href="#myPath?name=misko">test hash</a>| <a id="ex-reset" href="#!/api/angular.service.$location">reset hash</a><br/> <input type='text' name="$location.hash" size="30"> <pre>$location = {{$location}}</pre> </div> </doc:source> <doc:scenario> it('should initialize the input field', function() { expect(using('.doc-example-live').element('input[name=$location.hash]').val()). toBe('!/api/angular.service.$location'); }); it('should bind $location.hash to the input field', function() { using('.doc-example-live').input('$location.hash').enter('foo'); expect(browser().location().hash()).toBe('foo'); }); it('should set the hash to a test string with test link is presed', function() { using('.doc-example-live').element('#ex-test').click(); expect(using('.doc-example-live').element('input[name=$location.hash]').val()). toBe('myPath?name=misko'); }); it('should reset $location when reset link is pressed', function() { using('.doc-example-live').input('$location.hash').enter('foo'); using('.doc-example-live').element('#ex-reset').click(); expect(using('.doc-example-live').element('input[name=$location.hash]').val()). toBe('!/api/angular.service.$location'); }); </doc:scenario> </doc:example> */ angularServiceInject("$location", function($browser) { var scope = this, location = {update:update, updateHash: updateHash}, lastLocation = {}; $browser.onHashChange(function() { //register update($browser.getUrl()); copy(location, lastLocation); scope.$eval(); })(); //initialize this.$onEval(PRIORITY_FIRST, sync); this.$onEval(PRIORITY_LAST, updateBrowser); return location; // PUBLIC METHODS /** * @workInProgress * @ngdoc method * @name angular.service.$location#update * @methodOf angular.service.$location * * @description * Updates the location object. * * Does not immediately update the browser. Instead the browser is updated at the end of $eval() * cycle. * * <pre> $location.update('http://www.angularjs.org/path#hash?search=x'); $location.update({host: 'www.google.com', protocol: 'https'}); $location.update({hashPath: '/path', hashSearch: {a: 'b', x: true}}); </pre> * * @param {string|Object} href Full href as a string or object with properties */ function update(href) { if (isString(href)) { extend(location, parseHref(href)); } else { if (isDefined(href.hash)) { extend(href, isString(href.hash) ? parseHash(href.hash) : href.hash); } extend(location, href); if (isDefined(href.hashPath || href.hashSearch)) { location.hash = composeHash(location); } location.href = composeHref(location); } } /** * @workInProgress * @ngdoc method * @name angular.service.$location#updateHash * @methodOf angular.service.$location * * @description * Updates the hash fragment part of the url. * * @see update() * * <pre> scope.$location.updateHash('/hp') ==> update({hashPath: '/hp'}) scope.$location.updateHash({a: true, b: 'val'}) ==> update({hashSearch: {a: true, b: 'val'}}) scope.$location.updateHash('/hp', {a: true}) ==> update({hashPath: '/hp', hashSearch: {a: true}}) </pre> * * @param {string|Object} path A hashPath or hashSearch object * @param {Object=} search A hashSearch object */ function updateHash(path, search) { var hash = {}; if (isString(path)) { hash.hashPath = path; hash.hashSearch = search || {}; } else hash.hashSearch = path; hash.hash = composeHash(hash); update({hash: hash}); } // INNER METHODS /** * Synchronizes all location object properties. * * User is allowed to change properties, so after property change, * location object is not in consistent state. * * Properties are synced with the following precedence order: * * - `$location.href` * - `$location.hash` * - everything else * * Keep in mind that if the following code is executed: * * scope.$location.href = 'http://www.angularjs.org/path#a/b' * * immediately afterwards all other properties are still the old ones... * * This method checks the changes and update location to the consistent state */ function sync() { if (!equals(location, lastLocation)) { if (location.href != lastLocation.href) { update(location.href); return; } if (location.hash != lastLocation.hash) { var hash = parseHash(location.hash); updateHash(hash.hashPath, hash.hashSearch); } else { location.hash = composeHash(location); location.href = composeHref(location); } update(location.href); } } /** * If location has changed, update the browser * This method is called at the end of $eval() phase */ function updateBrowser() { sync(); if ($browser.getUrl() != location.href) { $browser.setUrl(location.href); copy(location, lastLocation); } } /** * Compose href string from a location object * * @param {Object} loc The location object with all properties * @return {string} Composed href */ function composeHref(loc) { var url = toKeyValue(loc.search); var port = (loc.port == DEFAULT_PORTS[loc.protocol] ? null : loc.port); return loc.protocol + '://' + loc.host + (port ? ':' + port : '') + loc.path + (url ? '?' + url : '') + (loc.hash ? '#' + loc.hash : ''); } /** * Compose hash string from location object * * @param {Object} loc Object with hashPath and hashSearch properties * @return {string} Hash string */ function composeHash(loc) { var hashSearch = toKeyValue(loc.hashSearch); //TODO: temporary fix for issue #158 return escape(loc.hashPath).replace(/%21/gi, '!').replace(/%3A/gi, ':').replace(/%24/gi, '$') + (hashSearch ? '?' + hashSearch : ''); } /** * Parse href string into location object * * @param {string} href * @return {Object} The location object */ function parseHref(href) { var loc = {}; var match = URL_MATCH.exec(href); if (match) { loc.href = href.replace(/#$/, ''); loc.protocol = match[1]; loc.host = match[3] || ''; loc.port = match[5] || DEFAULT_PORTS[loc.protocol] || null; loc.path = match[6] || ''; loc.search = parseKeyValue(match[8]); loc.hash = match[10] || ''; extend(loc, parseHash(loc.hash)); } return loc; } /** * Parse hash string into object * * @param {string} hash */ function parseHash(hash) { var h = {}; var match = HASH_MATCH.exec(hash); if (match) { h.hash = hash; h.hashPath = unescape(match[1] || ''); h.hashSearch = parseKeyValue(match[3]); } return h; } }, ['$browser']); /** * @workInProgress * @ngdoc service * @name angular.service.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" name="message" value="Hello World!"/> <button ng:click="$log.log(message)">log</button> <button ng:click="$log.warn(message)">warn</button> <button ng:click="$log.info(message)">info</button> <button ng:click="$log.error(message)">error</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ var $logFactory; //reference to be used only in tests angularServiceInject("$log", $logFactory = function($window){ return { /** * @workInProgress * @ngdoc method * @name angular.service.$log#log * @methodOf angular.service.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#warn * @methodOf angular.service.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#info * @methodOf angular.service.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#error * @methodOf angular.service.$log * * @description * Write an error message */ error: consoleLog('error') }; function consoleLog(type) { var console = $window.console || {}; var logFn = console[type] || console.log || noop; if (logFn.apply) { return function(){ var args = []; forEach(arguments, function(arg){ args.push(formatError(arg)); }); return logFn.apply(console, args); }; } else { // we are IE, in which case there is nothing we can do return logFn; } } }, ['$window']); /** * @workInProgress * @ngdoc service * @name angular.service.$resource * @requires $xhr.cache * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link angular.service.$xhr $xhr} service or * raw XMLHttpRequest. * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?, verifyCache:?}, * action2: {method:?, params:?, isArray:?, verifyCache:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSON` (also known as JSONP). * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * - verifyCache – {boolean=} – If true then whenever cache hit occurs, the object is returned and * an async request will be made to the server and the resources as well as the cache will be * updated when the response is received. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link angular.service.$xhr} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class `save`, `remove` and `delete` actions are available on it as * methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, * update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [callback])` * - non-GET "class" actions: `Resource.action(postData, [parameters], [callback])` * - non-GET instance actions: `instance.$action([parameters], [callback])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(); // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$xhr` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * It's worth noting that the callback for `get`, `query` and other method gets passed in the * response that came from the server, so one could rewrite the above example as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u){ u.abc = true; u.$save(); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source> <script> function BuzzController($resource) { this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng:controller="BuzzController"> <input name="userId" value="googlebuzz"/> <button ng:click="fetch()">fetch</button> <hr/> <div ng:repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$resource', function($xhr){ var resource = new ResourceFactory($xhr); return bind(resource, resource.route); }, ['$xhr.cache']); /** * @workInProgress * @ngdoc service * @name angular.service.$route * @requires $location * * @property {Object} current Reference to the current route definition. * @property {Array.<Object>} routes Array of all configured routes. * * @description * Watches `$location.hashPath` and tries to map the hash to an existing route * definition. It is used for deep-linking URLs to controllers and views (HTML partials). * * The `$route` service is typically used in conjunction with {@link angular.widget.ng:view ng:view} * widget. * * @example This example shows how changing the URL hash causes the <tt>$route</tt> to match a route against the URL, and the <tt>[[ng:include]]</tt> pulls in the partial. Try changing the URL in the input box to see changes. <doc:example> <doc:source> <script> angular.service('myApp', function($route) { $route.when('/Book/:bookId', {template:'rsrc/book.html', controller:BookCntl}); $route.when('/Book/:bookId/ch/:chapterId', {template:'rsrc/chapter.html', controller:ChapterCntl}); $route.onChange(function() { $route.current.scope.params = $route.current.params; }); }, {$inject: ['$route']}); function BookCntl() { this.name = "BookCntl"; } function ChapterCntl() { this.name = "ChapterCntl"; } </script> Chose: <a href="#/Book/Moby">Moby</a> | <a href="#/Book/Moby/ch/1">Moby: Ch1</a> | <a href="#/Book/Gatsby">Gatsby</a> | <a href="#/Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a><br/> <input type="text" name="$location.hashPath" size="80" /> <pre>$location={{$location}}</pre> <pre>$route.current.template={{$route.current.template}}</pre> <pre>$route.current.params={{$route.current.params}}</pre> <pre>$route.current.scope.name={{$route.current.scope.name}}</pre> <hr/> <ng:include src="$route.current.template" scope="$route.current.scope"/> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$route', function(location, $updateView) { var routes = {}, onChange = [], matcher = switchRouteMatcher, parentScope = this, dirty = 0, $route = { routes: routes, /** * @workInProgress * @ngdoc method * @name angular.service.$route#onChange * @methodOf angular.service.$route * * @param {function()} fn Function that will be called when `$route.current` changes. * @returns {function()} The registered function. * * @description * Register a handler function that will be called when route changes */ onChange: function(fn) { onChange.push(fn); return fn; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#parent * @methodOf angular.service.$route * * @param {Scope} [scope=rootScope] Scope to be used as parent for newly created * `$route.current.scope` scopes. * * @description * Sets a scope to be used as the parent scope for scopes created on route change. If not * set, defaults to the root scope. */ parent: function(scope) { if (scope) parentScope = scope; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#when * @methodOf angular.service.$route * * @param {string} path Route path (matched against `$location.hash`) * @param {Object} params Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – path to an html template that should be used by * {@link angular.widget.ng:view ng:view} or * {@link angular.widget.ng:include ng:include} widgets. * - `redirectTo` – {(string|function())=} – value to update * {@link angular.service.$location $location} hash with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.hashPath` by applying the current route template. * - `{string}` - current `$location.hash` * - `{string}` - current `$location.hashPath` * - `{string}` - current `$location.hashSearch` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.hash`. * * @returns {Object} route object * * @description * Adds a new route definition to the `$route` service. */ when:function (path, params) { if (isUndefined(path)) return routes; //TODO(im): remove - not needed! var route = routes[path]; if (!route) route = routes[path] = {}; if (params) extend(route, params); dirty++; return route; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#otherwise * @methodOf angular.service.$route * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. */ otherwise: function(params) { $route.when(null, params); }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#reload * @methodOf angular.service.$route * * @description * Causes `$route` service to reload (and recreate the `$route.current` scope) upon the next * eval even if {@link angular.service.$location $location} hasn't changed. */ reload: function() { dirty++; } }; function switchRouteMatcher(on, when, dstName) { var regex = '^' + when.replace(/[\.\\\(\)\^\$]/g, "\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param){ if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index){ dst[name] = match[index + 1]; }); if (dstName) this.$set(dstName, dst); } return match ? dst : null; } function updateRoute(){ var childScope, routeParams, pathParams, segmentMatch, key, redir; $route.current = null; forEach(routes, function(rParams, rPath) { if (!pathParams) { if (pathParams = matcher(location.hashPath, rPath)) { routeParams = rParams; } } }); // "otherwise" fallback routeParams = routeParams || routes[null]; if(routeParams) { if (routeParams.redirectTo) { if (isString(routeParams.redirectTo)) { // interpolate the redirectTo string redir = {hashPath: '', hashSearch: extend({}, location.hashSearch, pathParams)}; forEach(routeParams.redirectTo.split(':'), function(segment, i) { if (i==0) { redir.hashPath += segment; } else { segmentMatch = segment.match(/(\w+)(.*)/); key = segmentMatch[1]; redir.hashPath += pathParams[key] || location.hashSearch[key]; redir.hashPath += segmentMatch[2] || ''; delete redir.hashSearch[key]; } }); } else { // call custom redirectTo function redir = {hash: routeParams.redirectTo(pathParams, location.hash, location.hashPath, location.hashSearch)}; } location.update(redir); $updateView(); //TODO this is to work around the $location<=>$browser issues return; } childScope = createScope(parentScope); $route.current = extend({}, routeParams, { scope: childScope, params: extend({}, location.hashSearch, pathParams) }); } //fire onChange callbacks forEach(onChange, parentScope.$tryEval); if (childScope) { childScope.$become($route.current.controller); } } this.$watch(function(){return dirty + location.hash;}, updateRoute); return $route; }, ['$location', '$updateView']); /** * @workInProgress * @ngdoc service * @name angular.service.$updateView * @requires $browser * * @description * Calling `$updateView` enqueues the eventual update of the view. (Update the DOM to reflect the * model). The update is eventual, since there are often multiple updates to the model which may * be deferred. The default update delayed is 25 ms. This means that the view lags the model by * that time. (25ms is small enough that it is perceived as instantaneous by the user). The delay * can be adjusted by setting the delay property of the service. * * <pre>angular.service('$updateView').delay = 10</pre> * * The delay is there so that multiple updates to the model which occur sufficiently close * together can be merged into a single update. * * You don't usually call '$updateView' directly since angular does it for you in most cases, * but there are some cases when you need to call it. * * - `$updateView()` called automatically by angular: * - Your Application Controllers: Your controller code is called by angular and hence * angular is aware that you may have changed the model. * - Your Services: Your service is usually called by your controller code, hence same rules * apply. * - May need to call `$updateView()` manually: * - Widgets / Directives: If you listen to any DOM events or events on any third party * libraries, then angular is not aware that you may have changed state state of the * model, and hence you need to call '$updateView()' manually. * - 'setTimeout'/'XHR': If you call 'setTimeout' (instead of {@link angular.service.$defer}) * or 'XHR' (instead of {@link angular.service.$xhr}) then you may be changing the model * without angular knowledge and you may need to call '$updateView()' directly. * * NOTE: if you wish to update the view immediately (without delay), you can do so by calling * {@link angular.scope.$eval} at any time from your code: * <pre>scope.$root.$eval()</pre> * * In unit-test mode the update is instantaneous and synchronous to simplify writing tests. * */ function serviceUpdateViewFactory($browser){ var rootScope = this; var scheduled; function update(){ scheduled = false; rootScope.$eval(); } return $browser.isMock ? update : function(){ if (!scheduled) { scheduled = true; $browser.defer(update, serviceUpdateViewFactory.delay); } }; } serviceUpdateViewFactory.delay = 25; angularServiceInject('$updateView', serviceUpdateViewFactory, ['$browser']); /** * @workInProgress * @ngdoc service * @name angular.service.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng:init="$window = $service('$window'); greeting='Hello World!'" type="text" name="greeting" /> <button ng:click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject("$window", bind(window, identity, window)); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.bulk * @requires $xhr * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, callback) { if (isFunction(post)) { callback = post; post = null; } var currentQueue; forEach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; currentQueue.requests.push({method: method, url: url, data:post, callback:callback}); } else { $xhr(method, url, post, callback); } } bulkXHR.urls = {}; bulkXHR.flush = function(callback){ forEach(bulkXHR.urls, function(queue, url){ var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests:currentRequests}, function(code, response){ forEach(response, function(response, i){ try { if (response.status == 200) { (currentRequests[i].callback || noop)(response.status, response.response); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); (callback || noop)(); }); scope.$eval(); } }); }; this.$onEval(PRIORITY_LAST, bulkXHR.flush); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.cache * @function * @requires $xhr * * @description * Acts just like the {@link angular.service.$xhr $xhr} service but caches responses for `GET` * requests. All cache misses are delegated to the $xhr service. * * @property {function()} delegate Function to delegate all the cache misses to. Defaults to * the {@link angular.service.$xhr $xhr} service. * @property {object} data The hashmap where all cached entries are stored. * * @param {string} method HTTP method. * @param {string} url Destination URL. * @param {(string|Object)=} post Request body. * @param {function(number, (string|Object))} callback Response callback. * @param {boolean=} [verifyCache=false] If `true` then a result is immediately returned from cache * (if present) while a request is sent to the server for a fresh response that will update the * cached entry. The `callback` function will be called when the response is received. * @param {boolean=} [sync=false] in case of cache hit execute `callback` synchronously. */ angularServiceInject('$xhr.cache', function($xhr, $defer, $log){ var inflight = {}, self = this; function cache(method, url, post, callback, verifyCache, sync){ if (isFunction(post)) { callback = post; post = null; } if (method == 'GET') { var data, dataCached; if (dataCached = cache.data[url]) { if (sync) { callback(200, copy(dataCached.value)); } else { $defer(function() { callback(200, copy(dataCached.value)); }); } if (!verifyCache) return; } if (data = inflight[url]) { data.callbacks.push(callback); } else { inflight[url] = {callbacks: [callback]}; cache.delegate(method, url, post, function(status, response){ if (status == 200) cache.data[url] = { value: response }; var callbacks = inflight[url].callbacks; delete inflight[url]; forEach(callbacks, function(callback){ try { (callback||noop)(status, copy(response)); } catch(e) { $log.error(e); } }); }); } } else { cache.data = {}; cache.delegate(method, url, post, callback); } } cache.data = {}; cache.delegate = $xhr; return cache; }, ['$xhr.bulk', '$defer', '$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.error * @function * @requires $log * * @description * Error handler for {@link angular.service.$xhr $xhr service}. An application can replaces this * service with one specific for the application. The default implementation logs the error to * {@link angular.service.$log $log.error}. * * @param {Object} request Request object. * * The object has the following properties * * - `method` – `{string}` – The http request method. * - `url` – `{string}` – The request destination. * - `data` – `{(string|Object)=} – An optional request body. * - `callback` – `{function()}` – The callback function * * @param {Object} response Response object. * * The response object has the following properties: * * - status – {number} – Http status code. * - body – {string|Object} – Body of the response. * * @example <doc:example> <doc:source> fetch a non-existent file and log an error in the console: <button ng:click="$service('$xhr')('GET', '/DOESNT_EXIST')">fetch</button> </doc:source> </doc:example> */ angularServiceInject('$xhr.error', function($log){ return function(request, response){ $log.error('ERROR: XHR: ' + request.url, request, response); }; }, ['$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr * @function * @requires $browser $xhr delegates all XHR requests to the `$browser.xhr()`. A mock version * of the $browser exists which allows setting expectaitions on XHR requests * in your tests * @requires $xhr.error $xhr delegates all non `2xx` response code to this service. * @requires $log $xhr delegates all exceptions to `$log.error()`. * @requires $updateView After a server response the view needs to be updated for data-binding to * take effect. * * @description * Generates an XHR request. The $xhr service delegates all requests to * {@link angular.service.$browser $browser.xhr()} and adds error handling and security features. * While $xhr service provides nicer api than raw XmlHttpRequest, it is still considered a lower * level api in angular. For a higher level abstraction that utilizes `$xhr`, please check out the * {@link angular.service.$resource $resource} service. * * # Error handling * All XHR responses with response codes other then `2xx` are delegated to * {@link angular.service.$xhr.error $xhr.error}. The `$xhr.error` can intercept the request * and process it in application specific way, or resume normal execution by calling the * request callback method. * * # Security Considerations * When designing web applications your design needs to consider security threats from * {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} and {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}. * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which an * unauthorized site can gain your user's private data. Angular provides following mechanism to * counter XSRF. When performing XHR requests, the $xhr service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the server * can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure that only * JavaScript running on your domain could have read the token. The token must be unique for each * user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). * We recommend that the token is a digest of your site's authentication cookie with * {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * @param {string} method HTTP method to use. Valid values are: `GET`, `POST`, `PUT`, `DELETE`, and * `JSON`. `JSON` is a special case which causes a * [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP) cross domain request using script tag * insertion. * @param {string} url Relative or absolute URL specifying the destination of the request. For * `JSON` requests, `url` should include `JSON_CALLBACK` string to be replaced with a name of an * angular generated callback function. * @param {(string|Object)=} post Request content as either a string or an object to be stringified * as JSON before sent to the server. * @param {function(number, (string|Object))} callback A function to be called when the response is * received. The callback will be called with: * * - {number} code [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) of * the response. This will currently always be 200, since all non-200 responses are routed to * {@link angular.service.$xhr.error} service. * - {string|Object} response Response object as string or an Object if the response was in JSON * format. * * @example <doc:example> <doc:source> <script> function FetchCntl($xhr) { var self = this; this.fetch = function() { self.clear(); $xhr(self.method, self.url, function(code, response) { self.code = code; self.response = response; }); }; this.clear = function() { self.code = null; self.response = null; }; } FetchCntl.$inject = ['$xhr']; </script> <div ng:controller="FetchCntl"> <select name="method"> <option>GET</option> <option>JSON</option> </select> <input type="text" name="url" value="index.html" size="80"/><br/> <button ng:click="fetch()">fetch</button> <button ng:click="clear()">clear</button> <a href="" ng:click="method='GET'; url='index.html'">sample</a> <a href="" ng:click="method='JSON'; url='https://www.googleapis.com/buzz/v1/activities/googlebuzz/@self?alt=json&callback=JSON_CALLBACK'">buzz</a> <pre>code={{code}}</pre> <pre>response={{response}}</pre> </div> </doc:source> </doc:example> */ angularServiceInject('$xhr', function($browser, $error, $log, $updateView){ return function(method, url, post, callback){ if (isFunction(post)) { callback = post; post = null; } if (post && isObject(post)) { post = toJson(post); } $browser.xhr(method, url, post, function(code, response){ try { if (isString(response)) { if (response.match(/^\)\]\}',\n/)) response=response.substr(6); if (/^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { response = fromJson(response, true); } } if (200 <= code && code < 300) { callback(code, response); } else { $error( {method: method, url:url, data:post, callback:callback}, {status: code, body:response}); } } catch (e) { $log.error(e); } finally { $updateView(); } }, { 'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN'] }); }; }, ['$browser', '$xhr.error', '$log', '$updateView']); /** * @workInProgress * @ngdoc overview * @name angular.directive * @description * * Custom attributes for DOM elements. Directives modify the behavior of the element they are * specified in, but are not intended to add elements to the DOM as are * {@link angular.widget widgets}. * * Following is the list of built-in angular directives: * * * {@link angular.directive.ng:bind ng:bind} - Creates a data-binding between HTML text value and * data model. * * {@link angular.directive.ng:bind-attr ng:bind-attr} - Creates a data-binding as in `ng:bind`, * but uses JSON key / value pairs. * * {@link angular.directive.ng:bind-template ng:bind-template} - Replaces text value of an element * with a specified template. * * {@link angular.directive.ng:change ng:change} - Executes an expression when the value of an * input widget changes. * * {@link angular.directive.ng:class ng:class} - Conditionally set CSS class on an element. * * {@link angular.directive.ng:class-even ng:class-even} - Like `ng:class`, but works in * conjunction with {@link angular.widget.@ng:repeat} to affect even rows in a collection. * * {@link angular.directive.ng:class-odd ng:class-odd} - Like `ng:class`, but works with {@link * angular.widget.@ng:repeat} to affect odd rows. * * {@link angular.directive.ng:click ng:click} - Executes custom behavior when element is clicked. * * {@link angular.directive.ng:controller ng:controller} - Creates a scope object linked to the * DOM element and assigns behavior to the scope. * * {@link angular.directive.ng:eval ng:eval} - Executes a binding but blocks output. * * {@link angular.directive.ng:eval-order ng:eval-order} - Change evaluation order when updating * the view. * * {@link angular.directive.ng:hide ng:hide} - Conditionally hides a portion of HTML. * * {@link angular.directive.ng:href ng:href} - Places an href in the angular namespace. * * {@link angular.directive.ng:init} - Initialization tasks run before a template is executed. * * {@link angular.directive.ng:show ng:show} - Conditionally displays a portion of HTML. * * {@link angular.directive.ng:src ng:src} - Places a `src` attribute into the angular namespace. * * {@link angular.directive.ng:style ng:style} - Conditionally set CSS styles on an element. * * {@link angular.directive.ng:submit} - Binds angular expressions to `onSubmit` events. * * For more information about how angular directives work, and how to create your own directives, * see {@link guide/dev_guide.compiler.directives Understanding Angular Directives} in the angular * Developer Guide. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:init * * @description * The `ng:init` attribute specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <div ng:init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function(){ expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ angularDirective("ng:init", function(expression){ return function(element){ this.$tryEval(expression, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:controller * * @description * The `ng:controller` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ng:controller` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link angular.service.$route}` * service. * * @element ANY * @param {expression} expression Name of a globally accessible constructor function or an * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script type="text/javascript"> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; } SettingsController.prototype = { greet: function(){ alert(this.name); }, addContact: function(){ this.contacts.push({type:'email', value:'yourname@example.org'}); }, removeContact: function(contactToRemove) { angular.Array.remove(this.contacts, contactToRemove); }, clearContact: function(contact) { contact.type = 'phone'; contact.value = ''; } }; </script> <div ng:controller="SettingsController"> Name: <input type="text" name="name"/> [ <a href="" ng:click="greet()">greet</a> ]<br/> Contact: <ul> <li ng:repeat="contact in contacts"> <select name="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" name="contact.value"/> [ <a href="" ng:click="clearContact(contact)">clear</a> | <a href="" ng:click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng:click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function(){ expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li[ng\\:repeat-index="0"] input').val()).toBe('408 555 1212'); expect(element('.doc-example-live li[ng\\:repeat-index="1"] input').val()).toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li[ng\\:repeat-index="2"] input').val()).toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ angularDirective("ng:controller", function(expression){ this.scope(true); return function(element){ var controller = getter(window, expression, true) || getter(this, expression, true); if (!controller) throw "Can not find '"+expression+"' controller."; if (!isFunction(controller)) throw "Reference '"+expression+"' is not a class."; this.$become(controller); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:eval * * @description * The `ng:eval` allows you to execute a binding which has side effects * without displaying the result to the user. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example * Notice that `{{` `obj.multiplied = obj.a * obj.b` `}}` has a side effect of assigning * a value to `obj.multiplied` and displaying the result to the user. Sometimes, * however, it is desirable to execute a side effect without showing the value to * the user. In such a case `ng:eval` allows you to execute code without updating * the display. <doc:example> <doc:source> <input name="obj.a" value="6" > * <input name="obj.b" value="2"> = {{obj.multiplied = obj.a * obj.b}} <br> <span ng:eval="obj.divide = obj.a / obj.b"></span> <span ng:eval="obj.updateCount = 1 + (obj.updateCount||0)"> </span> <tt>obj.divide = {{obj.divide}}</tt><br> <tt>obj.updateCount = {{obj.updateCount}}</tt> </doc:source> <doc:scenario> it('should check eval', function(){ expect(binding('obj.divide')).toBe('3'); expect(binding('obj.updateCount')).toBe('2'); input('obj.a').enter('12'); expect(binding('obj.divide')).toBe('6'); expect(binding('obj.updateCount')).toBe('3'); }); </doc:scenario> </doc:example> */ angularDirective("ng:eval", function(expression){ return function(element){ this.$onEval(expression, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind * * @description * The `ng:bind` attribute asks angular to replace the text content of this * HTML element with the value of the given expression, and to keep the text * content up to date when the expression's value changes. Usually you would * just write `{{ expression }}` and let angular compile it into * `<span ng:bind="expression"></span>` at bootstrap time. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example * You can try it right here: enter text in the text box and watch the greeting change. <doc:example> <doc:source> Enter name: <input type="text" name="name" value="Whirled"> <br> Hello <span ng:bind="name" />! </doc:source> <doc:scenario> it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind", function(expression, element){ element.addClass('ng-binding'); return function(element) { var lastValue = noop, lastError = noop; this.$onEval(function() { var error, value, html, isHtml, isDomElement, oldElement = this.hasOwnProperty($$element) ? this.$element : undefined; this.$element = element; value = this.$tryEval(expression, function(e){ error = formatError(e); }); this.$element = oldElement; // If we are HTML than save the raw HTML data so that we don't // recompute sanitization since it is expensive. // TODO: turn this into a more generic way to compute this if (isHtml = (value instanceof HTML)) value = (html = value).html; if (lastValue === value && lastError == error) return; isDomElement = isElement(value); if (!isHtml && !isDomElement && isObject(value)) { value = toJson(value, true); } if (value != lastValue || error != lastError) { lastValue = value; lastError = error; elementError(element, NG_EXCEPTION, error); if (error) value = error; if (isHtml) { element.html(html.get()); } else if (isDomElement) { element.html(''); element.append(value); } else { element.text(value == undefined ? '' : value); } } }, element); }; }); var bindTemplateCache = {}; function compileBindTemplate(template){ var fn = bindTemplateCache[template]; if (!fn) { var bindings = []; forEach(parseBindings(template), function(text){ var exp = binding(text); bindings.push(exp ? function(element){ var error, value = this.$tryEval(exp, function(e){ error = toJson(e); }); elementError(element, NG_EXCEPTION, error); return error ? error : value; } : function() { return text; }); }); bindTemplateCache[template] = fn = function(element, prettyPrintJson){ var parts = [], self = this, oldElement = this.hasOwnProperty($$element) ? self.$element : undefined; self.$element = element; for ( var i = 0; i < bindings.length; i++) { var value = bindings[i].call(self, element); if (isElement(value)) value = ''; else if (isObject(value)) value = toJson(value, prettyPrintJson); parts.push(value); } self.$element = oldElement; return parts.join(''); }; } return fn; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-template * * @description * The `ng:bind-template` attribute specifies that the element * text should be replaced with the template in ng:bind-template. * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few. * * @element ANY * @param {string} template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> Salutation: <input type="text" name="salutation" value="Hello"><br/> Name: <input type="text" name="name" value="World"><br/> <pre ng:bind-template="{{salutation}} {{name}}!"></pre> </doc:source> <doc:scenario> it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Hello World!'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Greetings user!'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-template", function(expression, element){ element.addClass('ng-binding'); var templateFn = compileBindTemplate(expression); return function(element) { var lastValue; this.$onEval(function() { var value = templateFn.call(this, element, true); if (value != lastValue) { element.text(value); lastValue = value; } }, element); }; }); var REMOVE_ATTRIBUTES = { 'disabled':'disabled', 'readonly':'readOnly', 'checked':'checked', 'selected':'selected' }; /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-attr * * @description * The `ng:bind-attr` attribute specifies that * {@link guide/dev_guide.templates.databinding databindings} should be created between element * attributes and given expressions. Unlike `ng:bind` the `ng:bind-attr` contains a JSON key value * pairs representing which attributes need to be mapped to which * {@link guide/dev_guide.expressions expressions}. * * You don't usually write the `ng:bind-attr` in the HTML since embedding * <tt ng:non-bindable>{{expression}}</tt> into the attribute directly as the attribute value is * preferred. The attributes get translated into `<span ng:bind-attr="{attr:expression}"/>` at * compile time. * * This HTML snippet is preferred way of working with `ng:bind-attr` * <pre> * <a href="http://www.google.com/search?q={{query}}">Google</a> * </pre> * * The above gets translated to bellow during bootstrap time. * <pre> * <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a> * </pre> * * @element ANY * @param {string} attribute_json a JSON key-value pairs representing * the attributes to replace. Each key matches the attribute * which needs to be replaced. Each value is a text template of * the attribute with embedded * <tt ng:non-bindable>{{expression}}</tt>s. Any number of * key-value pairs can be specified. * * @example * Try it here: enter text in text box and click Google. <doc:example> <doc:source> Google for: <input type="text" name="query" value="AngularJS"/> <a href="http://www.google.com/search?q={{query}}">Google</a> </doc:source> <doc:scenario> it('should check ng:bind-attr', function(){ expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-attr", function(expression){ return function(element){ var lastValue = {}; var updateFn = element.data($$update) || noop; this.$onEval(function(){ var values = this.$eval(expression), dirty = noop; for(var key in values) { var value = compileBindTemplate(values[key]).call(this, element), specialName = REMOVE_ATTRIBUTES[lowercase(key)]; if (lastValue[key] !== value) { lastValue[key] = value; if (specialName) { if (toBoolean(value)) { element.attr(specialName, specialName); element.attr('ng-' + specialName, value); } else { element.removeAttr(specialName); element.removeAttr('ng-' + specialName); } (element.data($$validate)||noop)(); } else { element.attr(key, value); } dirty = updateFn; } } dirty(); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:click * * @description * The ng:click allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval upon click. * * @example <doc:example> <doc:source> <button ng:click="count = count + 1" ng:init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng:click', function(){ expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. * * TODO: maybe we should consider allowing users to control event propagation in the future. */ angularDirective("ng:click", function(expression, element){ return injectUpdateView(function($updateView, element){ var self = this; element.bind('click', function(event){ self.$tryEval(expression, element); $updateView(); event.stopPropagation(); }); }); }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:submit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <form ng:submit="list.push(text);text='';" ng:init="list=[]"> Enter text and hit enter: <input type="text" name="text" value="hello"/> </form> <pre>list={{list}}</pre> </doc:source> <doc:scenario> it('should check ng:submit', function(){ expect(binding('list')).toBe('list=[]'); element('.doc-example-live form input').click(); this.addFutureAction('submit from', function($window, $document, done) { $window.angular.element( $document.elements('.doc-example-live form')). trigger('submit'); done(); }); expect(binding('list')).toBe('list=["hello"]'); }); </doc:scenario> </doc:example> */ angularDirective("ng:submit", function(expression, element) { return injectUpdateView(function($updateView, element) { var self = this; element.bind('submit', function(event) { self.$tryEval(expression, element); $updateView(); event.preventDefault(); }); }); }); function ngClass(selector) { return function(expression, element){ var existing = element[0].className + ' '; return function(element){ this.$onEval(function(){ if (selector(this.$index)) { var value = this.$eval(expression); if (isArray(value)) value = value.join(' '); element[0].className = trim(existing + value); } }, element); }; }; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class * * @description * The `ng:class` allows you to set CSS class on HTML element * conditionally. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'"> <input type="button" value="clear" ng:click="myVar=''"> <br> <span ng:class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> </doc:source> <doc:scenario> it('should check ng:class', function(){ expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').attr('className')). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class", ngClass(function(){return true;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-odd * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. Must be * inside `ng:repeat`. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-even * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. Must be * inside `ng:repeat`. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:show * * @description * The `ng:show` and `ng:hide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng:hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:show", function(expression, element){ return function(element){ this.$onEval(function(){ element.css($display, toBoolean(this.$eval(expression)) ? '' : $none); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:hide * * @description * The `ng:hide` and `ng:show` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:hide", function(expression, element){ return function(element){ this.$onEval(function(){ element.css($display, toBoolean(this.$eval(expression)) ? $none : ''); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:style * * @description * The ng:style allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myStyle={color:'red'}"> <input type="button" value="clear" ng:click="myStyle={}"> <br/> <span ng:style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </doc:source> <doc:scenario> it('should check ng:style', function(){ expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('red'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </doc:scenario> </doc:example> */ angularDirective("ng:style", function(expression, element){ return function(element){ var resetStyle = getStyle(element); this.$onEval(function(){ var style = this.$eval(expression) || {}, key, mergedStyle = {}; for(key in style) { if (resetStyle[key] === undefined) resetStyle[key] = ''; mergedStyle[key] = style[key]; } for(key in resetStyle) { mergedStyle[key] = mergedStyle[key] || resetStyle[key]; } element.css(mergedStyle); }, element); }; }); /** * @workInProgress * @ngdoc overview * @name angular.markup * @description * * Angular markup transforms content of DOM elements or portions of this content into other text or * DOM elements for further compilation. * * Markup extensions do not themselves produce linking functions. Think of markup as a way to * produce shorthand for a {@link angular.widget widget} or a {@link angular.directive directive}. * * The most prominent example of an markup in angular is the built-in double curly markup * `{{expression}}`, which is a shorthand for `<span ng:bind="expression"></span>`. * * Create custom markup like this: * * <pre> * angular.markup('newMarkup', function(text, textNode, parentElement){ * //tranformation code * }); * </pre> * * For more information about angular markup, see {@link guide/dev_guide.compiler.markup * Understanding Angular Markup} in the angular Developer Guide. */ /** * @workInProgress * @ngdoc overview * @name angular.attrMarkup * @description * * Attribute markup extends the angular compiler in a very similar way as {@link angular.markup} * except that it allows you to modify the state of the attribute text rather then the content of a * node. * * Create custom attribute markup like this: * * <pre> * angular.attrMarkup('newAttrMarkup', function(attrValue, attrName, element){ * //tranformation code * }); * </pre> * * For more information about angular attribute markup, see {@link guide/dev_guide.compiler.markup * Understanding Angular Markup} in the angular Developer Guide. */ function parseBindings(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; } function binding(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : null; } function hasBindings(bindings) { return bindings.length > 1 || binding(bindings[0]) !== null; } angularTextMarkup('{{}}', function(text, textNode, parentElement) { var bindings = parseBindings(text), self = this; if (hasBindings(bindings)) { if (isLeafNode(parentElement[0])) { parentElement.attr('ng:bind-template', text); } else { var cursor = textNode, newElement; forEach(parseBindings(text), function(text){ var exp = binding(text); if (exp) { newElement = jqLite('<span>'); newElement.attr('ng:bind', exp); } else { newElement = jqLite(document.createTextNode(text)); } if (msie && text.charAt(0) == ' ') { newElement = jqLite('<span>&nbsp;</span>'); var nbsp = newElement.html(); newElement.text(text.substr(1)); newElement.html(nbsp + newElement.html()); } cursor.after(newElement); cursor = newElement; }); textNode.remove(); } } }); /** * This tries to normalize the behavior of value attribute across browsers. If value attribute is * not specified, then specify it to be that of the text. */ angularTextMarkup('option', function(text, textNode, parentElement){ if (lowercase(nodeName_(parentElement)) == 'option') { if (msie <= 7) { // In IE7 The issue is that there is no way to see if the value was specified hence // we have to resort to parsing HTML; htmlParser(parentElement[0].outerHTML, { start: function(tag, attrs) { if (isUndefined(attrs.value)) { parentElement.attr('value', text); } } }); } else if (parentElement[0].getAttribute('value') == null) { // jQuery does normalization on 'value' so we have to bypass it. parentElement.attr('value', text); } } }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:href * * @description * Using <angular/> markup like {{hash}} in an href attribute makes * the page open to a wrong URL, ff the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ng:href` solves this problem by placing the `href` in the * `ng:` namespace. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng:href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input name="value" /><br /> <a id="link-1" href ng:click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng:click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng:href="#{{'123'}}" ng:click="value = 3">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng:click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng:click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng:href="#/{{value}}">link</a> (link, change hash) </doc:source> <doc:scenario> it('should execute ng:click but not reload when href without value', function() { element('#link-1').click(); expect(element('input[name=value]').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng:click but not reload when href empty string', function() { element('#link-2').click(); expect(element('input[name=value]').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng:click and change url when ng:href specified', function() { element('#link-3').click(); expect(element('input[name=value]').val()).toEqual('3'); expect(element('#link-3').attr('href')).toBe("#123"); expect(browser().location().hash()).toEqual('123'); }); it('should execute ng:click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(element('input[name=value]').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(""); }); it('should execute ng:click but not reload when no href but name specified', function() { element('#link-5').click(); expect(element('input[name=value]').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng:href', function() { input('value').enter('6'); element('#link-6').click(); expect(browser().location().hash()).toEqual('/6'); expect(element('#link-6').attr('href')).toBe("#/6"); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:src * * @description * Using <angular/> markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until <angular/> replaces the expression inside * `{{hash}}`. The `ng:src` attribute solves this problem by placing * the `src` attribute in the `ng:` namespace. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng:src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. */ var NG_BIND_ATTR = 'ng:bind-attr'; var SPECIAL_ATTRS = {'ng:src': 'src', 'ng:href': 'href'}; angularAttrMarkup('{{}}', function(value, name, element){ // don't process existing attribute markup if (angularDirective(name) || angularDirective("@" + name)) return; if (msie && name == 'src') value = decodeURI(value); var bindings = parseBindings(value), bindAttr; if (hasBindings(bindings)) { element.removeAttr(name); bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}"); bindAttr[SPECIAL_ATTRS[name] || name] = value; element.attr(NG_BIND_ATTR, toJson(bindAttr)); } }); /** * @workInProgress * @ngdoc overview * @name angular.widget * @description * * Widgets are custom DOM elements. An angular widget can be either a custom * attribute that modifies an existing DOM elements or an entirely new DOM element. * * Following is the list of built-in angular widgets: * * * {@link angular.widget.@ng:format ng:format} - Formats data for display to user and for storage. * * {@link angular.widget.@ng:non-bindable ng:non-bindable} - Blocks angular from processing an * HTML element. * * {@link angular.widget.@ng:repeat ng:repeat} - Creates and manages a collection of cloned HTML * elements. * * {@link angular.widget.@ng:required ng:required} - Verifies presence of user input. * * {@link angular.widget.@ng:validate ng:validate} - Validates content of user input. * * {@link angular.widget.HTML HTML} - Standard HTML processed by angular. * * {@link angular.widget.ng:view ng:view} - Works with $route to "include" partial templates * * {@link angular.widget.ng:switch ng:switch} - Conditionally changes DOM structure * * {@link angular.widget.ng:include ng:include} - Includes an external HTML fragment * * For more information about angular widgets, see {@link guide/dev_guide.compiler.widgets * Understanding Angular Widgets} in the angular Developer Guide. */ /** * @workInProgress * @ngdoc widget * @name angular.widget.HTML * * @description * The most common widgets you will use will be in the form of the * standard HTML set. These widgets are bound using the `name` attribute * to an expression. In addition they can have `ng:validate`, `ng:required`, * `ng:format`, `ng:change` attribute to further control their behavior. * * @usageContent * see example below for usage * * <input type="text|checkbox|..." ... /> * <textarea ... /> * <select ...> * <option>...</option> * </select> * * @example <doc:example> <doc:source> <table style="font-size:.9em;"> <tr> <th>Name</th> <th>Format</th> <th>HTML</th> <th>UI</th> <th ng:non-bindable>{{input#}}</th> </tr> <tr> <th>text</th> <td>String</td> <td><tt>&lt;input type="text" name="input1"&gt;</tt></td> <td><input type="text" name="input1" size="4"></td> <td><tt>{{input1|json}}</tt></td> </tr> <tr> <th>textarea</th> <td>String</td> <td><tt>&lt;textarea name="input2"&gt;&lt;/textarea&gt;</tt></td> <td><textarea name="input2" cols='6'></textarea></td> <td><tt>{{input2|json}}</tt></td> </tr> <tr> <th>radio</th> <td>String</td> <td><tt> &lt;input type="radio" name="input3" value="A"&gt;<br> &lt;input type="radio" name="input3" value="B"&gt; </tt></td> <td> <input type="radio" name="input3" value="A"> <input type="radio" name="input3" value="B"> </td> <td><tt>{{input3|json}}</tt></td> </tr> <tr> <th>checkbox</th> <td>Boolean</td> <td><tt>&lt;input type="checkbox" name="input4" value="checked"&gt;</tt></td> <td><input type="checkbox" name="input4" value="checked"></td> <td><tt>{{input4|json}}</tt></td> </tr> <tr> <th>pulldown</th> <td>String</td> <td><tt> &lt;select name="input5"&gt;<br> &nbsp;&nbsp;&lt;option value="c"&gt;C&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="d"&gt;D&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input5"> <option value="c">C</option> <option value="d">D</option> </select> </td> <td><tt>{{input5|json}}</tt></td> </tr> <tr> <th>multiselect</th> <td>Array</td> <td><tt> &lt;select name="input6" multiple size="4"&gt;<br> &nbsp;&nbsp;&lt;option value="e"&gt;E&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="f"&gt;F&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input6" multiple size="4"> <option value="e">E</option> <option value="f">F</option> </select> </td> <td><tt>{{input6|json}}</tt></td> </tr> </table> </doc:source> <doc:scenario> it('should exercise text', function(){ input('input1').enter('Carlos'); expect(binding('input1')).toEqual('"Carlos"'); }); it('should exercise textarea', function(){ input('input2').enter('Carlos'); expect(binding('input2')).toEqual('"Carlos"'); }); it('should exercise radio', function(){ expect(binding('input3')).toEqual('null'); input('input3').select('A'); expect(binding('input3')).toEqual('"A"'); input('input3').select('B'); expect(binding('input3')).toEqual('"B"'); }); it('should exercise checkbox', function(){ expect(binding('input4')).toEqual('false'); input('input4').check(); expect(binding('input4')).toEqual('true'); }); it('should exercise pulldown', function(){ expect(binding('input5')).toEqual('"c"'); select('input5').option('d'); expect(binding('input5')).toEqual('"d"'); }); it('should exercise multiselect', function(){ expect(binding('input6')).toEqual('[]'); select('input6').options('e'); expect(binding('input6')).toEqual('["e"]'); select('input6').options('e', 'f'); expect(binding('input6')).toEqual('["e","f"]'); }); </doc:scenario> </doc:example> */ function modelAccessor(scope, element) { var expr = element.attr('name'); var assign; if (expr) { assign = parser(expr).assignable().assign; if (!assign) throw new Error("Expression '" + expr + "' is not assignable."); return { get: function() { return scope.$eval(expr); }, set: function(value) { if (value !== undefined) { return scope.$tryEval(function(){ assign(scope, value); }, element); } } }; } } function modelFormattedAccessor(scope, element) { var accessor = modelAccessor(scope, element), formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName); if (accessor) { return { get: function() { return formatter.format(scope, accessor.get()); }, set: function(value) { return accessor.set(formatter.parse(scope, value)); } }; } } function compileValidator(expr) { return parser(expr).validator()(); } function compileFormatter(expr) { return parser(expr).formatter()(); } /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:validate * * @description * The `ng:validate` attribute widget validates the user input. If the input does not pass * validation, the `ng-validation-error` CSS class and the `ng:error` attribute are set on the input * element. Check out {@link angular.validator validators} to find out more. * * @param {string} validator The name of a built-in or custom {@link angular.validator validator} to * to be used. * * @element INPUT * @css ng-validation-error * * @example * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * <doc:example> <doc:source> I don't validate: <input type="text" name="value" value="NotANumber"><br/> I need an integer or nothing: <input type="text" name="value" ng:validate="integer"><br/> </doc:source> <doc:scenario> it('should check ng:validate', function(){ expect(element('.doc-example-live :input:last').attr('className')). toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input:last').attr('className')). not().toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:required * * @description * The `ng:required` attribute widget validates that the user input is present. It is a special case * of the {@link angular.widget.@ng:validate ng:validate} attribute widget. * * @element INPUT * @css ng-validation-error * * @example * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * <doc:example> <doc:source> I cannot be blank: <input type="text" name="value" ng:required><br/> </doc:source> <doc:scenario> it('should check ng:required', function(){ expect(element('.doc-example-live :input').attr('className')).toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input').attr('className')).not().toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:format * * @description * The `ng:format` attribute widget formats stored data to user-readable text and parses the text * back to the stored form. You might find this useful for example if you collect user input in a * text field but need to store the data in the model as a list. Check out * {@link angular.formatter formatters} to learn more. * * @param {string} formatter The name of the built-in or custom {@link angular.formatter formatter} * to be used. * * @element INPUT * * @example * This example shows how the user input is converted from a string and internally represented as an * array. * <doc:example> <doc:source> Enter a comma separated list of items: <input type="text" name="list" ng:format="list" value="table, chairs, plate"> <pre>list={{list}}</pre> </doc:source> <doc:scenario> it('should check ng:format', function(){ expect(binding('list')).toBe('list=["table","chairs","plate"]'); input('list').enter(',,, a ,,,'); expect(binding('list')).toBe('list=["a"]'); }); </doc:scenario> </doc:example> */ function valueAccessor(scope, element) { var validatorName = element.attr('ng:validate') || NOOP, validator = compileValidator(validatorName), requiredExpr = element.attr('ng:required'), formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName), format, parse, lastError, required, invalidWidgets = scope.$service('$invalidWidgets') || {markValid:noop, markInvalid:noop}; if (!validator) throw "Validator named '" + validatorName + "' not found."; format = formatter.format; parse = formatter.parse; if (requiredExpr) { scope.$watch(requiredExpr, function(newValue) { required = newValue; validate(); }); } else { required = requiredExpr === ''; } element.data($$validate, validate); return { get: function(){ if (lastError) elementError(element, NG_VALIDATION_ERROR, null); try { var value = parse(scope, element.val()); validate(); return value; } catch (e) { lastError = e; elementError(element, NG_VALIDATION_ERROR, e); } }, set: function(value) { var oldValue = element.val(), newValue = format(scope, value); if (oldValue != newValue) { element.val(newValue || ''); // needed for ie } validate(); } }; function validate() { var value = trim(element.val()); if (element[0].disabled || element[0].readOnly) { elementError(element, NG_VALIDATION_ERROR, null); invalidWidgets.markValid(element); } else { var error, validateScope = inherit(scope, {$element:element}); error = required && !value ? 'Required' : (value ? validator(validateScope, value) : null); elementError(element, NG_VALIDATION_ERROR, error); lastError = error; if (error) { invalidWidgets.markInvalid(element); } else { invalidWidgets.markValid(element); } } } } function checkedAccessor(scope, element) { var domElement = element[0], elementValue = domElement.value; return { get: function(){ return !!domElement.checked; }, set: function(value){ domElement.checked = toBoolean(value); } }; } function radioAccessor(scope, element) { var domElement = element[0]; return { get: function(){ return domElement.checked ? domElement.value : null; }, set: function(value){ domElement.checked = value == domElement.value; } }; } function optionsAccessor(scope, element) { var formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName); return { get: function(){ var values = []; forEach(element[0].options, function(option){ if (option.selected) values.push(formatter.parse(scope, option.value)); }); return values; }, set: function(values){ var keys = {}; forEach(values, function(value){ keys[formatter.format(scope, value)] = true; }); forEach(element[0].options, function(option){ option.selected = keys[option.value]; }); } }; } function noopAccessor() { return { get: noop, set: noop }; } /* * TODO: refactor * * The table bellow is not quite right. In some cases the formatter is on the model side * and in some cases it is on the view side. This is a historical artifact * * The concept of model/view accessor is useful for anyone who is trying to develop UI, and * so it should be exposed to others. There should be a form object which keeps track of the * accessors and also acts as their factory. It should expose it as an object and allow * the validator to publish errors to it, so that the the error messages can be bound to it. * */ var textWidget = inputWidget('keydown change', modelAccessor, valueAccessor, initWidgetValue(), true), buttonWidget = inputWidget('click', noopAccessor, noopAccessor, noop), INPUT_TYPE = { 'text': textWidget, 'textarea': textWidget, 'hidden': textWidget, 'password': textWidget, 'button': buttonWidget, 'submit': buttonWidget, 'reset': buttonWidget, 'image': buttonWidget, 'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)), 'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit), 'select-one': inputWidget('change', modelAccessor, valueAccessor, initWidgetValue(null)), 'select-multiple': inputWidget('change', modelAccessor, optionsAccessor, initWidgetValue([])) // 'file': fileWidget??? }; function initWidgetValue(initValue) { return function (model, view) { var value = view.get(); if (!value && isDefined(initValue)) { value = copy(initValue); } if (isUndefined(model.get()) && isDefined(value)) { model.set(value); } }; } function radioInit(model, view, element) { var modelValue = model.get(), viewValue = view.get(), input = element[0]; input.checked = false; input.name = this.$id + '@' + input.name; if (isUndefined(modelValue)) { model.set(modelValue = null); } if (modelValue == null && viewValue !== null) { model.set(viewValue); } view.set(modelValue); } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:change * * @description * The directive executes an expression whenever the input widget changes. * * @element INPUT * @param {expression} expression to execute. * * @example * @example <doc:example> <doc:source> <div ng:init="checkboxCount=0; textCount=0"></div> <input type="text" name="text" ng:change="textCount = 1 + textCount"> changeCount {{textCount}}<br/> <input type="checkbox" name="checkbox" ng:change="checkboxCount = 1 + checkboxCount"> changeCount {{checkboxCount}}<br/> </doc:source> <doc:scenario> it('should check ng:change', function(){ expect(binding('textCount')).toBe('0'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('text').enter('abc'); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('checkbox').check(); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('1'); }); </doc:scenario> </doc:example> */ function inputWidget(events, modelAccessor, viewAccessor, initFn, textBox) { return injectService(['$updateView', '$defer'], function($updateView, $defer, element) { var scope = this, model = modelAccessor(scope, element), view = viewAccessor(scope, element), action = element.attr('ng:change') || '', lastValue; if (model) { initFn.call(scope, model, view, element); this.$eval(element.attr('ng:init')||''); element.bind(events, function(event){ function handler(){ var value = view.get(); if (!textBox || value != lastValue) { model.set(value); lastValue = model.get(); scope.$tryEval(action, element); $updateView(); } } event.type == 'keydown' ? $defer(handler) : handler(); }); scope.$watch(model.get, function(value){ if (lastValue !== value) { view.set(lastValue = value); } }); } }); } function inputWidgetSelector(element){ this.directives(true); this.descend(true); return INPUT_TYPE[lowercase(element[0].type)] || noop; } angularWidget('input', inputWidgetSelector); angularWidget('textarea', inputWidgetSelector); angularWidget('button', inputWidgetSelector); angularWidget('select', function(element){ this.descend(true); return inputWidgetSelector.call(this, element); }); /* * Consider this: * <select name="selection"> * <option ng:repeat="x in [1,2]">{{x}}</option> * </select> * * The issue is that the select gets evaluated before option is unrolled. * This means that the selection is undefined, but the browser * default behavior is to show the top selection in the list. * To fix that we register a $update function on the select element * and the option creation then calls the $update function when it is * unrolled. The $update function then calls this update function, which * then tries to determine if the model is unassigned, and if so it tries to * chose one of the options from the list. */ angularWidget('option', function(){ this.descend(true); this.directives(true); return function(option) { var select = option.parent(); var isMultiple = select[0].type == 'select-multiple'; var scope = select.scope(); var model = modelAccessor(scope, select); //if parent select doesn't have a name, don't bother doing anything any more if (!model) return; var formattedModel = modelFormattedAccessor(scope, select); var view = isMultiple ? optionsAccessor(scope, select) : valueAccessor(scope, select); var lastValue = option.attr($value); var wasSelected = option.attr('ng-' + $selected); option.data($$update, isMultiple ? function(){ view.set(model.get()); } : function(){ var currentValue = option.attr($value); var isSelected = option.attr('ng-' + $selected); var modelValue = model.get(); if (wasSelected != isSelected || lastValue != currentValue) { wasSelected = isSelected; lastValue = currentValue; if (isSelected || !modelValue == null || modelValue == undefined ) formattedModel.set(currentValue); if (currentValue == modelValue) { view.set(lastValue); } } } ); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:include * * @description * Include external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ng:include won't work for file:// access). * * @param {string} src expression evaluating to URL. * @param {Scope=} [scope=new_child_scope] optional expression which evaluates to an * instance of angular.scope to set the HTML fragment to. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @example <doc:example> <doc:source> <select name="url"> <option value="api/angular.filter.date.html">date filter</option> <option value="api/angular.filter.html.html">html filter</option> <option value="">(blank)</option> </select> <tt>url = <a href="{{url}}">{{url}}</a></tt> <hr/> <ng:include src="url"></ng:include> </doc:source> <doc:scenario> it('should load date filter', function(){ expect(element('.doc-example-live ng\\:include').text()).toMatch(/angular\.filter\.date/); }); it('should change to html filter', function(){ select('url').option('api/angular.filter.html.html'); expect(element('.doc-example-live ng\\:include').text()).toMatch(/angular\.filter\.html/); }); it('should change to blank', function(){ select('url').option(''); expect(element('.doc-example-live ng\\:include').text()).toEqual(''); }); </doc:scenario> </doc:example> */ angularWidget('ng:include', function(element){ var compiler = this, srcExp = element.attr("src"), scopeExp = element.attr("scope") || '', onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537 if (element[0]['ng:compiled']) { this.descend(true); this.directives(true); } else { element[0]['ng:compiled'] = true; return extend(function(xhr, element){ var scope = this, childScope; var changeCounter = 0; var preventRecursion = false; function incrementChange(){ changeCounter++;} this.$watch(srcExp, incrementChange); this.$watch(scopeExp, incrementChange); // note that this propagates eval to the current childScope, where childScope is dynamically // bound (via $route.onChange callback) to the current scope created by $route scope.$onEval(function(){ if (childScope && !preventRecursion) { preventRecursion = true; try { childScope.$eval(); } finally { preventRecursion = false; } } }); this.$watch(function(){return changeCounter;}, function(){ var src = this.$eval(srcExp), useScope = this.$eval(scopeExp); if (src) { xhr('GET', src, null, function(code, response){ element.html(response); childScope = useScope || createScope(scope); compiler.compile(element)(childScope); scope.$eval(onloadExp); }, false, true); } else { childScope = null; element.html(''); } }); }, {$inject:['$xhr.cache']}); } }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:switch * * @description * Conditionally change the DOM structure. * * @usageContent * <any ng:switch-when="matchValue1">...</any> * <any ng:switch-when="matchValue2">...</any> * ... * <any ng:switch-default>...</any> * * @param {*} on expression to match against <tt>ng:switch-when</tt>. * @paramDescription * On child elments add: * * * `ng:switch-when`: the case statement to match against. If match then this * case will be displayed. * * `ng:switch-default`: the default case when no other casses match. * * @example <doc:example> <doc:source> <select name="switch"> <option>settings</option> <option>home</option> <option>other</option> </select> <tt>switch={{switch}}</tt> </hr> <ng:switch on="switch" > <div ng:switch-when="settings">Settings Div</div> <span ng:switch-when="home">Home Span</span> <span ng:switch-default>default</span> </ng:switch> </code> </doc:source> <doc:scenario> it('should start in settings', function(){ expect(element('.doc-example-live ng\\:switch').text()).toEqual('Settings Div'); }); it('should change to home', function(){ select('switch').option('home'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('Home Span'); }); it('should select deafault', function(){ select('switch').option('other'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('default'); }); </doc:scenario> </doc:example> */ //TODO(im): remove all the code related to using and inline equals var ngSwitch = angularWidget('ng:switch', function (element){ var compiler = this, watchExpr = element.attr("on"), usingExpr = (element.attr("using") || 'equals'), usingExprParams = usingExpr.split(":"), usingFn = ngSwitch[usingExprParams.shift()], changeExpr = element.attr('change') || '', cases = []; if (!usingFn) throw "Using expression '" + usingExpr + "' unknown."; if (!watchExpr) throw "Missing 'on' attribute."; eachNode(element, function(caseElement){ var when = caseElement.attr('ng:switch-when'); var switchCase = { change: changeExpr, element: caseElement, template: compiler.compile(caseElement) }; if (isString(when)) { switchCase.when = function(scope, value){ var args = [value, when]; forEach(usingExprParams, function(arg){ args.push(arg); }); return usingFn.apply(scope, args); }; cases.unshift(switchCase); } else if (isString(caseElement.attr('ng:switch-default'))) { switchCase.when = valueFn(true); cases.push(switchCase); } }); // this needs to be here for IE forEach(cases, function(_case){ _case.element.remove(); }); element.html(''); return function(element){ var scope = this, childScope; this.$watch(watchExpr, function(value){ var found = false; element.html(''); childScope = createScope(scope); forEach(cases, function(switchCase){ if (!found && switchCase.when(childScope, value)) { found = true; childScope.$tryEval(switchCase.change, element); switchCase.template(childScope, function(caseElement){ element.append(caseElement); }); } }); }); scope.$onEval(function(){ if (childScope) childScope.$eval(); }); }; }, { equals: function(on, when) { return ''+on == when; } }); /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with ng:click without * changing the location or causing page reloads, e.g.: * <a href="" ng:click="model.$save()">Save</a> */ angularWidget('a', function() { this.descend(true); this.directives(true); return function(element) { var hasNgHref = ((element.attr('ng:bind-attr') || '').indexOf('"href":') !== -1); // turn <a href ng:click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!hasNgHref && !element.attr('name') && !element.attr('href')) { element.attr('href', ''); } if (element.attr('href') === '' && !hasNgHref) { element.bind('click', function(event){ event.preventDefault(); }); } }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:repeat * * @description * The `ng:repeat` widget instantiates a template once per item from a collection. The collection is * enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets * its own scope, where the given loop variable is set to the current collection item, and `$index` * is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$position` – `{string}` – position of the repeated element in the iterator. One of: * * `'first'`, * * `'middle'` * * `'last'` * * Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget. * * @element ANY * @param {string} repeat_expression The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ng:repeat` to display every person: <doc:example> <doc:source> <div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng:repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng:repeat', function(){ var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ angularWidget('@ng:repeat', function(expression, element){ element.removeAttr('ng:repeat'); element.replaceWith(jqLite('<!-- ng:repeat: ' + expression + ' --!>')); var linker = this.compile(element); return function(iterStartElement){ var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ng:repeat in form of 'item in collection' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + keyValue + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; var children = [], currentScope = this; this.$onEval(function(){ var index = 0, childCount = children.length, lastIterElement = iterStartElement, collection = this.$tryEval(rhs, iterStartElement), collectionLength = size(collection, true), fragment = (element[0].nodeName != 'OPTION') ? document.createDocumentFragment() : null, addFragment, childScope, key; for (key in collection) { if (collection.hasOwnProperty(key)) { if (index < childCount) { // reuse existing child childScope = children[index]; childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; lastIterElement = childScope.$element; childScope.$eval(); } else { // grow children childScope = createScope(currentScope); childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); children.push(childScope); linker(childScope, function(clone){ clone.attr('ng:repeat-index', index); if (fragment) { fragment.appendChild(clone[0]); addFragment = true; } else { //temporarily preserve old way for option element lastIterElement.after(clone); lastIterElement = clone; } }); } index ++; } } //attach new nodes buffered in doc fragment if (addFragment) { lastIterElement.after(jqLite(fragment)); } // shrink children while(children.length > index) { children.pop().$element.remove(); } }, iterStartElement); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:non-bindable * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML. * * NOTE: `ng:non-bindable` looks like a directive, but is actually an attribute widget. * * @element ANY * * @example * In this example there are two location where a siple binding (`{{}}`) is present, but the one * wrapped in `ng:non-bindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng:non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng:non-bindable', function(){ expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ angularWidget("@ng:non-bindable", noop); /** * @ngdoc widget * @name angular.widget.ng:view * * @description * # Overview * `ng:view` is a widget that complements the {@link angular.service.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when * used like this: * * <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include> * * * # Advantages * Compared to `ng:include`, `ng:view` offers these advantages: * * - shorter syntax * - more efficient execution * - doesn't require `$route` service to be available on the root scope * * * @example <doc:example> <doc:source> <script> function MyCtrl($route) { $route.when('/overview', {controller: OverviewCtrl, template: 'guide.overview.html'}); $route.when('/bootstrap', {controller: BootstrapCtrl, template: 'guide.bootstrap.html'}); console.log(window.$route = $route); }; MyCtrl.$inject = ['$route']; function BootstrapCtrl(){} function OverviewCtrl(){} </script> <div ng:controller="MyCtrl"> <a href="#/overview">overview</a> | <a href="#/bootstrap">bootstrap</a> | <a href="#/undefined">undefined</a><br/> The view is included below: <hr/> <ng:view></ng:view> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularWidget('ng:view', function(element) { var compiler = this; if (!element[0]['ng:compiled']) { element[0]['ng:compiled'] = true; return injectService(['$xhr.cache', '$route'], function($xhr, $route, element){ var parentScope = this, childScope; $route.onChange(function(){ var src; if ($route.current) { src = $route.current.template; childScope = $route.current.scope; } if (src) { //xhr's callback must be async, see commit history for more info $xhr('GET', src, function(code, response){ element.html(response); compiler.compile(element)(childScope); }); } else { element.html(''); } })(); //initialize the state forcefully, it's possible that we missed the initial //$route#onChange already // note that this propagates eval to the current childScope, where childScope is dynamically // bound (via $route.onChange callback) to the current scope created by $route parentScope.$onEval(function() { if (childScope) { childScope.$eval(); } }); }); } else { this.descend(true); this.directives(true); } }); var browserSingleton; /** * @workInProgress * @ngdoc service * @name angular.service.$browser * @requires $log * * @description * Represents the browser. */ angularService('$browser', function($log){ if (!browserSingleton) { browserSingleton = new Browser(window, jqLite(window.document), jqLite(window.document.body), XHR, $log); browserSingleton.bind(); } return browserSingleton; }, {$inject:['$log']}); extend(angular, { 'element': jqLite, 'compile': compile, 'scope': createScope, 'copy': copy, 'extend': extend, 'equals': equals, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isArray': isArray }); //try to bind to jquery now so that one can write angular.element().read() //but we will rebind on bootstrap again. bindJQuery(); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {Function} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {Function} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {Function} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function (config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {Function} iterator Callback function(value, continueFunction) * @param {Function} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number} maxStackLines Optional. max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} Optional event type. */ function browserTrigger(element, type) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[element.type] || 'click'; } if (lowercase(nodeName_(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } if (msie < 9) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } } else { var evnt = document.createEvent('MouseEvents'); evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); element.dispatchEvent(evnt); } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown)/.test(type)) { return this.each(function(index, node) { browserTrigger(node, type); }); } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} name The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(name) { function contains(text, value) { return value instanceof RegExp ? value.test(text) : text && text.indexOf(value) >= 0; } var result = []; this.find('.ng-binding:visible').each(function() { var element = new _jQuery(this); if (!angular.isDefined(name) || contains(element.attr('ng:bind'), name) || contains(element.attr('ng:bind-template'), name)) { if (element.is('input, textarea')) { result.push(element.val()); } else { result.push(element.html()); } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().attr('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {Function} loadFn function($window, $document) Called when frame loads. * @param {Function} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.css('display', 'none').attr('src', 'about:blank'); this.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {Function} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } var $browser = $window.angular.service.$browser(); $browser.poll(); $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, _jQuery($window.document)); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {Function} future callback(error, result) * @param {Function} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {Function} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {Function} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec, step) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {Function} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { return scope.$new(angular.scenario.SpecRunner); }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.scope(this); $root.application = application; this.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = angular.scope(runner); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, specDone); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {Function} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().location().href() the full URL of the page * browser().location().hash() the full hash in the url * browser().location().path() the full path in the url * browser().location().hashSearch() the hashSearch Object from angular * browser().location().hashPath() the hashPath string from angular */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.location = function() { var api = {}; api.href = function() { return this.addFutureAction('browser url', function($window, $document, done) { done(null, $window.location.href); }); }; api.hash = function() { return this.addFutureAction('browser url hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; api.path = function() { return this.addFutureAction('browser url path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('browser url search', function($window, $document, done) { done(null, $window.angular.scope().$service('$location').search); }); }; api.hashSearch = function() { return this.addFutureAction('browser url hash search', function($window, $document, done) { done(null, $window.angular.scope().$service('$location').hashSearch); }); }; api.hashPath = function() { return this.addFutureAction('browser url hash path', function($window, $document, done) { done(null, $window.angular.scope().$service('$location').hashPath); }); }; return api; }; return function(time) { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings(name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; chain.enter = function(value) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements(':input[name="$1"]', this.name); input.val(value); input.trigger('change'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements(':checkbox[name="$1"]', this.name); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements(':radio[name$="@$1"][value="$2"]', this.name, value); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements(':input[name="$1"]', this.name); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings(binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var values = []; var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings()); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[name="$1"]', this.name); select.val(value); select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][name="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); elements.trigger('click'); if (href && elements[0].nodeName.toUpperCase() === 'A') { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var futureName = "element '" + this.label + "' get " + methodName + " '" + name + "'"; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, name, value)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var futureName = "element '" + this.label + "' " + methodName; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, value)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">&lt;angular/&gt;</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec, step) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); }; /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {Function} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); }; }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); var $runner = new angular.scenario.Runner(window), config = angularJsConfig(document); if (config.autotest) { jqLiteWrap(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n white-space: pre;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2N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QIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
web/static/js/application.js
everydayhoodie/phoenix-trello-notes
import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from './store'; import Root from './containers/root'; const store = configureStore(browserHistory); const history = syncHistoryWithStore(browserHistory, store); const target = document.getElementById('main_container'); const node = <Root routerHistory={history} store={store} />; ReactDOM.render(node, target);
src/native/components/Header.js
TeodorKolev/Help
import React from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; import { Text, H1 } from 'native-base'; import Spacer from './Spacer'; const Header = ({ title, content }) => ( <View> <Spacer size={25} /> <H1>{title}</H1> {!!content && <View> <Spacer size={10} /> <Text>{content}</Text> </View> } <Spacer size={25} /> </View> ); Header.propTypes = { title: PropTypes.string, content: PropTypes.string, }; Header.defaultProps = { title: 'Missing title', content: '', }; export default Header;
src/svg-icons/action/view-list.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewList = (props) => ( <SvgIcon {...props}> <path d="M4 14h4v-4H4v4zm0 5h4v-4H4v4zM4 9h4V5H4v4zm5 5h12v-4H9v4zm0 5h12v-4H9v4zM9 5v4h12V5H9z"/> </SvgIcon> ); ActionViewList = pure(ActionViewList); ActionViewList.displayName = 'ActionViewList'; ActionViewList.muiName = 'SvgIcon'; export default ActionViewList;
src/sites/all/modules/contrib/devel/jquery-1.4.4-uncompressed.js
codigociudadano/codigociudadano.com.ar
/*! * jQuery JavaScript Library v1.4.4 * 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: Thu Nov 11 19:04:53 2010 -0500 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document; 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 ); }, // 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 // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, rwhite = /\s/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for non-word characters rnonword = /\W/, // 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.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute 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 = { init: function( selector, context ) { 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 = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? 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] ) { 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 ? ret.fragment.cloneNode(true) : 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: $("TAG") } else if ( !context && !rnonword.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // 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 jQuery( 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.4.4", // 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.slice(num)[ 0 ] : 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 = jQuery(); 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(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( 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 || jQuery(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 ) { window.$ = _$; if ( deep ) { 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, // Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !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 if ( readyList ) { // Execute all of them var fn, i = 0, ready = readyList; // Reset the list of functions readyList = null; while ( (fn = ready[ i++ ]) ) { fn.call( document, jQuery ); } // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // 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; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. 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 ); // 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, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, 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 ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } 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.indexOf ) { return array.indexOf( 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 ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its 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" }; }, 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; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // Verify that \s matches non-breaking spaces // (IE fails on this test) if ( !rwhite.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(); } // Expose jQuery to the global object return (window.jQuery = window.$ = jQuery); })(); (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + jQuery.now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0], select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.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 insted) style: /red/.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: div.getElementsByTagName("input")[0].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, // Will be defined later deleteExpando: true, optDisabled: false, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableHiddenOffsets: true }; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as diabled) select.disabled = true; jQuery.support.optDisabled = !opt.disabled; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.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; jQuery.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>"; jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; } div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>"; var 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) jQuery.support.reliableHiddenOffsets = 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) jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; div.innerHTML = ""; document.body.removeChild( div ).style.display = "none"; div = tds = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); var windowData = {}, rbrace = /^(?:\{.*\}|\[.*\])$/; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page expando: "jQuery" + jQuery.now(), // 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 }, data: function( elem, name, data ) { if ( !jQuery.acceptData( elem ) ) { return; } elem = elem == window ? windowData : elem; var isNode = elem.nodeType, id = isNode ? elem[ jQuery.expando ] : null, cache = jQuery.cache, thisCache; if ( isNode && !id && typeof name === "string" && data === undefined ) { return; } // Get the data from the object directly if ( !isNode ) { cache = elem; // Compute a unique ID for the element } else if ( !id ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { if ( isNode ) { cache[ id ] = jQuery.extend(cache[ id ], name); } else { jQuery.extend( cache, name ); } } else if ( isNode && !cache[ id ] ) { cache[ id ] = {}; } thisCache = isNode ? cache[ id ] : cache; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( !jQuery.acceptData( elem ) ) { return; } elem = elem == window ? windowData : elem; var isNode = elem.nodeType, id = isNode ? elem[ jQuery.expando ] : elem, cache = jQuery.cache, thisCache = isNode ? cache[ id ] : id; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( isNode && jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( isNode && jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); // Completely remove the data cache } else if ( isNode ) { delete cache[ id ]; // Remove all fields from the object } else { for ( var n in elem ) { delete elem[ n ]; } } } }, // 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 ) { var attr = this[0].attributes, name; data = jQuery.data( this[0] ); for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = name.substr( 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 ) { data = elem.getAttribute( "data-" + key ); 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; } jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // 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); }); } } }); 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( i ) { 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", [] ); } }); var rclass = /[\n\t]/g, rspaces = /\s+/, rreturn = /\r/g, rspecialurl = /^(?:href|src|style)$/, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rradiocheck = /^(?:radio|checkbox)$/i; jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var 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) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), 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( rspaces ); 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].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( !arguments.length ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { // 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; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var 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 ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // 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 + ""; }); } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way // 'in' checks fail in Blackberry 4.7 #6931 if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } if ( value === null ) { if ( elem.nodeType === 1 ) { elem.removeAttribute( name ); } } else { elem[ name ] = value; } } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // 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/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } // Ensure that missing attributes return undefined // Blackberry 4.7 returns "" from getAttribute #6938 if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { return undefined; } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspace = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }, focusCounts = { focusin: 0, focusout: 0 }; /* * 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; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { elem = window; } 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; } // Use a key less likely to result in collisions for plain JS objects. // Fixes bug #7150. var eventKey = elem.nodeType ? "events" : "__events__", events = elemData[ eventKey ], eventHandle = elemData.handle; if ( typeof events === "function" ) { // On plain objects events is a fn that holds the the data // which prevents this data from being JSON serialized // the function does not need to be called, it just contains the data eventHandle = events.handle; events = events.events; } else if ( !events ) { if ( !elem.nodeType ) { // On plain objects, create a fn that acts as the holder // of the values to avoid JSON serialization of event data elemData[ eventKey ] = elemData = function(){}; } elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? 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 global triggering 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, eventKey = elem.nodeType ? "events" : "__events__", elemData = jQuery.data( elem ), events = elemData && elemData[ eventKey ]; if ( !elemData || !events ) { return; } if ( typeof events === "function" ) { elemData = events; events = events.events; } // 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 ( typeof elemData === "function" ) { jQuery.removeData( elem, eventKey ); } else if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = elem.nodeType ? jQuery.data( elem, "handle" ) : (jQuery.data( elem, "__events__" ) || {}).handle; if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; event.preventDefault(); } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (inlineError) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var old, target = event.target, targetType = type.replace( rnamespaces, "" ), isClick = jQuery.nodeName( target, "a" ) && targetType === "click", special = jQuery.event.special[ targetType ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ targetType ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + targetType ]; if ( old ) { target[ "on" + targetType ] = null; } jQuery.event.triggered = true; target[ targetType ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (triggerError) {} if ( old ) { target[ "on" + targetType ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace_re, events, namespace_sort = [], args = jQuery.makeArray( arguments ); event = args[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace_sort = namespaces.slice(0).sort(); namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.namespace = event.namespace || namespace_sort.join("."); events = jQuery.data(this, this.nodeType ? "events" : "__events__"); if ( typeof events === "function" ) { events = events.events; } handlers = (events || {})[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || 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 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); } // 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 ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // 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 parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // 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 ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { e.liveFired = undefined; return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { e.liveFired = undefined; return 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 = 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 ( elem.nodeName.toLowerCase() === "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; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return 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 = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return 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 ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { if ( focusCounts[fix]++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --focusCounts[fix] === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.trigger( e, null, e.target ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) || data === false ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : 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] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, 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; })); }, 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 ( jQuery.isFunction( data ) ) { fn = data; 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 ( type === "focus" || type === "blur" ) { 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, this.nodeType ? "events" : "__events__" ); if ( typeof events === "function" ) { events = events.events; } // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || 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 )) ) { 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]; } 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(rspace, "&"); } 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; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { jQuery(window).bind("unload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, 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; // 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(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = 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|)\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( elem ) { return elem.getAttribute( "href" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.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 && !/\W/.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" && !/\W/.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" && !/\W/.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 ) { return context.getElementsByTagName( match[1] ); } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace(/\\/g, "") + " "; 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]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace(/\\/g, ""); }, TAG: function( match, curLoop ) { return match[1].toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { // 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; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } 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 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 ) { return "text" === elem.type; }, radio: function( elem ) { return "radio" === elem.type; }, checkbox: function( elem ) { return "checkbox" === elem.type; }, file: function( elem ) { return "file" === elem.type; }, password: function( elem ) { return "password" === elem.type; }, submit: function( elem ) { return "submit" === elem.type; }, image: function( elem ) { return "image" === elem.type; }, reset: function( elem ) { return "reset" === elem.type; }, button: function( elem ) { return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); } }, 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( "Syntax error, unrecognized expression: " + 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 ) { var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // If the nodes are siblings (or identical) we can do a quick check } else 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; // Make sure that attribute selectors are quoted query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { if ( context.nodeType === 9 ) { 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 old = context.getAttribute( "id" ), nid = old || id; if ( !old ) { context.setAttribute( "id", nid ); } try { return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra ); } catch(pseudoError) { } finally { if ( !old ) { context.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, 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; } if ( matches ) { 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 ) ) { return matches.call( node, expr ); } } 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; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var 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 ( var n = length; n < ret.length; n++ ) { for ( var 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 && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; 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] = jQuery.expr.match.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; } var pos = POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; 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 ) { 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 ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // 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 || this.context ) : jQuery.makeArray( 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 ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).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 ) { 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 (html5) rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, raction = /\=([^="'>\s]+\/)>/g, 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( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(raction, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, 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.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, 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; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(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(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) 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 && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( 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 ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { 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 = []; 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" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // 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 ( var 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; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { 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 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, 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 ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { jQuery.removeEvent( elem, type, data.handle ); } } } 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 || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; 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: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": 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, 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 ) { // Make sure that NaN and null values aren't set. See: #7116 if ( typeof value === "number" && isNaN( value ) || value == null ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( typeof value === "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 ) { // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // 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, origName ); } }, // 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 ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // 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 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, 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; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN(value) ? "" : "alpha(opacity=" + value * 100 + ")", filter = style.filter || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : style.filter + ' ' + opacity; } }; } if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, newName, 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, rsLeft, ret = elem.currentStyle && elem.currentStyle[ 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; rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } 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 jsc = jQuery.now(), rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rnoContent = /^(?:GET|HEAD)$/, rbracket = /\[\]$/, jsre = /\=\?(&|$)/, rquery = /\?/, rts = /([?&])_=[^&]*/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, rhash = /#.*$/, // Keep a copy of the old load method _load = jQuery.fn.load; 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 = null; // 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: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // 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(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); 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 }; }) : { name: elem.name, value: val }; }).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.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // This function can be overriden by calling jQuery.ajaxSetup xhr: function() { return new window.XMLHttpRequest(); }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings), jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type); s.url = s.url.replace( rhash, "" ); // Use original (not extended) context object if it was provided s.context = origSettings && origSettings.context != null ? origSettings.context : s; // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading var customJsonp = window[ jsonp ]; window[ jsonp ] = function( tmp ) { if ( jQuery.isFunction( customJsonp ) ) { customJsonp( tmp ); } else { // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch( jsonpError ) {} } data = tmp; jQuery.handleSuccess( s, xhr, status, data ); jQuery.handleComplete( s, xhr, status, data ); if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && noContent ) { var ts = jQuery.now(); // try replacing _= if it is there var 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 : ""); } // If data is available, append data to url for GET/HEAD requests if ( s.data && noContent ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; jQuery.handleSuccess( s, xhr, status, data ); jQuery.handleComplete( s, xhr, status, data ); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // 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 ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set content-type if data specified and content-body is valid for this type if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*; q=0.01" : s.accepts._default ); } catch( headerError ) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && jQuery.active-- === 1 ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] ); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { jQuery.handleComplete( s, xhr, status, data ); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch( parserError ) { status = "parsererror"; errMsg = parserError; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { jQuery.handleSuccess( s, xhr, status, data ); } } else { jQuery.handleError( s, xhr, status, errMsg ); } // Fire the complete handlers if ( !jsonp ) { jQuery.handleComplete( s, xhr, status, data ); } if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { // oldAbort has no call property in IE7 so // just do it this way, which works in all // browsers Function.prototype.call.call( oldAbort, xhr ); } onreadystatechange( "abort" ); }; } catch( abortError ) {} // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( noContent || s.data == null ? null : s.data ); } catch( sendError ) { jQuery.handleError( s, xhr, null, sendError ); // Fire the complete handlers jQuery.handleComplete( s, xhr, status, data ); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, // 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 ) { // 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) && obj.length ) { // 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" ) { if ( jQuery.isEmptyObject( obj ) ) { add( prefix, "" ); // Serialize object item. } else { jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v, 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: {}, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context, xhr, status, e ); } // Fire the global callback if ( s.global ) { jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] ); } }, handleSuccess: function( s, xhr, status, data ) { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( s.context, data, status, xhr ); } // Fire the global callback if ( s.global ) { jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] ); } }, handleComplete: function( s, xhr, status ) { // Process result if ( s.complete ) { s.complete.call( s.context, xhr, status ); } // The request was completed if ( s.global ) { jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && jQuery.active-- === 1 ) { jQuery.event.trigger( "ajaxStop" ); } }, triggerGlobal: function( s, type, args ) { (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args); }, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 || xhr.status === 1223; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } return xhr.status === 304; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; } }); /* * Create the request object; 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. */ if ( window.ActiveXObject ) { jQuery.ajaxSettings.xhr = function() { if ( window.location.protocol !== "file:" ) { try { return new window.XMLHttpRequest(); } catch(xhrError) {} } try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(activeError) {} }; } // Does this browser support XHR requests? jQuery.support.ajax = !!jQuery.ajaxSettings.xhr(); var elemdisplay = {}, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; 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]; 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]; 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++ ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" ) { 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++ ) { 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 ); } return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite var opt = jQuery.extend({}, optall), p, isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( isElement && ( p === "height" || p === "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 { var 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 ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur() || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { jQuery.style( self, name, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( self, name, 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 ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; 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; } }); 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() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( 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; if ( !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 r = parseFloat( jQuery.css( this.elem, this.prop ) ); return r && r > -10000 ? r : 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = jQuery.now(); this.start = from; this.end = to; this.unit = unit || this.unit || "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 = jQuery.now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { var elem = this.elem, options = this.options; jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; } ); } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style( this.elem, p, this.options.orig[p] ); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.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() { var timers = jQuery.timers; for ( var 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; }; } function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery("<" + nodeName + ">").appendTo("body"), display = elem.css("display"); elem.remove(); if ( display === "none" || display === "" ) { display = "block"; } 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: 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 ); body = container = innerDiv = checkDiv = table = td = null; 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" && 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 absolute if ( calculatePosition ) { curPosition = curElem.position(); } curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0; curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 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 = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // 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; } }); } else { 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 ]; } }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create 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() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], 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 return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ]; // 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" ); } }; }); })(window);
ajax/libs/angular-google-maps/2.1.0-X.2/angular-google-maps_dev_mapped.js
lobbin/cdnjs
/*! angular-google-maps 2.1.0-X.2 2015-03-10 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/angular-google-maps.git */ ; (function( window, angular, undefined ){ 'use strict'; /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/angular-ui/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps.providers', []); angular.module('uiGmapgoogle-maps.wrapped', []); angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']); angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']); angular.module('uiGmapgoogle-maps.directives.api.managers', []); angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']); angular.module('uiGmapgoogle-maps.directives.api.options.builders', []); angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']); angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']); angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']); angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [ '$q', 'uiGmapuuid', function($q, uuid) { var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId; scriptId = void 0; getScriptUrl = function(options) { if (options.china) { return 'http://maps.google.cn/maps/api/js?'; } else { return 'https://maps.googleapis.com/maps/api/js?'; } }; includeScript = function(options) { var query, script; query = _.map(options, function(v, k) { return k + '=' + v; }); if (scriptId) { document.getElementById(scriptId).remove(); } query = query.join('&'); script = document.createElement('script'); script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate()); script.type = 'text/javascript'; script.src = getScriptUrl(options) + query; return document.body.appendChild(script); }; isGoogleMapsLoaded = function() { return angular.isDefined(window.google) && angular.isDefined(window.google.maps); }; return { load: function(options) { var deferred, randomizedFunctionName; deferred = $q.defer(); if (isGoogleMapsLoaded()) { deferred.resolve(window.google.maps); return deferred.promise; } randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000); window[randomizedFunctionName] = function() { window[randomizedFunctionName] = null; deferred.resolve(window.google.maps); }; if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE) { document.addEventListener('online', function() { if (!isGoogleMapsLoaded()) { return includeScript(options); } }); } else { includeScript(options); } return deferred.promise; } }; } ]).provider('uiGmapGoogleMapApi', function() { this.options = { china: false, v: '3.17', libraries: '', language: 'en', sensor: 'false' }; this.configure = function(options) { angular.extend(this.options, options); }; this.$get = [ 'uiGmapMapScriptLoader', (function(_this) { return function(loader) { return loader.load(_this.options); }; })(this) ]; return this; }); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() { return { init: _.once(function() { var uiGmapInfoBox; if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) { if (recurse != null) { return; } this._isOpen = true; this._open(map, anchor, true); }; google.maps.InfoWindow.prototype.close = function(recurse) { if (recurse != null) { return; } this._isOpen = false; this._close(true); }; google.maps.InfoWindow.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; /* Do the same for InfoBox TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier */ if (window.InfoBox) { window.InfoBox.prototype._open = window.InfoBox.prototype.open; window.InfoBox.prototype._close = window.InfoBox.prototype.close; window.InfoBox.prototype._isOpen = false; window.InfoBox.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; window.InfoBox.prototype.close = function() { this._isOpen = false; this._close(); }; window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; uiGmapInfoBox = (function(_super) { __extends(uiGmapInfoBox, _super); function uiGmapInfoBox(opts) { this.getOrigCloseBoxImg_ = __bind(this.getOrigCloseBoxImg_, this); this.getCloseBoxDiv_ = __bind(this.getCloseBoxDiv_, this); var box; box = new window.InfoBox(opts); _.extend(this, box); if (opts.closeBoxDiv != null) { this.closeBoxDiv_ = opts.closeBoxDiv; } } uiGmapInfoBox.prototype.getCloseBoxDiv_ = function() { return this.closeBoxDiv_; }; uiGmapInfoBox.prototype.getCloseBoxImg_ = function() { var div, img; div = this.getCloseBoxDiv_(); img = this.getOrigCloseBoxImg_(); return div || img; }; uiGmapInfoBox.prototype.getOrigCloseBoxImg_ = function() { var img; img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; img += " style='"; img += " position: relative;"; img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; return uiGmapInfoBox; })(window.InfoBox); window.uiGmapInfoBox = uiGmapInfoBox; } if (window.MarkerLabel_) { return window.MarkerLabel_.prototype.setContent = function() { var content; content = this.marker_.get('labelContent'); if (!content || _.isEqual(this.oldContent, content)) { return; } if (typeof (content != null ? content.nodeType : void 0) === 'undefined') { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; this.oldContent = content; } else { this.labelDiv_.innerHTML = ''; this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.labelDiv_.innerHTML = ''; this.eventDiv_.appendChild(content); this.oldContent = content; } }; } }) }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() { /* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ this.intersectionObjects = function(array1, array2, comparison) { var res; if (comparison == null) { comparison = void 0; } res = _.map(array1, (function(_this) { return function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }; })(this)); return _.filter(res, function(o) { return o != null; }); }; this.containsObject = _.includeObject = function(obj, target, comparison) { if (comparison == null) { comparison = void 0; } if (obj === null) { return false; } return _.any(obj, (function(_this) { return function(value) { if (comparison != null) { return comparison(value, target); } else { return _.isEqual(value, target); } }; })(this)); }; this.differenceObjects = function(array1, array2, comparison) { if (comparison == null) { comparison = void 0; } return _.filter(array1, (function(_this) { return function(value) { return !_this.containsObject(array2, value, comparison); }; })(this)); }; this.withoutObjects = this.differenceObjects; this.indexOfObject = function(array, item, comparison, isSorted) { var i, length; if (array == null) { return -1; } i = 0; length = array.length; if (isSorted) { if (typeof isSorted === "number") { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return (array[i] === item ? i : -1); } } while (i < length) { if (comparison != null) { if (comparison(array[i], item)) { return i; } } else { if (_.isEqual(array[i], item)) { return i; } } i++; } return -1; }; this["extends"] = function(arrayOfObjectsToCombine) { return _.reduce(arrayOfObjectsToCombine, function(combined, toAdd) { return _.extend(combined, toAdd); }, {}); }; this.isNullOrUndefined = function(thing) { return _.isNull(thing || _.isUndefined(thing)); }; return this; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() { return function(str) { this.contains = function(value, fromIndex) { return str.indexOf(value, fromIndex) !== -1; }; return this; }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [ function() { return { fakePromise: function() { var _cb; _cb = void 0; return { then: function(cb) { return _cb = cb; }, resolve: function() { return _cb.apply(void 0, arguments); } }; } }; } ]).service('uiGmap_async', [ '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) { var ExposedPromise, PromiseQueueManager, SniffedPromise, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch, _getArrayAndKeys, _getIterateeValue; promiseTypes = uiGmapPromise.promiseTypes; isInProgress = uiGmapPromise.isInProgress; promiseStatus = uiGmapPromise.promiseStatus; ExposedPromise = uiGmapPromise.ExposedPromise; SniffedPromise = uiGmapPromise.SniffedPromise; kickPromise = function(sniffedPromise, cancelCb) { var promise; promise = sniffedPromise.promise(); promise.promiseType = sniffedPromise.promiseType; if (promise.$$state) { $log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status))); } promise.cancelCb = cancelCb; return promise; }; doSkippPromise = function(sniffedPromise, lastPromise) { if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) { $log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY"); return true; } return false; }; maybeCancelPromises = function(queue, sniffedPromise, lastPromise) { var first; if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) { if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) { $log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType); lastPromise.cancelCb('cancel safe'); first = queue.peek(); if ((first != null) && isInProgress(first)) { if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) { $log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType); return first.cancelCb('cancel safe'); } else { return $log.warn('first promise was not cancelable'); } } } } }; /* From a High Level: This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces. This is a function and should not be considered a class. So it is run to manage the state (cancel, skip, link) as needed. Purpose: The whole point is to check if there is existing async work going on. If so we wait on it. arguments: - existingPiecesObj = Queue<Promises> - sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise) with its intended type. - cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise gracefully without messing up state. Synopsis: - Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering) where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete - Every Promise that comes is is enqueue and linked to the last promise in the queue. - A promise can be skipped or canceled to save cycles. Saved Cycles: - Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in after a delete promise. - Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type. NOTE: - You should not muck with existingPieces as its state is dependent on this functional loop. - PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces. */ PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) { var lastPromise, newPromise; if (!existingPiecesObj.existingPieces) { existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue(); return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb)); } else { lastPromise = _.last(existingPiecesObj.existingPieces._content); if (doSkippPromise(sniffedPromise, lastPromise)) { return; } maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise); newPromise = ExposedPromise(lastPromise["finally"](function() { return kickPromise(sniffedPromise, cancelCb); })); newPromise.cancelCb = cancelCb; newPromise.promiseType = sniffedPromise.promiseType; existingPiecesObj.existingPieces.enqueue(newPromise); return lastPromise["finally"](function() { return existingPiecesObj.existingPieces.dequeue(); }); } }; managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) { var cancelLogger; if (msg == null) { msg = ''; } cancelLogger = function(msg) { $log.debug("" + msg + ": " + msg); return cancelCb(msg); }; return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger); }; defaultChunkSize = 80; errorObject = { value: null }; tryCatch = function(fn, ctx, args) { var e; try { return fn.apply(ctx, args); } catch (_error) { e = _error; errorObject.value = e; return errorObject; } }; logTryCatch = function(fn, ctx, deferred, args) { var msg, result; result = tryCatch(fn, ctx, args); if (result === errorObject) { msg = "error within chunking iterator: " + errorObject.value; $log.error(msg); deferred.reject(msg); } if (result === 'cancel safe') { return false; } return true; }; _getIterateeValue = function(collection, array, index) { var valOrKey, _isArray; _isArray = collection === array; valOrKey = array[index]; if (_isArray) { return valOrKey; } return collection[valOrKey]; }; _getArrayAndKeys = function(collection, keys, bailOutCb, cb) { var array; if (angular.isArray(collection)) { array = collection; } else { array = keys ? keys : Object.keys(_.omit(collection, 'length')); keys = array; } if (cb == null) { cb = bailOutCb; } if (angular.isArray(array) && (array === void 0 || (array != null ? array.length : void 0) <= 0)) { if (cb !== bailOutCb) { return bailOutCb(); } } return cb(array, keys); }; /* Author: Nicholas McCready & jfriend00 _async handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui The design of any functionality of _async is to be like lodash/underscore and replicate it but call things asynchronously underneath. Each should be sufficient for most things to be derived from. Optional Asynchronous Chunking via promises. */ doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) { return _getArrayAndKeys(collection, _keys, function(array, keys) { var cnt, i, keepGoing; if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) { cnt = chunkSizeOrDontChunk; } else { cnt = array.length; } i = index; keepGoing = true; while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) { keepGoing = logTryCatch(chunkCb, void 0, overallD, [_getIterateeValue(collection, array, i), i]); ++i; } if (array) { if (keepGoing && i < array.length) { index = i; if (chunkSizeOrDontChunk) { if ((pauseCb != null) && _.isFunction(pauseCb)) { logTryCatch(pauseCb, void 0, overallD, []); } return $timeout(function() { return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys); }, pauseMilli, false); } } else { return overallD.resolve(); } } }); }; each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var error, overallD, ret; if (chunkSizeOrDontChunk == null) { chunkSizeOrDontChunk = defaultChunkSize; } if (index == null) { index = 0; } if (pauseMilli == null) { pauseMilli = 1; } ret = void 0; overallD = uiGmapPromise.defer(); ret = overallD.promise; if (!pauseMilli) { error = 'pause (delay) must be set from _async!'; $log.error(error); overallD.reject(error); return ret; } return _getArrayAndKeys(collection, _keys, function() { overallD.resolve(); return ret; }, function(array, keys) { doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys); return ret; }); }; map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var results; results = []; return _getArrayAndKeys(collection, _keys, function() { return uiGmapPromise.resolve(results); }, function(array, keys) { return each(collection, function(o) { return results.push(iterator(o)); }, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() { return results; }); }); }; return { each: each, map: map, managePromiseQueue: managePromiseQueue, promiseLock: managePromiseQueue, defaultChunkSize: defaultChunkSize, chunkSizeFrom: function(fromSize, ret) { if (ret == null) { ret = void 0; } if (_.isNumber(fromSize)) { ret = fromSize; } if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) { ret = false; } return ret; } }; } ]); }).call(this); ;(function() { var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() { var BaseObject, baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((_ref = obj.extended) != null) { _ref.apply(this); } return this; }; BaseObject.include = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((_ref = obj.included) != null) { _ref.apply(this); } return this; }; return BaseObject; })(); return BaseObject; }); }).call(this); ; /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() { return { onChildCreation: function(child) {} }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.$on('$destroy', function() { return CtrlHandle.handle($scope); }); $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [ "uiGmapLogger", function($log) { return { setEvents: function(gObject, scope, model, ignores) { if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) { return _.compact(_.map(scope.events, function(eventHandler, eventName) { var doIgnore; if (ignores) { doIgnore = _(ignores).contains(eventName); } if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName]) && !doIgnore) { return google.maps.event.addListener(gObject, eventName, function() { if (!scope.$evalAsync) { scope.$evalAsync = function() {}; } return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments])); }); } })); } }, removeEvents: function(listeners) { if (!listeners) { return; } return listeners.forEach(function(l) { if (l) { return google.maps.event.removeListener(l); } }); } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [ 'uiGmapLogger', 'uiGmap_async', function($log, _async) { return { fit: function(gMarkers, gMap) { var bounds, everSet; if (gMap && gMarkers && gMarkers.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; gMarkers.forEach((function(_this) { return function(gMarker) { if (gMarker) { if (!everSet) { everSet = true; } return bounds.extend(gMarker.getPosition()); } }; })(this)); if (everSet) { return gMap.fitBounds(bounds); } } } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [ 'uiGmapLogger', '$compile', function(Logger, $compile) { var getCoords, getLatitude, getLongitude, validateCoords, _isFalse, _isTruthy; _isTruthy = function(value, bool, optionsArray) { return value === bool || optionsArray.indexOf(value) !== -1; }; _isFalse = function(value) { return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']); }; getLatitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[1]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[1]; } else { return value.latitude; } }; getLongitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[0]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[0]; } else { return value.longitude; } }; getCoords = function(value) { if (!value) { return; } if (Array.isArray(value) && value.length === 2) { return new google.maps.LatLng(value[1], value[0]); } else if (angular.isDefined(value.type) && value.type === 'Point') { return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]); } else { return new google.maps.LatLng(value.latitude, value.longitude); } }; validateCoords = function(coords) { if (angular.isUndefined(coords)) { return false; } if (_.isArray(coords)) { if (coords.length === 2) { return true; } } else if ((coords != null) && (coords != null ? coords.type : void 0)) { if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) { return true; } } if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) { return true; } return false; }; return { setCoordsFromEvent: function(prevValue, newLatLon) { if (!prevValue) { return; } if (Array.isArray(prevValue) && prevValue.length === 2) { prevValue[1] = newLatLon.lat(); prevValue[0] = newLatLon.lng(); } else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') { prevValue.coordinates[1] = newLatLon.lat(); prevValue.coordinates[0] = newLatLon.lng(); } else { prevValue.latitude = newLatLon.lat(); prevValue.longitude = newLatLon.lng(); } return prevValue; }, getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor); xPos = parseFloat(anchor[1]); yPos = parseFloat(anchor[2]); if ((xPos != null) && (yPos != null)) { return new google.maps.Point(xPos, yPos); } }, createWindowOptions: function(gMarker, scope, content, defaults) { var options; if ((content != null) && (defaults != null) && ($compile != null)) { options = angular.extend({}, defaults, { content: this.buildContent(scope, defaults, content), position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords) }); if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) { if (options.boxClass == null) { } else { options.pixelOffset = { height: 0, width: -2 }; } } return options; } else { if (!defaults) { Logger.error('infoWindow defaults not defined'); if (!content) { return Logger.error('infoWindow content not defined'); } } else { return defaults; } } }, buildContent: function(scope, defaults, content) { var parsed, ret; if (defaults.content != null) { ret = defaults.content; } else { if ($compile != null) { content = content.replace(/^\s+|\s+$/g, ''); parsed = content === '' ? '' : $compile(content)(scope); if (parsed.length > 0) { ret = parsed[0]; } } else { ret = content; } } return ret; }, defaultDelay: 50, isTrue: function(value) { return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']); }, isFalse: _isFalse, isFalsy: function(value) { return _isTruthy(value, false, [void 0, null]) || _isFalse(value); }, getCoords: getCoords, validateCoords: validateCoords, equalCoords: function(coord1, coord2) { return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2); }, validatePath: function(path) { var array, i, polygon, trackMaxVertices; i = 0; if (angular.isUndefined(path.type)) { if (!Array.isArray(path) || path.length < 2) { return false; } while (i < path.length) { if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) { return false; } i++; } return true; } else { if (angular.isUndefined(path.coordinates)) { return false; } if (path.type === 'Polygon') { if (path.coordinates[0].length < 4) { return false; } array = path.coordinates[0]; } else if (path.type === 'MultiPolygon') { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); polygon = path.coordinates[trackMaxVertices.index]; array = polygon[0]; if (array.length < 4) { return false; } } else if (path.type === 'LineString') { if (path.coordinates.length < 2) { return false; } array = path.coordinates; } else { return false; } while (i < array.length) { if (array[i].length !== 2) { return false; } i++; } return true; } }, convertPathPoints: function(path) { var array, i, latlng, result, trackMaxVertices; i = 0; result = new google.maps.MVCArray(); if (angular.isUndefined(path.type)) { while (i < path.length) { latlng; if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) { latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude); } else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') { latlng = path[i]; } result.push(latlng); i++; } } else { array; if (path.type === 'Polygon') { array = path.coordinates[0]; } else if (path.type === 'MultiPolygon') { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); array = path.coordinates[trackMaxVertices.index][0]; } else if (path.type === 'LineString') { array = path.coordinates; } while (i < array.length) { result.push(new google.maps.LatLng(array[i][1], array[i][0])); i++; } } return result; }, extendMapBounds: function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }, getPath: function(object, key) { var obj; if ((key == null) || !_.isString(key)) { return key; } obj = object; _.each(key.split('.'), function(value) { if (obj) { return obj = obj[value]; } }); return obj; }, validateBoundPoints: function(bounds) { if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) { return false; } return true; }, convertBoundPoints: function(bounds) { var result; result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude)); return result; }, fitMapBounds: function(map, bounds) { return map.fitBounds(bounds); } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [ '$q', '$timeout', function($q, $timeout) { var ctr, promises, proms; ctr = 0; proms = []; promises = function() { return $q.all(proms); }; return { spawn: function() { var d; d = $q.defer(); proms.push(d.promise); ctr += 1; return { instance: ctr, deferred: d }; }, promises: promises, instances: function() { return ctr; }, promise: function(expect) { var d, ohCrap; if (expect == null) { expect = 1; } d = $q.defer(); ohCrap = function() { return $timeout(function() { if (ctr !== expect) { return ohCrap(); } else { return d.resolve(promises()); } }); }; ohCrap(); return d.promise; }, reset: function() { ctr = 0; return proms.length = 0; } }; } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [ "uiGmapBaseObject", function(BaseObject) { var Linked; Linked = (function(_super) { __extends(Linked, _super); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(BaseObject); return Linked; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [ '$log', function($log) { var LEVELS, Logger, log, maybeExecLevel; LEVELS = { log: 1, info: 2, debug: 3, warn: 4, error: 5, none: 6 }; maybeExecLevel = function(level, current, fn) { if (level >= current) { return fn(); } }; log = function(logLevelFnName, msg) { if ($log != null) { return $log[logLevelFnName](msg); } else { return console[logLevelFnName](msg); } }; Logger = (function() { function Logger() { var logFns; this.doLog = true; logFns = {}; ['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) { return function(level) { return logFns[level] = function(msg) { if (_this.doLog) { return maybeExecLevel(LEVELS[level], _this.currentLevel, function() { return log(level, msg); }); } }; }; })(this)); this.LEVELS = LEVELS; this.currentLevel = LEVELS.error; this.log = logFns['log']; this.info = logFns['info']; this.debug = logFns['debug']; this.warn = logFns['warn']; this.error = logFns['error']; } Logger.prototype.spawn = function() { return new Logger(); }; Logger.prototype.setLog = function(someLogger) { return $log = someLogger; }; return Logger; })(); return new Logger(); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) { var ModelKey; return ModelKey = (function(_super) { __extends(ModelKey, _super); function ModelKey(scope) { this.scope = scope; this.modelsLength = __bind(this.modelsLength, this); this.updateChild = __bind(this.updateChild, this); this.destroy = __bind(this.destroy, this); this.onDestroy = __bind(this.onDestroy, this); this.setChildScope = __bind(this.setChildScope, this); this.getChanges = __bind(this.getChanges, this); this.getProp = __bind(this.getProp, this); this.setIdKey = __bind(this.setIdKey, this); this.modelKeyComparison = __bind(this.modelKeyComparison, this); ModelKey.__super__.constructor.call(this); this["interface"] = {}; this["interface"].scopeKeys = []; this.defaultIdKey = 'id'; this.idKey = void 0; } ModelKey.prototype.evalModelHandle = function(model, modelKey) { if ((model == null) || (modelKey == null)) { return; } if (modelKey === 'self') { return model; } else { if (_.isFunction(modelKey)) { modelKey = modelKey(); } return GmapUtil.getPath(model, modelKey); } }; ModelKey.prototype.modelKeyComparison = function(model1, model2) { var hasCoords, isEqual, scope; hasCoords = _.contains(this["interface"].scopeKeys, 'coords'); if (hasCoords && (this.scope.coords != null) || !hasCoords) { scope = this.scope; } if (scope == null) { throw 'No scope set!'; } if (hasCoords) { isEqual = GmapUtil.equalCoords(this.scopeOrModelVal('coords', scope, model1), this.scopeOrModelVal('coords', scope, model2)); if (!isEqual) { return isEqual; } } isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) { return function(k) { return _this.scopeOrModelVal(scope[k], scope, model1) === _this.scopeOrModelVal(scope[k], scope, model2); }; })(this)); return isEqual; }; ModelKey.prototype.setIdKey = function(scope) { return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey; }; ModelKey.prototype.setVal = function(model, key, newValue) { var thingToSet; thingToSet = this.modelOrKey(model, key); thingToSet = newValue; return model; }; ModelKey.prototype.modelOrKey = function(model, key) { if (key == null) { return; } if (key !== 'self') { return model[key]; } return model; }; ModelKey.prototype.getProp = function(propName, scope, model) { return this.scopeOrModelVal(propName, scope, model); }; /* For the cases were watching a large object we only want to know the list of props that actually changed. Also we want to limit the amount of props we analyze to whitelisted props that are actually tracked by scope. (should make things faster with whitelisted) */ ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) { var c, changes, prop; if (whitelistedProps) { prev = _.pick(prev, whitelistedProps); now = _.pick(now, whitelistedProps); } changes = {}; prop = {}; c = {}; for (prop in now) { if (!prev || prev[prop] !== now[prop]) { if (_.isArray(now[prop])) { changes[prop] = now[prop]; } else if (_.isObject(now[prop])) { c = this.getChanges(now[prop], (prev ? prev[prop] : null)); if (!_.isEmpty(c)) { changes[prop] = c; } } else { changes[prop] = now[prop]; } } } return changes; }; ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) { var maybeWrap, modelKey, modelProp, scopeProp; if (doWrap == null) { doWrap = false; } maybeWrap = function(isScope, ret, doWrap) { if (doWrap == null) { doWrap = false; } if (doWrap) { return { isScope: isScope, value: ret }; } return ret; }; scopeProp = scope[key]; if (_.isFunction(scopeProp)) { return maybeWrap(true, scopeProp(model), doWrap); } if (_.isObject(scopeProp)) { return maybeWrap(true, scopeProp, doWrap); } if (!_.isString(scopeProp)) { return maybeWrap(true, scopeProp, doWrap); } modelKey = scopeProp; if (!modelKey) { modelProp = model[key]; } else { modelProp = modelKey === 'self' ? model : model[modelKey]; } if (_.isFunction(modelProp)) { return maybeWrap(false, modelProp(), doWrap); } return maybeWrap(false, modelProp, doWrap); }; ModelKey.prototype.setChildScope = function(keys, childScope, model) { _.each(keys, (function(_this) { return function(name) { var isScopeObj, newValue; isScopeObj = _this.scopeOrModelVal(name, childScope, model, true); if ((isScopeObj != null ? isScopeObj.value : void 0) != null) { newValue = isScopeObj.value; if (newValue !== childScope[name]) { return childScope[name] = newValue; } } }; })(this)); return childScope.model = model; }; ModelKey.prototype.onDestroy = function(scope) {}; ModelKey.prototype.destroy = function(manualOverride) { var _ref; if (manualOverride == null) { manualOverride = false; } if ((this.scope != null) && !((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { return this.scope.$destroy(); } else { return this.clean(); } }; ModelKey.prototype.updateChild = function(child, model) { if (model[this.idKey] == null) { this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } return child.updateModel(model); }; ModelKey.prototype.modelsLength = function() { var len; len = 0; if (this.scope.models == null) { return len; } if (angular.isArray(this.scope.models) || (this.scope.models.length != null)) { len = this.scope.models.length; } else { len = Object.keys(this.scope.models).length; } return len; }; return ModelKey; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [ 'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) { return { didQueueInitPromise: function(existingPiecesObj, scope) { if (scope.models.length === 0) { _async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) { return function() { return uiGmapPromise.resolve(); }; })(this))); return true; } return false; }, figureOutState: function(idKey, scope, childObjects, comparison, callBack) { var adds, children, mappedScopeModelIds, removals, updates; adds = []; mappedScopeModelIds = {}; removals = []; updates = []; scope.models.forEach(function(m) { var child; if (m[idKey] != null) { mappedScopeModelIds[m[idKey]] = {}; if (childObjects.get(m[idKey]) == null) { return adds.push(m); } else { child = childObjects.get(m[idKey]); if (!comparison(m, child.clonedModel, scope)) { return updates.push({ model: m, child: child }); } } } else { return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion'); } }); children = childObjects.values(); children.forEach(function(c) { var id; if (c == null) { Logger.error('child undefined in ModelsWatcher.'); return; } if (c.model == null) { Logger.error('child.model undefined in ModelsWatcher.'); return; } id = c.model[idKey]; if (mappedScopeModelIds[id] == null) { return removals.push(c); } }); return { adds: adds, removals: removals, updates: updates }; } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [ '$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) { var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses; promiseTypes = { create: 'create', update: 'update', "delete": 'delete', init: 'init' }; promiseStatuses = { IN_PROGRESS: 0, RESOLVED: 1, REJECTED: 2 }; strPromiseStatuses = (function() { var obj; obj = {}; obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress'; obj["" + promiseStatuses.RESOLVED] = 'resolved'; obj["" + promiseStatuses.REJECTED] = 'rejected'; return obj; })(); isInProgress = function(promise) { if (promise.$$state) { return promise.$$state.status === promiseStatuses.IN_PROGRESS; } if (!promise.hasOwnProperty("$$v")) { return true; } }; isResolved = function(promise) { if (promise.$$state) { return promise.$$state.status === promiseStatuses.RESOLVED; } if (promise.hasOwnProperty("$$v")) { return true; } }; promiseStatus = function(status) { return strPromiseStatuses[status] || 'done w error'; }; ExposedPromise = function(promise) { var cancelDeferred, combined, wrapped; cancelDeferred = $q.defer(); combined = $q.all([promise, cancelDeferred.promise]); wrapped = $q.defer(); promise.then(cancelDeferred.resolve, (function() {}), function(notify) { cancelDeferred.notify(notify); return wrapped.notify(notify); }); combined.then(function(successes) { return wrapped.resolve(successes[0] || successes[1]); }, function(error) { return wrapped.reject(error); }); wrapped.promise.cancel = function(reason) { if (reason == null) { reason = 'canceled'; } return cancelDeferred.reject(reason); }; wrapped.promise.notify = function(msg) { if (msg == null) { msg = 'cancel safe'; } wrapped.notify(msg); if (promise.hasOwnProperty('notify')) { return promise.notify(msg); } }; if (promise.promiseType != null) { wrapped.promise.promiseType = promise.promiseType; } return wrapped.promise; }; SniffedPromise = function(fnPromise, promiseType) { return { promise: fnPromise, promiseType: promiseType }; }; defer = function() { return $q.defer(); }; resolve = function() { var d; d = $q.defer(); d.resolve.apply(void 0, arguments); return d.promise; }; promise = function(fnToWrap) { var d; if (!_.isFunction(fnToWrap)) { $log.error("uiGmapPromise.promise() only accepts functions"); return; } d = $q.defer(); $timeout(function() { var result; result = fnToWrap(); return d.resolve(result); }); return d.promise; }; return { defer: defer, promise: promise, resolve: resolve, promiseTypes: promiseTypes, isInProgress: isInProgress, isResolved: isResolved, promiseStatus: promiseStatus, ExposedPromise: ExposedPromise, SniffedPromise: SniffedPromise }; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() { /* Simple Object Map with a length property to make it easy to track length/size */ var PropMap; return PropMap = (function() { function PropMap() { this.removeAll = __bind(this.removeAll, this); this.slice = __bind(this.slice, this); this.push = __bind(this.push, this); this.keys = __bind(this.keys, this); this.values = __bind(this.values, this); this.remove = __bind(this.remove, this); this.put = __bind(this.put, this); this.stateChanged = __bind(this.stateChanged, this); this.get = __bind(this.get, this); this.length = 0; this.dict = {}; this.didValsStateChange = false; this.didKeysStateChange = false; this.allVals = []; this.allKeys = []; } PropMap.prototype.get = function(key) { return this.dict[key]; }; PropMap.prototype.stateChanged = function() { this.didValsStateChange = true; return this.didKeysStateChange = true; }; PropMap.prototype.put = function(key, value) { if (this.get(key) == null) { this.length++; } this.stateChanged(); return this.dict[key] = value; }; PropMap.prototype.remove = function(key, isSafe) { var value; if (isSafe == null) { isSafe = false; } if (isSafe && !this.get(key)) { return void 0; } value = this.dict[key]; delete this.dict[key]; this.length--; this.stateChanged(); return value; }; PropMap.prototype.valuesOrKeys = function(str) { var keys, vals; if (str == null) { str = 'Keys'; } if (!this["did" + str + "StateChange"]) { return this['all' + str]; } vals = []; keys = []; _.each(this.dict, function(v, k) { vals.push(v); return keys.push(k); }); this.didKeysStateChange = false; this.didValsStateChange = false; this.allVals = vals; this.allKeys = keys; return this['all' + str]; }; PropMap.prototype.values = function() { return this.valuesOrKeys('Vals'); }; PropMap.prototype.keys = function() { return this.valuesOrKeys(); }; PropMap.prototype.push = function(obj, key) { if (key == null) { key = "key"; } return this.put(obj[key], obj); }; PropMap.prototype.slice = function() { return this.keys().map((function(_this) { return function(k) { return _this.remove(k); }; })(this)); }; PropMap.prototype.removeAll = function() { return this.slice(); }; PropMap.prototype.each = function(cb) { return _.each(this.dict, function(v, k) { return cb(v); }); }; PropMap.prototype.map = function(cb) { return _.map(this.dict, function(v, k) { return cb(v); }); }; return PropMap; })(); }); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [ "uiGmapLogger", function(Logger) { var PropertyAction; PropertyAction = function(setterFn) { this.setIfChange = function(newVal, oldVal) { var callingKey; callingKey = this.exp; if (!_.isEqual(oldVal, newVal)) { return setterFn(callingKey, newVal); } }; this.sic = this.setIfChange; return this; }; return PropertyAction; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [ 'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', function($log, FitHelper, PropMap) { var ClustererMarkerManager; ClustererMarkerManager = (function() { ClustererMarkerManager.type = 'ClustererMarkerManager'; function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) { if (opt_markers == null) { opt_markers = {}; } this.opt_options = opt_options != null ? opt_options : {}; this.opt_events = opt_events; this.checkSync = __bind(this.checkSync, this); this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.destroy = __bind(this.destroy, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.update = __bind(this.update, this); this.add = __bind(this.add, this); this.type = ClustererMarkerManager.type; this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options); this.propMapGMarkers = new PropMap(); this.attachEvents(this.opt_events, 'opt_events'); this.clusterer.setIgnoreHidden(true); this.noDrawOnSingleAddRemoves = true; $log.info(this); } ClustererMarkerManager.prototype.checkKey = function(gMarker) { var msg; if (gMarker.key == null) { msg = 'gMarker.key undefined and it is REQUIRED!!'; return $log.error(msg); } }; ClustererMarkerManager.prototype.add = function(gMarker) { this.checkKey(gMarker); this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.put(gMarker.key, gMarker); return this.checkSync(); }; ClustererMarkerManager.prototype.update = function(gMarker) { this.remove(gMarker); return this.add(gMarker); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.remove(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.removeMany(this.getGMarkers()); return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Attaching event: " + eventName + " to clusterer"); _results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName])); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.clearEvents = function(options, optionsName) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Clearing event: " + eventName + " to clusterer"); _results.push(google.maps.event.clearListeners(this.clusterer, eventName)); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.destroy = function() { this.clearEvents(this.opt_events, 'opt_events'); return this.clear(); }; ClustererMarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap()); }; ClustererMarkerManager.prototype.getGMarkers = function() { return this.clusterer.getMarkers().values(); }; ClustererMarkerManager.prototype.checkSync = function() {}; return ClustererMarkerManager; })(); return ClustererMarkerManager; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [ "uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) { var MarkerManager; MarkerManager = (function() { MarkerManager.type = 'MarkerManager'; function MarkerManager(gMap, opt_markers, opt_options) { this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.handleOptDraw = __bind(this.handleOptDraw, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.update = __bind(this.update, this); this.add = __bind(this.add, this); this.type = MarkerManager.type; this.gMap = gMap; this.gMarkers = new PropMap(); this.$log = Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { var exists, msg; if (optDraw == null) { optDraw = true; } if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; Logger.error(msg); throw msg; } exists = this.gMarkers.get(gMarker.key); if (!exists) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.put(gMarker.key, gMarker); } }; MarkerManager.prototype.update = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.remove(gMarker, optDraw); return this.add(gMarker, optDraw); }; MarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; MarkerManager.prototype.remove = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.handleOptDraw(gMarker, optDraw, false); if (this.gMarkers.get(gMarker.key)) { return this.gMarkers.remove(gMarker.key); } }; MarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(marker) { return _this.remove(marker); }; })(this)); }; MarkerManager.prototype.draw = function() { var deletes; deletes = []; this.gMarkers.each((function(_this) { return function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { gMarker.setMap(_this.gMap); return gMarker.isDrawn = true; } else { return deletes.push(gMarker); } } }; })(this)); return deletes.forEach((function(_this) { return function(gMarker) { gMarker.isDrawn = false; return _this.remove(gMarker, true); }; })(this)); }; MarkerManager.prototype.clear = function() { this.gMarkers.each(function(gMarker) { return gMarker.setMap(null); }); delete this.gMarkers; return this.gMarkers = new PropMap(); }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; MarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.gMap); }; MarkerManager.prototype.getGMarkers = function() { return this.gMarkers.values(); }; return MarkerManager; })(); return MarkerManager; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [ '$timeout', function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(listener) { return google.maps.event.removeListener(listener); }); return remove = null; }; }; return addEvents; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [ 'uiGmapadd-events', function(mapEvents) { return function(mapArray, scope, pathEval, pathChangedFn) { var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener; isSetFromScope = false; scopePath = scope.$eval(pathEval); if (!scope["static"]) { legacyHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath[index] = value; } else { scopePath[index].latitude = value.lat(); return scopePath[index].longitude = value.lng(); } }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath.splice(index, 0, value); } else { return scopePath.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); } }, remove_at: function(index) { if (isSetFromScope) { return; } return scopePath.splice(index, 1); } }; geojsonArray; if (scopePath.type === 'Polygon') { geojsonArray = scopePath.coordinates[0]; } else if (scopePath.type === 'LineString') { geojsonArray = scopePath.coordinates; } geojsonHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } geojsonArray[index][1] = value.lat(); return geojsonArray[index][0] = value.lng(); }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return geojsonArray.splice(index, 0, [value.lng(), value.lat()]); }, remove_at: function(index) { if (isSetFromScope) { return; } return geojsonArray.splice(index, 1); } }; mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers); } legacyWatcher = function(newPath) { var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { i = 0; oldLength = oldArray.getLength(); newLength = newPath.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newPath[i]; if (typeof newValue.equals === 'function') { if (!newValue.equals(oldValue)) { oldArray.setAt(i, newValue); changed = true; } } else { if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); changed = true; } } i++; } while (i < newLength) { newValue = newPath[i]; if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') { oldArray.push(newValue); } else { oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; geojsonWatcher = function(newPath) { var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { array; if (scopePath.type === 'Polygon') { array = newPath.coordinates[0]; } else if (scopePath.type === 'LineString') { array = newPath.coordinates; } i = 0; oldLength = oldArray.getLength(); newLength = array.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = array[i]; if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) { oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0])); changed = true; } i++; } while (i < newLength) { newValue = array[i]; oldArray.push(new google.maps.LatLng(newValue[1], newValue[0])); changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; watchListener; if (!scope["static"]) { if (angular.isUndefined(scopePath.type)) { watchListener = scope.$watchCollection(pathEval, legacyWatcher); } else { watchListener = scope.$watch(pathEval, geojsonWatcher, true); } } return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [ '$timeout', function($timeout) { return { maybeRepaint: function(el) { if (el) { el.style.opacity = 0.9; return $timeout(function() { return el.style.opacity = 1; }); } } }; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) { var CommonOptionsBuilder; return CommonOptionsBuilder = (function(_super) { __extends(CommonOptionsBuilder, _super); function CommonOptionsBuilder() { this.watchProps = __bind(this.watchProps, this); this.buildOpts = __bind(this.buildOpts, this); return CommonOptionsBuilder.__super__.constructor.apply(this, arguments); } CommonOptionsBuilder.prototype.props = [ 'clickable', 'draggable', 'editable', 'visible', { prop: 'stroke', isColl: true } ]; CommonOptionsBuilder.prototype.getCorrectModel = function(scope) { if (angular.isDefined(scope != null ? scope.model : void 0)) { return scope.model; } else { return scope; } }; CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var model, opts, stroke; if (customOpts == null) { customOpts = {}; } if (forEachOpts == null) { forEachOpts = {}; } if (!this.scope) { $log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts'); return; } if (!this.map) { $log.error('this.map not defined in CommonOptionsBuilder can not buildOpts'); return; } model = this.getCorrectModel(this.scope); stroke = this.scopeOrModelVal('stroke', this.scope, model); opts = angular.extend(customOpts, this.DEFAULTS, { map: this.map, strokeColor: stroke != null ? stroke.color : void 0, strokeOpacity: stroke != null ? stroke.opacity : void 0, strokeWeight: stroke != null ? stroke.weight : void 0 }); angular.forEach(angular.extend(forEachOpts, { clickable: true, draggable: false, editable: false, "static": false, fit: false, visible: true, zIndex: 0, icons: [] }), (function(_this) { return function(defaultValue, key) { var val; val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model); if (angular.isUndefined(val)) { return opts[key] = defaultValue; } else { return opts[key] = model[key]; } }; })(this)); if (opts["static"]) { opts.editable = false; } return opts; }; CommonOptionsBuilder.prototype.watchProps = function(props) { if (props == null) { props = this.props; } return props.forEach((function(_this) { return function(prop) { if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) { if (prop != null ? prop.isColl : void 0) { return _this.scope.$watchCollection(prop.prop, _this.setMyOptions); } else { return _this.scope.$watch(prop, _this.setMyOptions); } } }; })(this)); }; return CommonOptionsBuilder; })(ModelKey); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var PolylineOptionsBuilder; return PolylineOptionsBuilder = (function(_super) { __extends(PolylineOptionsBuilder, _super); function PolylineOptionsBuilder() { return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments); } PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolylineOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolylineOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapShapeOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var ShapeOptionsBuilder; return ShapeOptionsBuilder = (function(_super) { __extends(ShapeOptionsBuilder, _super); function ShapeOptionsBuilder() { return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments); } ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var fill, model; model = this.getCorrectModel(this.scope); fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model); customOpts = angular.extend(customOpts, { fillColor: fill != null ? fill.color : void 0, fillOpacity: fill != null ? fill.opacity : void 0 }); return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts); }; return ShapeOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapPolygonOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var PolygonOptionsBuilder; return PolygonOptionsBuilder = (function(_super) { __extends(PolygonOptionsBuilder, _super); function PolygonOptionsBuilder() { return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments); } PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolygonOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolygonOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapRectangleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var RectangleOptionsBuilder; return RectangleOptionsBuilder = (function(_super) { __extends(RectangleOptionsBuilder, _super); function RectangleOptionsBuilder() { return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments); } RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) { return RectangleOptionsBuilder.__super__.buildOpts.call(this, { bounds: bounds }, cachedEval); }; return RectangleOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapCircleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var CircleOptionsBuilder; return CircleOptionsBuilder = (function(_super) { __extends(CircleOptionsBuilder, _super); function CircleOptionsBuilder() { return CircleOptionsBuilder.__super__.constructor.apply(this, arguments); } CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) { return CircleOptionsBuilder.__super__.buildOpts.call(this, { center: center, radius: radius }, cachedEval); }; return CircleOptionsBuilder; })(ShapeOptionsBuilder); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [ 'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) { return _.extend(GmapUtil, { createOptions: function(coords, icon, defaults, map) { var opts; if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords), visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, isLabel: function(options) { if (options == null) { return false; } return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null); } }); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [ 'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) { return function(Builder, gFactory) { var BasePolyChildModel; return BasePolyChildModel = (function(_super) { __extends(BasePolyChildModel, _super); BasePolyChildModel.include(GmapUtil); function BasePolyChildModel(scope, attrs, map, defaults, model) { var create; this.scope = scope; this.attrs = attrs; this.map = map; this.defaults = defaults; this.model = model; this.clean = __bind(this.clean, this); this.clonedModel = _.clone(this.model, true); this.isDragging = false; this.internalEvents = { dragend: (function(_this) { return function() { return _.defer(function() { return _this.isDragging = false; }); }; })(this), dragstart: (function(_this) { return function() { return _this.isDragging = true; }; })(this) }; create = (function(_this) { return function() { var maybeCachedEval, pathPoints; if (_this.isDragging) { return; } pathPoints = _this.convertPathPoints(_this.scope.path); if (_this.gObject != null) { _this.clean(); } if (scope.model != null) { maybeCachedEval = scope; } if (pathPoints.length > 0) { _this.gObject = gFactory(_this.buildOpts(pathPoints, maybeCachedEval)); } if (_this.gObject) { if (_this.scope.fit) { _this.extendMapBounds(map, pathPoints); } arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) { if (_this.scope.fit) { return _this.extendMapBounds(map, pathPoints); } }); if (angular.isDefined(scope.events) && angular.isObject(scope.events)) { _this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope); } return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.model) : EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.scope); } }; })(this); create(); scope.$watch('path', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.gObject) { return create(); } }; })(this), true); if (!scope["static"] && angular.isDefined(scope.editable)) { scope.$watch('editable', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (_ref = _this.gObject) != null ? _ref.setEditable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(scope.draggable)) { scope.$watch('draggable', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (_ref = _this.gObject) != null ? _ref.setDraggable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(scope.visible)) { scope.$watch('visible', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); } return (_ref = _this.gObject) != null ? _ref.setVisible(newValue) : void 0; }; })(this), true); } if (angular.isDefined(scope.geodesic)) { scope.$watch('geodesic', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch('stroke.weight', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch('stroke.color', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch('stroke.opacity', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(scope.icons)) { scope.$watch('icons', (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } scope.$on('$destroy', (function(_this) { return function() { _this.clean(); return _this.scope = null; }; })(this)); if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.color)) { scope.$watch('fill.color', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.opacity)) { scope.$watch('fill.opacity', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(scope.zIndex)) { scope.$watch('zIndex', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } } BasePolyChildModel.prototype.clean = function() { var _ref; EventsHelper.removeEvents(this.listeners); EventsHelper.removeEvents(this.internalListeners); if ((_ref = this.gObject) != null) { _ref.setMap(null); } return this.gObject = null; }; return BasePolyChildModel; })(Builder); }; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , & http://jsfiddle.net/YsQdh/88/ */ (function() { angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [ 'uiGmapLogger', '$q', function($log, $q) { var drawFreeHand, freeHandMgr; drawFreeHand = function(map, polys, done) { var move, poly; poly = new google.maps.Polyline({ map: map, clickable: false }); move = google.maps.event.addListener(map, 'mousemove', function(e) { return poly.getPath().push(e.latLng); }); google.maps.event.addListenerOnce(map, 'mouseup', function(e) { var path; google.maps.event.removeListener(move); path = poly.getPath(); poly.setMap(null); polys.push(new google.maps.Polygon({ map: map, path: path })); poly = null; google.maps.event.clearListeners(map.getDiv(), 'mousedown'); return done(); }); return void 0; }; freeHandMgr = function(map, scope) { var disableMap, enableMap; this.map = map; disableMap = (function(_this) { return function() { var mapOptions; mapOptions = { draggable: false, disableDefaultUI: true, scrollwheel: false, disableDoubleClickZoom: false }; $log.info('disabling map move'); return _this.map.setOptions(mapOptions); }; })(this); enableMap = (function(_this) { return function() { var mapOptions, _ref; mapOptions = { draggable: true, disableDefaultUI: false, scrollwheel: true, disableDoubleClickZoom: true }; if ((_ref = _this.deferred) != null) { _ref.resolve(); } return _.defer(function() { return _this.map.setOptions(_.extend(mapOptions, scope.options)); }); }; })(this); this.engage = (function(_this) { return function(polys) { _this.polys = polys; _this.deferred = $q.defer(); disableMap(); $log.info('DrawFreeHandChildModel is engaged (drawing).'); google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) { return drawFreeHand(_this.map, _this.polys, enableMap); }); return _this.deferred.promise; }; })(this); return this; }; return freeHandMgr; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [ 'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) { var MarkerChildModel; MarkerChildModel = (function(_super) { var destroy; __extends(MarkerChildModel, _super); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); MarkerChildModel.include(MarkerOptions); destroy = function(child) { if ((child != null ? child.gObject : void 0) != null) { child.removeEvents(child.externalListeners); child.removeEvents(child.internalListeners); if (child != null ? child.gObject : void 0) { if (child.removeFromManager) { child.gManager.remove(child.gObject); } child.gObject.setMap(null); return child.gObject = null; } } }; function MarkerChildModel(scope, model, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) { var action; this.model = model; this.keys = keys; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gManager = gManager; this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true; this.trackModel = trackModel != null ? trackModel : true; this.needRedraw = needRedraw != null ? needRedraw : false; this.internalEvents = __bind(this.internalEvents, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.isNotValid = __bind(this.isNotValid, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); this.updateModel = __bind(this.updateModel, this); this.handleModelChanges = __bind(this.handleModelChanges, this); this.destroy = __bind(this.destroy, this); this.clonedModel = _.extend({}, this.model); this.deferred = uiGmapPromise.defer(); _.each(this.keys, (function(_this) { return function(v, k) { var keyValue; keyValue = _this.keys[k]; if ((keyValue != null) && !_.isFunction(keyValue) && _.isString(keyValue)) { return _this[k + 'Key'] = keyValue; } }; })(this)); this.idKey = this.idKeyKey || 'id'; if (this.model[this.idKey] != null) { this.id = this.model[this.idKey]; } MarkerChildModel.__super__.constructor.call(this, scope); this.scope.getGMarker = (function(_this) { return function() { return _this.gObject; }; })(this); this.firstTime = true; if (this.trackModel) { this.scope.model = this.model; this.scope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.handleModelChanges(newValue, oldValue); } }; })(this), true); } else { action = new PropertyAction((function(_this) { return function(calledKey, newVal) { if (!_this.firstTime) { return _this.setMyScope(calledKey, scope); } }; })(this), false); _.each(this.keys, function(v, k) { return scope.$watch(k, action.sic, true); }); } this.scope.$on('$destroy', (function(_this) { return function() { return destroy(_this); }; })(this)); this.createMarker(this.model); $log.info(this); } MarkerChildModel.prototype.destroy = function(removeFromManager) { if (removeFromManager == null) { removeFromManager = true; } this.removeFromManager = removeFromManager; return this.scope.$destroy(); }; MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) { var changes, ctr, len; changes = this.getChanges(newValue, oldValue, IMarker.keys); if (!this.firstTime) { ctr = 0; len = _.keys(changes).length; return _.each(changes, (function(_this) { return function(v, k) { var doDraw; ctr += 1; doDraw = len === ctr; _this.setMyScope(k, newValue, oldValue, false, true, doDraw); return _this.needRedraw = true; }; })(this)); } }; MarkerChildModel.prototype.updateModel = function(model) { this.clonedModel = _.extend({}, model); return this.setMyScope('all', model, this.model); }; MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) { var coords; if (doDraw == null) { doDraw = true; } coords = this.getProp('coords', this.scope, this.model); if (coords != null) { if (!this.validateCoords(coords)) { $log.debug('MarkerChild does not have coords yet. They may be defined later.'); return; } if (validCb != null) { validCb(); } if (doDraw && this.gObject) { return this.gManager.add(this.gObject); } } else { if (doDraw && this.gObject) { return this.gManager.remove(this.gObject); } } }; MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) { var justCreated; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (doDraw == null) { doDraw = true; } if (model == null) { model = this.model; } else { this.model = model; } if (!this.gObject) { this.setOptions(this.scope, doDraw); justCreated = true; } switch (thingThatChanged) { case 'all': return _.each(this.keys, (function(_this) { return function(v, k) { return _this.setMyScope(k, model, oldModel, isInit, doDraw); }; })(this)); case 'icon': return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw); case 'coords': return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw); case 'options': if (!justCreated) { return this.createMarker(model, oldModel, isInit, doDraw); } } }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (doDraw == null) { doDraw = true; } this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw); return this.firstTime = false; }; MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) { if (gSetter == null) { gSetter = void 0; } if (doDraw == null) { doDraw = true; } if (gSetter != null) { return gSetter(this.scope, doDraw); } }; if (MarkerChildModel.doDrawSelf && doDraw) { MarkerChildModel.gManager.draw(); } MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) { var hasIdenticalScopes, hasNoGmarker; if (doCheckGmarker == null) { doCheckGmarker = true; } hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0; hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false; return hasIdenticalScopes || hasNoGmarker; }; MarkerChildModel.prototype.setCoords = function(scope, doDraw) { if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope) || (this.gObject == null)) { return; } return this.renderGMarker(doDraw, (function(_this) { return function() { var newGValue, newModelVal, oldGValue; newModelVal = _this.getProp('coords', scope, _this.model); newGValue = _this.getCoords(newModelVal); oldGValue = _this.gObject.getPosition(); if ((oldGValue != null) && (newGValue != null)) { if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) { return; } } _this.gObject.setPosition(newGValue); return _this.gObject.setVisible(_this.validateCoords(newModelVal)); }; })(this)); }; MarkerChildModel.prototype.setIcon = function(scope, doDraw) { if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope) || (this.gObject == null)) { return; } return this.renderGMarker(doDraw, (function(_this) { return function() { var coords, newValue, oldValue; oldValue = _this.gObject.getIcon(); newValue = _this.getProp('icon', scope, _this.model); if (oldValue === newValue) { return; } _this.gObject.setIcon(newValue); coords = _this.getProp('coords', scope, _this.model); _this.gObject.setPosition(_this.getCoords(coords)); return _this.gObject.setVisible(_this.validateCoords(coords)); }; })(this)); }; MarkerChildModel.prototype.setOptions = function(scope, doDraw) { var _ref; if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope, false)) { return; } this.renderGMarker(doDraw, (function(_this) { return function() { var coords, icon, _options; coords = _this.getProp('coords', scope, _this.model); icon = _this.getProp('icon', scope, _this.model); _options = _this.getProp('options', scope, _this.model); _this.opts = _this.createOptions(coords, icon, _options); if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) { _this.gManager.remove(_this.gObject); _this.gObject = void 0; } if (_this.gObject != null) { _this.gObject.setOptions(_this.setLabelOptions(_this.opts)); } if (!_this.gObject) { if (_this.isLabel(_this.opts)) { _this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts)); } else { _this.gObject = new google.maps.Marker(_this.opts); } _.extend(_this.gObject, { model: _this.model }); } if (_this.externalListeners) { _this.removeEvents(_this.externalListeners); } if (_this.internalListeners) { _this.removeEvents(_this.internalListeners); } _this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']); _this.internalListeners = _this.setEvents(_this.gObject, { events: _this.internalEvents(), $evalAsync: function() {} }, _this.model); if (_this.id != null) { return _this.gObject.key = _this.id; } }; })(this)); if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) { this.deferred.resolve(this.gObject); } else { if (!this.gObject) { return this.deferred.reject('gObject is null'); } if (!(((_ref = this.gObject) != null ? _ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) { $log.debug('gObject has no map yet'); this.deferred.resolve(this.gObject); } } if (this.model[this.fitKey]) { return this.gManager.fit(); } }; MarkerChildModel.prototype.setLabelOptions = function(opts) { opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor); return opts; }; MarkerChildModel.prototype.internalEvents = function() { return { dragend: (function(_this) { return function(marker, eventName, model, mousearg) { var events, modelToSet, newCoords; modelToSet = _this.trackModel ? _this.scope.model : _this.model; newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition()); modelToSet = _this.setVal(model, _this.coordsKey, newCoords); events = _this.scope.events; if ((events != null ? events.dragend : void 0) != null) { events.dragend(marker, eventName, modelToSet, mousearg); } return _this.scope.$apply(); }; })(this), click: (function(_this) { return function(marker, eventName, model, mousearg) { var click; click = _this.getProp('click', _this.scope, _this.model); if (_this.doClick && (click != null)) { return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg)); } }; })(this) }; }; return MarkerChildModel; })(ModelKey); return MarkerChildModel; } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) { var PolygonChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polygon(opts); }; base = new BaseGen(Builder, gFactory); return PolygonChildModel = (function(_super) { __extends(PolygonChildModel, _super); function PolygonChildModel() { return PolygonChildModel.__super__.constructor.apply(this, arguments); } return PolygonChildModel; })(base); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) { var PolylineChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polyline(opts); }; base = BaseGen(Builder, gFactory); return PolylineChildModel = (function(_super) { __extends(PolylineChildModel, _super); function PolylineChildModel() { return PolylineChildModel.__super__.constructor.apply(this, arguments); } return PolylineChildModel; })(base); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) { var WindowChildModel; WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(GmapUtil); WindowChildModel.include(EventsHelper); function WindowChildModel(model, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) { var maybeMarker; this.model = model; this.scope = scope; this.opts = opts; this.isIconVisibleOnClick = isIconVisibleOnClick; this.mapCtrl = mapCtrl; this.markerScope = markerScope; this.element = element; this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false; this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true; this.updateModel = __bind(this.updateModel, this); this.destroy = __bind(this.destroy, this); this.remove = __bind(this.remove, this); this.getLatestPosition = __bind(this.getLatestPosition, this); this.hideWindow = __bind(this.hideWindow, this); this.showWindow = __bind(this.showWindow, this); this.handleClick = __bind(this.handleClick, this); this.watchOptions = __bind(this.watchOptions, this); this.watchCoords = __bind(this.watchCoords, this); this.createGWin = __bind(this.createGWin, this); this.watchElement = __bind(this.watchElement, this); this.watchAndDoShow = __bind(this.watchAndDoShow, this); this.doShow = __bind(this.doShow, this); this.clonedModel = _.clone(this.model, true); this.getGmarker = function() { var _ref, _ref1; if (((_ref = this.markerScope) != null ? _ref['getGMarker'] : void 0) != null) { return (_ref1 = this.markerScope) != null ? _ref1.getGMarker() : void 0; } }; this.listeners = []; this.createGWin(); maybeMarker = this.getGmarker(); if (maybeMarker != null) { maybeMarker.setClickable(true); } this.watchElement(); this.watchOptions(); this.watchCoords(); this.watchAndDoShow(); this.scope.$on('$destroy', (function(_this) { return function() { return _this.destroy(); }; })(this)); $log.info(this); } WindowChildModel.prototype.doShow = function(wasOpen) { if (this.scope.show === true || wasOpen) { return this.showWindow(); } else { return this.hideWindow(); } }; WindowChildModel.prototype.watchAndDoShow = function() { if (this.model.show != null) { this.scope.show = this.model.show; } this.scope.$watch('show', this.doShow, true); return this.doShow(); }; WindowChildModel.prototype.watchElement = function() { return this.scope.$watch((function(_this) { return function() { var wasOpen, _ref; if (!(_this.element || _this.html)) { return; } if (_this.html !== _this.element.html() && _this.gObject) { if ((_ref = _this.opts) != null) { _ref.content = void 0; } wasOpen = _this.gObject.isOpen(); _this.remove(); return _this.createGWin(wasOpen); } }; })(this)); }; WindowChildModel.prototype.createGWin = function(isOpen) { var defaults, maybeMarker, _opts, _ref, _ref1; if (isOpen == null) { isOpen = false; } maybeMarker = this.getGmarker(); defaults = {}; if (this.opts != null) { if (this.scope.coords) { this.opts.position = this.getCoords(this.scope.coords); } defaults = this.opts; } if (this.element) { this.html = _.isObject(this.element) ? this.element.html() : this.element; } _opts = this.scope.options ? this.scope.options : defaults; this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts); if (this.opts != null) { if (!this.gObject) { if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) { this.gObject = new window.InfoBox(this.opts); } else { this.gObject = new google.maps.InfoWindow(this.opts); } this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() { return ChromeFixes.maybeRepaint(this.content); })); this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) { return function() { if (maybeMarker) { maybeMarker.setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { maybeMarker.setVisible(false); return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _this.gObject.close(); _this.model.show = false; if (_this.scope.closeClick != null) { return _this.scope.$evalAsync(_this.scope.closeClick()); } else { return _this.scope.$evalAsync(); } }; })(this))); } this.gObject.setContent(this.opts.content); this.handleClick(((_ref = this.scope) != null ? (_ref1 = _ref.options) != null ? _ref1.forceClick : void 0 : void 0) || isOpen); return this.doShow(this.gObject.isOpen()); } }; WindowChildModel.prototype.watchCoords = function() { var scope; scope = this.markerScope != null ? this.markerScope : this.scope; return scope.$watch('coords', (function(_this) { return function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { _this.hideWindow(); } else if (!_this.validateCoords(newValue)) { $log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.doShow(); _this.gObject.setPosition(pos); if (_this.opts) { return _this.opts.position = pos; } } }; })(this), true); }; WindowChildModel.prototype.watchOptions = function() { return this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.opts = newValue; if (_this.gObject != null) { _this.gObject.setOptions(_this.opts); if ((_this.opts.visible != null) && _this.opts.visible) { return _this.showWindow(); } else if (_this.opts.visible != null) { return _this.hideWindow(); } } } }; })(this), true); }; WindowChildModel.prototype.handleClick = function(forceClick) { var click, maybeMarker; if (this.gObject == null) { return; } maybeMarker = this.getGmarker(); click = (function(_this) { return function() { if (_this.gObject == null) { _this.createGWin(); } _this.showWindow(); if (maybeMarker != null) { _this.initialMarkerVisibility = maybeMarker.getVisible(); _this.oldMarkerAnimation = maybeMarker.getAnimation(); return maybeMarker.setVisible(_this.isIconVisibleOnClick); } }; })(this); if (forceClick) { click(); } if (maybeMarker) { return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, { events: { click: click } }, this.model)); } }; WindowChildModel.prototype.showWindow = function() { var compiled, show, templateScope; if (this.gObject != null) { show = (function(_this) { return function() { var isOpen, maybeMarker, pos; if (!_this.gObject.isOpen()) { maybeMarker = _this.getGmarker(); if ((_this.gObject != null) && (_this.gObject.getPosition != null)) { pos = _this.gObject.getPosition(); } if (maybeMarker) { pos = maybeMarker.getPosition(); } if (!pos) { return; } _this.gObject.open(_this.mapCtrl, maybeMarker); isOpen = _this.gObject.isOpen(); if (_this.model.show !== isOpen) { return _this.model.show = isOpen; } } }; })(this); if (this.scope.templateUrl) { return $http.get(this.scope.templateUrl, { cache: $templateCache }).then((function(_this) { return function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = $compile(content.data)(templateScope); _this.gObject.setContent(compiled[0]); return show(); }; })(this)); } else if (this.scope.template) { templateScope = this.scope.$new(); if (angular.isDefined(this.scope.templateParameter)) { templateScope.parameter = this.scope.templateParameter; } compiled = $compile(this.scope.template)(templateScope); this.gObject.setContent(compiled[0]); return show(); } else { return show(); } } }; WindowChildModel.prototype.hideWindow = function() { if ((this.gObject != null) && this.gObject.isOpen()) { return this.gObject.close(); } }; WindowChildModel.prototype.getLatestPosition = function(overridePos) { var maybeMarker; maybeMarker = this.getGmarker(); if ((this.gObject != null) && (maybeMarker != null) && !overridePos) { return this.gObject.setPosition(maybeMarker.getPosition()); } else { if (overridePos) { return this.gObject.setPosition(overridePos); } } }; WindowChildModel.prototype.remove = function() { this.hideWindow(); this.removeEvents(this.listeners); this.listeners.length = 0; delete this.gObject; return delete this.opts; }; WindowChildModel.prototype.destroy = function(manualOverride) { var _ref; if (manualOverride == null) { manualOverride = false; } this.remove(); if ((this.scope != null) && !((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { return this.scope.$destroy(); } }; WindowChildModel.prototype.updateModel = function(model) { this.clonedModel = _.extend({}, model); return _.extend(this.model, this.clonedModel); }; return WindowChildModel; })(BaseObject); return WindowChildModel; } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) { var CircleParentModel; return CircleParentModel = (function(_super) { __extends(CircleParentModel, _super); CircleParentModel.include(GmapUtil); CircleParentModel.include(EventsHelper); function CircleParentModel(scope, element, attrs, map, DEFAULTS) { var clean, gObject, lastRadius; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; lastRadius = null; clean = (function(_this) { return function() { lastRadius = null; if (_this.listeners != null) { _this.removeEvents(_this.listeners); return _this.listeners = void 0; } }; })(this); gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); } }; })(this); this.props = this.props.concat([ { prop: 'center', isColl: true }, { prop: 'fill', isColl: true }, 'radius' ]); this.watchProps(); if (this.scope.control != null) { this.scope.control.getCircle = function() { return gObject; }; } clean(); this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']); if (this.listeners != null) { this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() { /* possible google bug, and or because a circle has two radii radius_changed appears to fire twice (original and new) which is not too helpful therefore we will check for radius changes manually and bail out if nothing has changed */ var newRadius, work; newRadius = gObject.getRadius(); if (newRadius === lastRadius) { return; } lastRadius = newRadius; work = function() { var _ref, _ref1; if (newRadius !== scope.radius) { scope.radius = newRadius; } if (((_ref = scope.events) != null ? _ref.radius_changed : void 0) && _.isFunction((_ref1 = scope.events) != null ? _ref1.radius_changed : void 0)) { return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments); } }; if (!angular.mock) { return scope.$evalAsync(function() { return work(); }); } else { return work(); } })); } if (this.listeners != null) { this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() { return scope.$evalAsync(function() { if (angular.isDefined(scope.center.type)) { scope.center.coordinates[1] = gObject.getCenter().lat(); return scope.center.coordinates[0] = gObject.getCenter().lng(); } else { scope.center.latitude = gObject.getCenter().lat(); return scope.center.longitude = gObject.getCenter().lng(); } }); })); } scope.$on('$destroy', (function(_this) { return function() { clean(); return gObject.setMap(null); }; })(this)); $log.info(this); } return CircleParentModel; })(Builder); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) { var DrawingManagerParentModel; return DrawingManagerParentModel = (function(_super) { __extends(DrawingManagerParentModel, _super); DrawingManagerParentModel.include(EventsHelper); function DrawingManagerParentModel(scope, element, attrs, map) { var gObject, listeners; this.scope = scope; this.attrs = attrs; this.map = map; gObject = new google.maps.drawing.DrawingManager(this.scope.options); gObject.setMap(this.map); listeners = void 0; if (this.scope.control != null) { this.scope.control.getDrawingManager = function() { return gObject; }; } if (!this.scope["static"] && this.scope.options) { this.scope.$watch('options', function(newValue) { return gObject != null ? gObject.setOptions(newValue) : void 0; }, true); } if (this.scope.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } scope.$on('$destroy', (function(_this) { return function() { if (listeners != null) { _this.removeEvents(listeners); } gObject.setMap(null); return gObject = null; }; })(this)); } return DrawingManagerParentModel; })(BaseObject); } ]); }).call(this); ; /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [ "uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope, element, attrs, map) { this.scope = scope; this.element = element; this.attrs = attrs; this.map = map; this.onWatch = __bind(this.onWatch, this); this.watch = __bind(this.watch, this); this.validateScope = __bind(this.validateScope, this); IMarkerParentModel.__super__.constructor.call(this, this.scope); this.$log = Logger; if (!this.validateScope(scope)) { throw new String("Unable to construct IMarkerParentModel due to invalid scope"); } this.doClick = angular.isDefined(attrs.click); if (scope.options != null) { this.DEFAULTS = scope.options; } this.watch('coords', this.scope); this.watch('icon', this.scope); this.watch('options', this.scope); scope.$on("$destroy", (function(_this) { return function() { return _this.onDestroy(scope); }; })(this)); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) { if (equalityCheck == null) { equalityCheck = true; } return scope.$watch(propNameToWatch, (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }; })(this), equalityCheck); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {}; return IMarkerParentModel; })(ModelKey); return IMarkerParentModel; } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [ "uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; return IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(GmapUtil); function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { IWindowParentModel.__super__.constructor.call(this, scope); this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.DEFAULTS = {}; if (scope.options != null) { this.DEFAULTS = scope.options; } } IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return IWindowParentModel; })(ModelKey); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = __bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!'); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.gObject.setMap(this.gMap); } this.scope.$watch('show', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.gObject.setMap(_this.gMap); } else { return _this.gObject.setMap(null); } } }; })(this), true); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.gObject.setMap(null); _this.gObject = null; return _this.createGoogleLayer(); } }; })(this), true); this.scope.$on('$destroy', (function(_this) { return function() { return _this.gObject.setMap(null); }; })(this)); } LayerParentModel.prototype.createGoogleLayer = function() { var _base; if (this.attrs.options == null) { this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options); } if ((this.gObject != null) && (this.onLayerCreated != null)) { return typeof (_base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? _base(this.gObject) : void 0; } }; return LayerParentModel; })(BaseObject); return LayerParentModel; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) { var MapTypeParentModel; MapTypeParentModel = (function(_super) { __extends(MapTypeParentModel, _super); function MapTypeParentModel(scope, element, attrs, gMap, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.$log = $log != null ? $log : Logger; this.hideOverlay = __bind(this.hideOverlay, this); this.showOverlay = __bind(this.showOverlay, this); this.refreshMapType = __bind(this.refreshMapType, this); this.createMapType = __bind(this.createMapType, this); if (this.attrs.options == null) { this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!'); return; } this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0; this.doShow = true; this.createMapType(); if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.showOverlay(); } this.scope.$watch('show', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.showOverlay(); } else { return _this.hideOverlay(); } } }; })(this), true); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); if (angular.isDefined(this.attrs.refresh)) { this.scope.$watch('refresh', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); } this.scope.$on('$destroy', (function(_this) { return function() { _this.hideOverlay(); return _this.mapType = null; }; })(this)); } MapTypeParentModel.prototype.createMapType = function() { if (this.scope.options.getTile != null) { this.mapType = this.scope.options; } else if (this.scope.options.getTileUrl != null) { this.mapType = new google.maps.ImageMapType(this.scope.options); } else { this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!'); return; } if (this.attrs.id && this.scope.id) { this.gMap.mapTypes.set(this.scope.id, this.mapType); if (!angular.isDefined(this.attrs.show)) { this.doShow = false; } } return this.mapType.layerId = this.id; }; MapTypeParentModel.prototype.refreshMapType = function() { this.hideOverlay(); this.mapType = null; this.createMapType(); if (this.doShow && (this.gMap != null)) { return this.showOverlay(); } }; MapTypeParentModel.prototype.showOverlay = function() { return this.gMap.overlayMapTypes.push(this.mapType); }; MapTypeParentModel.prototype.hideOverlay = function() { var found; found = false; return this.gMap.overlayMapTypes.forEach((function(_this) { return function(mapType, index) { if (!found && mapType.layerId === _this.id) { found = true; _this.gMap.overlayMapTypes.removeAt(index); } }; })(this)); }; return MapTypeParentModel; })(BaseObject); return MapTypeParentModel; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [ "uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log) { var MarkersParentModel, _setPlurals; _setPlurals = function(val, objToSet) { objToSet.plurals = new PropMap(); objToSet.scope.plurals = objToSet.plurals; return objToSet; }; MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(GmapUtil); MarkersParentModel.include(ModelsWatcher); function MarkersParentModel(scope, element, attrs, map) { this.onDestroy = __bind(this.onDestroy, this); this.newChildMarker = __bind(this.newChildMarker, this); this.pieceMeal = __bind(this.pieceMeal, this); this.rebuildAll = __bind(this.rebuildAll, this); this.createAllNew = __bind(this.createAllNew, this); this.createChildScopes = __bind(this.createChildScopes, this); this.validateScope = __bind(this.validateScope, this); this.onWatch = __bind(this.onWatch, this); var self; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map); this["interface"] = IMarker; self = this; _setPlurals(new PropMap(), this); this.scope.pluralsUpdate = { updateCtr: 0 }; this.$log.info(this); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; this.setIdKey(scope); this.scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); if (!this.modelsLength()) { this.modelsRendered = false; } this.scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) { if (newValue.length === 0 && oldValue.length === 0) { return; } _this.modelsRendered = true; return _this.onWatch('models', scope, newValue, oldValue); } }; })(this), !this.isTrue(attrs.modelsbyref)); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('clusterEvents', scope); this.watch('fit', scope); this.watch('idKey', scope); this.gManager = void 0; this.createAllNew(scope); } MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === "idKey" && newValue !== oldValue) { this.idKey = newValue; } if (this.doRebuildAll || propNameToWatch === 'doCluster') { return this.rebuildAll(scope); } else { return this.pieceMeal(scope); } }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; /* Not used internally by this parent created for consistency for external control in the API */ MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if ((this.gMap == null) || (this.scope.models == null)) { return; } if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; MarkersParentModel.prototype.createAllNew = function(scope) { var maybeCanceled, self, _ref, _ref1, _ref2; if (this.gManager != null) { this.gManager.clear(); delete this.gManager; } if (scope.doCluster) { if (scope.clusterEvents) { self = this; if (!this.origClusterEvents) { this.origClusterEvents = { click: (_ref = scope.clusterEvents) != null ? _ref.click : void 0, mouseout: (_ref1 = scope.clusterEvents) != null ? _ref1.mouseout : void 0, mouseover: (_ref2 = scope.clusterEvents) != null ? _ref2.mouseover : void 0 }; } else { angular.extend(scope.clusterEvents, this.origClusterEvents); } angular.extend(scope.clusterEvents, { click: function(cluster) { return self.maybeExecMappedEvent(cluster, 'click'); }, mouseout: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseout'); }, mouseover: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseover'); } }); } this.gManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, scope.clusterEvents); } else { this.gManager = new MarkerManager(this.map); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { _this.newChildMarker(model, scope); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { _this.modelsRendered = true; if (scope.fit) { _this.gManager.fit(); } _this.gManager.draw(); return _this.scope.pluralsUpdate.updateCtr += 1; }, _async.chunkSizeFrom(scope.chunk)); }; })(this)); }; MarkersParentModel.prototype.rebuildAll = function(scope) { var _ref; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } if ((_ref = this.scope.plurals) != null ? _ref.length : void 0) { return this.onDestroy(scope).then((function(_this) { return function() { return _this.createAllNew(scope); }; })(this)); } else { return this.createAllNew(scope); } }; MarkersParentModel.prototype.pieceMeal = function(scope) { var maybeCanceled, payload; if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; if (this.modelsLength() && this.scope.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } _this.scope.plurals.remove(child.id); return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { _this.newChildMarker(modelToAdd, scope); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) { scope.plurals = _this.scope.plurals; if (scope.fit) { _this.gManager.fit(); } _this.gManager.draw(); } return _this.scope.pluralsUpdate.updateCtr += 1; }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(scope); } }; MarkersParentModel.prototype.newChildMarker = function(model, scope) { var child, childScope, doDrawSelf, keys; if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.$log.info('child', child, 'markers', this.scope.markerModels); childScope = scope.$new(false); childScope.events = scope.events; keys = {}; IMarker.scopeKeys.forEach(function(k) { return keys[k] = scope[k]; }); child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false); this.scope.plurals.put(model[this.idKey], child); return child; }; MarkersParentModel.prototype.onDestroy = function(scope) { MarkersParentModel.__super__.onDestroy.call(this, scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.scope.plurals.values(), function(model) { if (model != null) { return model.destroy(false); } }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { if (_this.gManager != null) { _this.gManager.clear(); } _this.plurals.removeAll(); if (_this.plurals !== _this.scope.plurals) { console.error('plurals out of sync for MarkersParentModel'); } return _this.scope.pluralsUpdate.updateCtr += 1; }); }; })(this)); }; MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) { var pair, _ref; if (_.isFunction((_ref = this.scope.clusterEvents) != null ? _ref[fnName] : void 0)) { pair = this.mapClusterToPlurals(cluster); if (this.origClusterEvents[fnName]) { return this.origClusterEvents[fnName](pair.cluster, pair.mapped); } } }; MarkersParentModel.prototype.mapClusterToPlurals = function(cluster) { var mapped; mapped = cluster.getMarkers().map((function(_this) { return function(g) { return _this.scope.plurals.get(g.key).model; }; })(this)); return { cluster: cluster, mapped: mapped }; }; MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return MarkersParentModel; })(IMarkerParentModel); return MarkersParentModel; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapPolygonsParentModel', [ '$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapPolygonChildModel', 'uiGmap_async', 'uiGmapPromise', 'uiGmapIPolygon', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, PolygonChildModel, _async, uiGmapPromise, IPolygon) { var PolygonsParentModel; return PolygonsParentModel = (function(_super) { __extends(PolygonsParentModel, _super); PolygonsParentModel.include(ModelsWatcher); function PolygonsParentModel(scope, element, attrs, gMap, defaults) { var self; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.defaults = defaults; this.createChild = __bind(this.createChild, this); this.pieceMeal = __bind(this.pieceMeal, this); this.createAllNew = __bind(this.createAllNew, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopes = __bind(this.createChildScopes, this); this.watchDestroy = __bind(this.watchDestroy, this); this.onDestroy = __bind(this.onDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); PolygonsParentModel.__super__.constructor.call(this, scope); this["interface"] = IPolygon; self = this; this.$log = $log; this.plurals = new PropMap(); _.each(IPolygon.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.createChildScopes(); } PolygonsParentModel.prototype.watchModels = function(scope) { return scope.$watchCollection('models', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }; })(this)); }; PolygonsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; PolygonsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; PolygonsParentModel.prototype.onDestroy = function(scope) { PolygonsParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(true); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var _ref; return (_ref = _this.plurals) != null ? _ref.removeAll() : void 0; }); }; })(this)); }; PolygonsParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; PolygonsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error('No models to create Polygons from! I Need direct models!'); return; } if ((this.gMap == null) || (this.scope.models == null)) { return; } this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; PolygonsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; PolygonsParentModel.prototype.createAllNew = function(scope, isArray) { var maybeCanceled; if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { var child; child = _this.createChild(model, _this.gMap); if (maybeCanceled) { $log.debug('createNew should fall through safely'); child.isEnabled = false; } return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.firstTime = false; }); }; })(this)); }; PolygonsParentModel.prototype.pieceMeal = function(scope, isArray) { var maybeCanceled, payload; if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; this.models = scope.models; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise(function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); }).then(function(state) { payload = state; if (payload.updates.length) { $log.warning("polygons updates: " + payload.updates.length + " will be missed"); } return _async.each(payload.removals, function(child) { if (child != null) { child.destroy(); _this.plurals.remove(child.model[_this.idKey]); return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { if (maybeCanceled) { $log.debug('pieceMeal should fall through safely'); } _this.createChild(modelToAdd, _this.gMap); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(this.scope, true, true); } }; PolygonsParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(IPolygon.scopeKeys, childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); childScope["static"] = this.scope["static"]; child = new PolygonChildModel(childScope, this.attrs, gMap, this.defaults, model); if (model[this.idKey] == null) { this.$log.error("Polygon model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; return PolygonsParentModel; })(ModelKey); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapPolylinesParentModel', [ '$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapPolylineChildModel', 'uiGmap_async', 'uiGmapPromise', 'uiGmapIPolyline', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, PolylineChildModel, _async, uiGmapPromise, IPolyline) { var PolylinesParentModel; return PolylinesParentModel = (function(_super) { __extends(PolylinesParentModel, _super); PolylinesParentModel.include(ModelsWatcher); function PolylinesParentModel(scope, element, attrs, gMap, defaults) { var self; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.defaults = defaults; this.setChildScope = __bind(this.setChildScope, this); this.createChild = __bind(this.createChild, this); this.pieceMeal = __bind(this.pieceMeal, this); this.createAllNew = __bind(this.createAllNew, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopes = __bind(this.createChildScopes, this); this.watchOurScope = __bind(this.watchOurScope, this); this.watchDestroy = __bind(this.watchDestroy, this); this.onDestroy = __bind(this.onDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); PolylinesParentModel.__super__.constructor.call(this, scope); this["interface"] = IPolyline; self = this; this.$log = $log; this.plurals = new PropMap(); _.each(IPolyline.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.watchOurScope(scope); this.createChildScopes(); } PolylinesParentModel.prototype.watch = function(scope, name, nameKey) { return scope.$watch(name, (function(_this) { return function(newValue, oldValue) { var maybeCanceled; if (newValue !== oldValue) { maybeCanceled = null; _this[nameKey] = _.isFunction(newValue) ? newValue() : newValue; return _async.promiseLock(_this, uiGmapPromise.promiseTypes.update, "watch " + name + " " + nameKey, (function(canceledMsg) { return maybeCanceled = canceledMsg; }), function() { return _async.each(_this.plurals.values(), function(model) { model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; return maybeCanceled; }, false); }); } }; })(this)); }; PolylinesParentModel.prototype.watchModels = function(scope) { return scope.$watchCollection('models', (function(_this) { return function(newValue, oldValue) { if (!(_.isEqual(newValue, oldValue) && (_this.lastNewValue !== newValue || _this.lastOldValue !== oldValue))) { _this.lastNewValue = newValue; _this.lastOldValue = oldValue; if (_this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }; })(this)); }; PolylinesParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; PolylinesParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; PolylinesParentModel.prototype.onDestroy = function(scope) { PolylinesParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(true); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var _ref; return (_ref = _this.plurals) != null ? _ref.removeAll() : void 0; }); }; })(this)); }; PolylinesParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; PolylinesParentModel.prototype.watchOurScope = function(scope) { return _.each(IPolyline.scopeKeys, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; return _this.watch(scope, name, nameKey); }; })(this)); }; PolylinesParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error('No models to create Polylines from! I Need direct models!'); return; } if (this.gMap != null) { if (this.scope.models != null) { this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } } } }; PolylinesParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; PolylinesParentModel.prototype.createAllNew = function(scope, isArray) { var maybeCanceled; if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { _this.createChild(model, _this.gMap); if (maybeCanceled) { $log.debug('createNew should fall through safely'); } return maybeCanceled; }).then(function() { return _this.firstTime = false; }); }; })(this)); }; PolylinesParentModel.prototype.pieceMeal = function(scope, isArray) { var maybeCanceled, payload; if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; this.models = scope.models; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise(function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); }).then(function(state) { payload = state; return _async.each(payload.removals, function(id) { var child; child = _this.plurals.get(id); if (child != null) { child.destroy(); _this.plurals.remove(id); return maybeCanceled; } }); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { if (maybeCanceled) { $log.debug('pieceMeal should fall through safely'); } _this.createChild(modelToAdd, _this.gMap); return maybeCanceled; }); }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(this.scope, true, true); } }; PolylinesParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); childScope["static"] = this.scope["static"]; child = new PolylineChildModel(childScope, this.attrs, gMap, this.defaults, model); if (model[this.idKey] == null) { this.$log.error("Polyline model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; PolylinesParentModel.prototype.setChildScope = function(childScope, model) { IPolyline.scopeKeys.forEach((function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; return PolylinesParentModel; })(ModelKey); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) { var RectangleParentModel; return RectangleParentModel = (function(_super) { __extends(RectangleParentModel, _super); RectangleParentModel.include(GmapUtil); RectangleParentModel.include(EventsHelper); function RectangleParentModel(scope, element, attrs, map, DEFAULTS) { var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; bounds = void 0; dragging = false; myListeners = []; listeners = void 0; fit = (function(_this) { return function() { if (_this.isTrue(attrs.fit)) { return _this.fitMapBounds(_this.map, bounds); } }; })(this); createBounds = (function(_this) { return function() { var _ref, _ref1; if ((scope.bounds != null) && (((_ref = scope.bounds) != null ? _ref.sw : void 0) != null) && (((_ref1 = scope.bounds) != null ? _ref1.ne : void 0) != null) && _this.validateBoundPoints(scope.bounds)) { bounds = _this.convertBoundPoints(scope.bounds); return $log.info("new new bounds created: " + (JSON.stringify(bounds))); } else if ((scope.bounds.getNorthEast != null) && (scope.bounds.getSouthWest != null)) { return bounds = scope.bounds; } else { if (scope.bounds != null) { return $log.error("Invalid bounds for newValue: " + (JSON.stringify(scope != null ? scope.bounds : void 0))); } } }; })(this); createBounds(); gObject = new google.maps.Rectangle(this.buildOpts(bounds)); $log.info("gObject (rectangle) created: " + gObject); settingBoundsFromScope = false; updateBounds = (function(_this) { return function() { var b, ne, sw; b = gObject.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return scope.$evalAsync(function(s) { if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) { return s.bounds = b; } }); }; })(this); init = (function(_this) { return function() { fit(); _this.removeEvents(myListeners); myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() { return dragging = true; })); myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() { dragging = false; return updateBounds(); })); return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() { if (dragging) { return; } return updateBounds(); })); }; })(this); clear = (function(_this) { return function() { _this.removeEvents(myListeners); if (listeners != null) { _this.removeEvents(listeners); } return gObject.setMap(null); }; })(this); if (bounds != null) { init(); } scope.$watch('bounds', (function(newValue, oldValue) { var isNew; if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) { return; } settingBoundsFromScope = true; if (newValue == null) { clear(); return; } if (bounds == null) { isNew = true; } else { fit(); } createBounds(); gObject.setBounds(bounds); settingBoundsFromScope = false; if (isNew && (bounds != null)) { return init(); } }), true); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { if ((bounds != null) && (newVals != null)) { return gObject.setOptions(_this.buildOpts(bounds)); } } }; })(this); this.props.push('bounds'); this.watchProps(this.props); if (attrs.events != null) { listeners = this.setEvents(gObject, scope, scope); scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, scope, scope); } }; })(this)); } scope.$on('$destroy', (function(_this) { return function() { return clear(); }; })(this)); $log.info(this); } return RectangleParentModel; })(Builder); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) { var SearchBoxParentModel; SearchBoxParentModel = (function(_super) { __extends(SearchBoxParentModel, _super); SearchBoxParentModel.include(EventsHelper); function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) { var controlDiv; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.ctrlPosition = ctrlPosition; this.template = template; this.$log = $log != null ? $log : Logger; this.setVisibility = __bind(this.setVisibility, this); this.getBounds = __bind(this.getBounds, this); this.setBounds = __bind(this.setBounds, this); this.createSearchBox = __bind(this.createSearchBox, this); this.addToParentDiv = __bind(this.addToParentDiv, this); this.addAsMapControl = __bind(this.addAsMapControl, this); this.init = __bind(this.init, this); if (this.attrs.template == null) { this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!'); return; } if (angular.isUndefined(this.scope.options)) { this.scope.options = {}; this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.visible)) { this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.autocomplete)) { this.scope.options.autocomplete = false; } this.visible = scope.options.visible; this.autocomplete = scope.options.autocomplete; controlDiv = angular.element('<div></div>'); controlDiv.append(this.template); this.input = controlDiv.find('input')[0]; this.init(); } SearchBoxParentModel.prototype.init = function() { this.createSearchBox(); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (angular.isObject(newValue)) { if (newValue.bounds != null) { _this.setBounds(newValue.bounds); } if (newValue.visible != null) { if (_this.visible !== newValue.visible) { return _this.setVisibility(newValue.visible); } } } }; })(this), true); if (this.attrs.parentdiv != null) { this.addToParentDiv(); } else { this.addAsMapControl(); } if (this.autocomplete) { this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) { return function() { return _this.places = _this.gObject.getPlace(); }; })(this)); } else { this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) { return function() { return _this.places = _this.gObject.getPlaces(); }; })(this)); } this.listeners = this.setEvents(this.gObject, this.scope, this.scope); this.$log.info(this); return this.scope.$on('$destroy', (function(_this) { return function() { return _this.gObject = null; }; })(this)); }; SearchBoxParentModel.prototype.addAsMapControl = function() { return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); }; SearchBoxParentModel.prototype.addToParentDiv = function() { this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv)); return this.parentDiv.append(this.input); }; SearchBoxParentModel.prototype.createSearchBox = function() { if (this.autocomplete) { return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options); } else { return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options); } }; SearchBoxParentModel.prototype.setBounds = function(bounds) { if (angular.isUndefined(bounds.isEmpty)) { this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.'); } else { if (bounds.isEmpty() === false) { if (this.gObject != null) { return this.gObject.setBounds(bounds); } } } }; SearchBoxParentModel.prototype.getBounds = function() { return this.gObject.getBounds(); }; SearchBoxParentModel.prototype.setVisibility = function(val) { if (this.attrs.parentdiv != null) { if (val === false) { this.parentDiv.addClass("ng-hide"); } else { this.parentDiv.removeClass("ng-hide"); } } else { if (val === false) { this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear(); } else { this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); } } return this.visible = val; }; return SearchBoxParentModel; })(BaseObject); return SearchBoxParentModel; } ]); }).call(this); ; /* WindowsChildModel generator where there are many ChildModels to a parent. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [ 'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) { var WindowsParentModel; WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, gMap, markersScope) { this.gMap = gMap; this.markersScope = markersScope; this.modelKeyComparison = __bind(this.modelKeyComparison, this); this.interpolateContent = __bind(this.interpolateContent, this); this.setChildScope = __bind(this.setChildScope, this); this.createWindow = __bind(this.createWindow, this); this.setContentKeys = __bind(this.setContentKeys, this); this.pieceMeal = __bind(this.pieceMeal, this); this.createAllNew = __bind(this.createAllNew, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopes = __bind(this.createChildScopes, this); this.watchOurScope = __bind(this.watchOurScope, this); this.watchDestroy = __bind(this.watchDestroy, this); this.onDestroy = __bind(this.onDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); this.go = __bind(this.go, this); WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache); this["interface"] = IWindow; this.plurals = new PropMap(); _.each(IWindow.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.linked = new Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.firstWatchModels = true; this.$log.info(self); this.parentScope = void 0; this.go(scope); } WindowsParentModel.prototype.go = function(scope) { this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); return this.createChildScopes(); }; WindowsParentModel.prototype.watchModels = function(scope) { var itemToWatch; itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models'; return scope.$watch(itemToWatch, (function(_this) { return function(newValue, oldValue) { var doScratch; if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) { _this.firstWatchModels = false; if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) { return _this.rebuildAll(scope, true, true); } else { doScratch = _this.plurals.length === 0; if (_this.existingPieces != null) { return _.last(_this.existingPieces._content).then(function() { return _this.createChildScopes(doScratch); }); } else { return _this.createChildScopes(doScratch); } } } }; })(this), true); }; WindowsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; WindowsParentModel.prototype.onDestroy = function(scope) { WindowsParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var _ref; return (_ref = _this.plurals) != null ? _ref.removeAll() : void 0; }); }; })(this)); }; WindowsParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { _this.firstWatchModels = true; _this.firstTime = true; return _this.rebuildAll(scope, false, true); }; })(this)); }; WindowsParentModel.prototype.watchOurScope = function(scope) { return _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; }; })(this)); }; WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { var modelsNotDefined, _ref, _ref1; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (this.markersScope === void 0 || (((_ref = this.markersScope) != null ? _ref.plurals : void 0) === void 0 || ((_ref1 = this.markersScope) != null ? _ref1.models : void 0) === void 0))) { this.$log.error('No models to create windows from! Need direct models or models derived from markers!'); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.watchIdKey(this.linked.scope); if (isCreatingFromScratch) { return this.createAllNew(this.linked.scope, false); } else { return this.pieceMeal(this.linked.scope, false); } } else { this.parentScope = this.markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNew(this.markersScope, true, 'plurals', false); } else { return this.pieceMeal(this.markersScope, true, 'plurals', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } this.setContentKeys(scope.models); if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { var gMarker, _ref; gMarker = hasGMarker ? (_ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? _ref.gObject : void 0 : void 0; if (!maybeCanceled) { if (!gMarker && _this.markersScope) { $log.error('Unable to get gMarker from markersScope!'); } _this.createWindow(model, gMarker, _this.gMap); } return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.firstTime = false; }); }; })(this)); }; WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled, payload; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; this.models = scope.models; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { _this.plurals.remove(child.id); if (child.destroy != null) { child.destroy(true); } return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker, _ref; gMarker = (_ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? _ref.gObject : void 0; if (!gMarker) { throw 'Gmarker undefined'; } _this.createWindow(modelToAdd, gMarker, _this.gMap); return maybeCanceled; }); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }); }; })(this)); } else { $log.debug('pieceMeal: rebuildAll'); return this.rebuildAll(this.scope, true, true); } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (this.modelsLength()) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { var child, childScope, fakeElement, opts, _ref, _ref1; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); fakeElement = { html: (function(_this) { return function() { return _this.interpolateContent(_this.linked.element.html(), model); }; })(this) }; this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {}; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (_ref = this.markersScope) != null ? (_ref1 = _ref.plurals.get(model[this.idKey])) != null ? _ref1.scope : void 0 : void 0, fakeElement, false, true); if (model[this.idKey] == null) { this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.'); return; } this.plurals.put(model[this.idKey], child); return child; }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, interpModel, key, _i, _len, _ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = $interpolate(content); interpModel = {}; _ref = this.contentKeys; for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; interpModel[key] = model[key]; } return exp(interpModel); }; WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) { var isEqual, scope; scope = this.scope.coords != null ? this.scope : this.parentScope; if (scope == null) { throw 'No scope or parentScope set!'; } isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords)); if (!isEqual) { return isEqual; } isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) { return function(k) { return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]); }; })(this)); return isEqual; }; return WindowsParentModel; })(IWindowParentModel); return WindowsParentModel; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [ "uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) { return _.extend(ICircle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new CircleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [ "uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) { var Control; return Control = (function(_super) { __extends(Control, _super); function Control() { this.link = __bind(this.link, this); Control.__super__.constructor.call(this); } Control.prototype.link = function(scope, element, attrs, ctrl) { return GoogleMapApi.then((function(_this) { return function(maps) { var index, position; if (angular.isUndefined(scope.template)) { _this.$log.error('mapControl: could not find a valid template property'); return; } index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0; position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER'; if (!maps.ControlPosition[position]) { _this.$log.error('mapControl: invalid position property'); return; } return IControl.mapPromise(scope, ctrl).then(function(map) { var control, controlDiv; control = void 0; controlDiv = angular.element('<div></div>'); return $http.get(scope.template, { cache: $templateCache }).success(function(template) { var templateCtrl, templateScope; templateScope = scope.$new(); controlDiv.append(template); if (angular.isDefined(scope.controller)) { templateCtrl = $controller(scope.controller, { $scope: templateScope }); controlDiv.children().data('$ngControllerController', templateCtrl); } control = $compile(controlDiv.children())(templateScope); if (index) { return control[0].index = index; } }).error(function(error) { return _this.$log.error('mapControl: template could not be found'); }).then(function() { return map.controls[google.maps.ControlPosition[position]].push(control[0]); }); }); }; })(this)); }; return Control; })(IControl); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [ 'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) { return { restrict: 'EMA', transclude: true, template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>', require: '^' + 'uiGmapGoogleMap', scope: { keyboardkey: '=', options: '=', spec: '=' }, controller: [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'uiGmapDragZoom'; return _.extend(this, CtrlHandle.handle($scope, $element)); } ], link: function(scope, element, attrs, ctrl) { return CtrlHandle.mapPromise(scope, ctrl).then(function(map) { var enableKeyDragZoom, setKeyAction, setOptionsAction; enableKeyDragZoom = function(opts) { map.enableKeyDragZoom(opts); if (scope.spec) { return scope.spec.enableKeyDragZoom(opts); } }; setKeyAction = new PropertyAction(function(key, newVal) { if (newVal) { return enableKeyDragZoom({ key: newVal }); } else { return enableKeyDragZoom(); } }); setOptionsAction = new PropertyAction(function(key, newVal) { if (newVal) { return enableKeyDragZoom(newVal); } }); scope.$watch('keyboardkey', setKeyAction.sic); setKeyAction.sic(scope.keyboardkey); scope.$watch('options', setOptionsAction.sic); return setOptionsAction.sic(scope.options); }); } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [ "uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) { return _.extend(IDrawingManager, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then(function(map) { return new DrawingManagerParentModel(scope, element, attrs, map); }); } }); } ]); }).call(this); ; /* - Link up Polygons to be sent back to a controller - inject the draw function into a controllers scope so that controller can call the directive to draw on demand - draw function creates the DrawFreeHandChildModel which manages itself */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [ 'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) { var FreeDrawPolygons; return FreeDrawPolygons = (function(_super) { __extends(FreeDrawPolygons, _super); function FreeDrawPolygons() { this.link = __bind(this.link, this); return FreeDrawPolygons.__super__.constructor.apply(this, arguments); } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EMA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap'; FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=' }; FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) { return this.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var freeHand, listener; if (!scope.polygons) { return $log.error('No polygons to bind to!'); } if (!_.isArray(scope.polygons)) { return $log.error('Free Draw Polygons must be of type Array!'); } freeHand = new DrawFreeHandChildModel(map, ctrl.getScope()); listener = void 0; return scope.draw = function() { if (typeof listener === "function") { listener(); } return freeHand.engage(scope.polygons).then(function() { var firstTime; firstTime = true; return listener = scope.$watchCollection('polygons', function(newValue, oldValue) { var removals; if (firstTime || newValue === oldValue) { firstTime = false; return; } removals = uiGmapLodash.differenceObjects(oldValue, newValue); return removals.forEach(function(p) { return p.setMap(null); }); }); }); }; }; })(this)); }; return FreeDrawPolygons; })(BaseObject); } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [ function() { var DEFAULTS; DEFAULTS = {}; return { restrict: "EA", replace: true, require: '^' + 'uiGmapGoogleMap', scope: { center: "=center", radius: "=radius", stroke: "=stroke", fill: "=fill", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=", events: "=", control: "=" } }; } ]); }).call(this); ; /* - interface for all controls to derive from - to enforce a minimum set of requirements - attributes - template - position - controller - index */ (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [ "uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) { var IControl; return IControl = (function(_super) { __extends(IControl, _super); IControl.extend(CtrlHandle); function IControl() { this.restrict = 'EA'; this.replace = true; this.require = '^' + 'uiGmapGoogleMap'; this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IControl; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [ function() { return { restrict: 'EA', replace: true, require: '^' + 'uiGmapGoogleMap', scope: { "static": '@', control: '=', options: '=', events: '=' } }; } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [ 'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(_super) { __extends(IMarker, _super); IMarker.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; IMarker.scopeKeys = _.keys(IMarker.scope); IMarker.keys = IMarker.scopeKeys; IMarker.extend(CtrlHandle); function IMarker() { this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = _.extend(this.scope || {}, IMarker.scope); } return IMarker; })(BaseObject); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolygon; return IPolygon = (function(_super) { __extends(IPolygon, _super); IPolygon.scope = { path: '=path', stroke: '=stroke', clickable: '=', draggable: '=', editable: '=', geodesic: '=', fill: '=', icons: '=icons', visible: '=', "static": '=', events: '=', zIndex: '=zindex', fit: '=', control: '=control' }; IPolygon.scopeKeys = _.keys(IPolygon.scope); IPolygon.include(GmapUtil); IPolygon.extend(CtrlHandle); function IPolygon() {} IPolygon.prototype.restrict = 'EMA'; IPolygon.prototype.replace = true; IPolygon.prototype.require = '^' + 'uiGmapGoogleMap'; IPolygon.prototype.scope = IPolygon.scope; IPolygon.prototype.DEFAULTS = {}; IPolygon.prototype.$log = Logger; return IPolygon; })(BaseObject); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolyline; return IPolyline = (function(_super) { __extends(IPolyline, _super); IPolyline.scope = { path: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', geodesic: '=', icons: '=', visible: '=', "static": '=', fit: '=', events: '=' }; IPolyline.scopeKeys = _.keys(IPolyline.scope); IPolyline.include(GmapUtil); IPolyline.extend(CtrlHandle); function IPolyline() {} IPolyline.prototype.restrict = 'EMA'; IPolyline.prototype.replace = true; IPolyline.prototype.require = '^' + 'uiGmapGoogleMap'; IPolyline.prototype.scope = IPolyline.scope; IPolyline.prototype.DEFAULTS = {}; IPolyline.prototype.$log = Logger; return IPolyline; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [ function() { 'use strict'; var DEFAULTS; DEFAULTS = {}; return { restrict: 'EMA', require: '^' + 'uiGmapGoogleMap', replace: true, scope: { bounds: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', fill: '=', visible: '=', events: '=' } }; } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [ 'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) { var IWindow; return IWindow = (function(_super) { __extends(IWindow, _super); IWindow.scope = { coords: '=coords', template: '=template', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options', control: '=control', show: '=show' }; IWindow.scopeKeys = _.keys(IWindow.scope); IWindow.include(ChildEvents); IWindow.extend(CtrlHandle); function IWindow() { this.restrict = 'EMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = '^' + 'uiGmapGoogleMap'; this.replace = true; this.scope = _.extend(this.scope || {}, IWindow.scope); } return IWindow; })(BaseObject); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [ '$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) { 'use strict'; var DEFAULTS, Map, initializeItems; DEFAULTS = void 0; initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer]; return Map = (function(_super) { __extends(Map, _super); Map.include(GmapUtil); function Map() { this.link = __bind(this.link, this); var ctrlFn, self; ctrlFn = function($scope) { var ctrlObj, retCtrl; retCtrl = void 0; $scope.$on('$destroy', function() { return IsReady.reset(); }); ctrlObj = CtrlHandle.handle($scope); $scope.ctrlType = 'Map'; $scope.deferred.promise.then(function() { return initializeItems.forEach(function(i) { return i.init(); }); }); ctrlObj.getMap = function() { return $scope.map; }; retCtrl = _.extend(this, ctrlObj); return retCtrl; }; this.controller = ['$scope', ctrlFn]; self = this; } Map.prototype.restrict = 'EMA'; Map.prototype.transclude = true; Map.prototype.replace = false; Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>'; Map.prototype.scope = { center: '=', zoom: '=', dragging: '=', control: '=', options: '=', events: '=', eventOpts: '=', styles: '=', bounds: '=', update: '=' }; Map.prototype.link = function(scope, element, attrs) { var listeners, unbindCenterWatch; listeners = []; scope.$on('$destroy', function() { return EventsHelper.removeEvents(listeners); }); scope.idleAndZoomChanged = false; if (scope.center == null) { unbindCenterWatch = scope.$watch('center', (function(_this) { return function() { if (!scope.center) { return; } unbindCenterWatch(); return _this.link(scope, element, attrs); }; })(this)); return; } return GoogleMapApi.then((function(_this) { return function(maps) { var customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise, _gMap, _ref; DEFAULTS = { mapTypeId: maps.MapTypeId.ROADMAP }; spawned = IsReady.spawn(); resolveSpawned = function() { return spawned.deferred.resolve({ instance: spawned.instance, map: _gMap }); }; if (!_this.validateCoords(scope.center)) { $log.error('angular-google-maps: could not find a valid center property'); return; } if (!angular.isDefined(scope.zoom)) { $log.error('angular-google-maps: map zoom property not set'); return; } el = angular.element(element); el.addClass('angular-google-map'); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type '" + attrs.type + "'"); } } mapOptions = angular.extend({}, DEFAULTS, opts, { center: _this.getCoords(scope.center), zoom: scope.zoom, bounds: scope.bounds }); _gMap = new google.maps.Map(el.find('div')[1], mapOptions); _gMap['uiGmap_id'] = uuid.generate(); dragging = false; listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() { scope.deferred.resolve(_gMap); return resolveSpawned(); })); disabledEvents = attrs.events && (((_ref = scope.events) != null ? _ref.blacklist : void 0) != null) ? scope.events.blacklist : []; if (_.isString(disabledEvents)) { disabledEvents = [disabledEvents]; } maybeHookToEvent = function(eventName, fn, prefn) { if (!_.contains(disabledEvents, eventName)) { if (prefn) { prefn(); } return listeners.push(google.maps.event.addListener(_gMap, eventName, function() { var _ref1; if (!((_ref1 = scope.update) != null ? _ref1.lazy : void 0)) { return fn(); } })); } }; if (!_.contains(disabledEvents, 'all')) { maybeHookToEvent('dragstart', function() { dragging = true; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); maybeHookToEvent('dragend', function() { dragging = false; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); updateCenter = function(c, s) { if (c == null) { c = _gMap.center; } if (s == null) { s = scope; } if (_.contains(disabledEvents, 'center')) { return; } if (angular.isDefined(s.center.type)) { if (s.center.coordinates[1] !== c.lat()) { s.center.coordinates[1] = c.lat(); } if (s.center.coordinates[0] !== c.lng()) { return s.center.coordinates[0] = c.lng(); } } else { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } }; settingFromDirective = false; maybeHookToEvent('idle', function() { var b, ne, sw; b = _gMap.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); settingFromDirective = true; return scope.$evalAsync(function(s) { updateCenter(); if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } if (!_.contains(disabledEvents, 'zoom')) { s.zoom = _gMap.zoom; scope.idleAndZoomChanged = !scope.idleAndZoomChanged; } return settingFromDirective = false; }); }); } if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]); }; }; customListeners = []; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName))); } } listeners.concat(customListeners); } _gMap.getOptions = function() { return mapOptions; }; scope.map = _gMap; if ((attrs.control != null) && (scope.control != null)) { scope.control.refresh = function(maybeCoords) { var coords, _ref1, _ref2; if (_gMap == null) { return; } if (((typeof google !== "undefined" && google !== null ? (_ref1 = google.maps) != null ? (_ref2 = _ref1.event) != null ? _ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) { google.maps.event.trigger(_gMap, 'resize'); } if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) { coords = _this.getCoords(maybeCoords); if (_this.isTrue(attrs.pan)) { return _gMap.panTo(coords); } else { return _gMap.setCenter(coords); } } }; scope.control.getGMap = function() { return _gMap; }; scope.control.getMapOptions = function() { return mapOptions; }; scope.control.getCustomEventListeners = function() { return customListeners; }; scope.control.removeEvents = function(yourListeners) { return EventsHelper.removeEvents(yourListeners); }; } scope.$watch('center', function(newValue, oldValue) { var coords, settingCenterFromScope; if (newValue === oldValue || settingFromDirective) { return; } coords = _this.getCoords(scope.center); if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) { return; } settingCenterFromScope = true; if (!dragging) { if (!_this.validateCoords(newValue)) { $log.error("Invalid center for newValue: " + (JSON.stringify(newValue))); } if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) { _gMap.panTo(coords); } else { _gMap.setCenter(coords); } } return settingCenterFromScope = false; }, true); zoomPromise = null; scope.$watch('zoom', function(newValue, oldValue) { var settingZoomFromScope, _ref1, _ref2; if (newValue == null) { return; } if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) { return; } settingZoomFromScope = true; if (zoomPromise != null) { $timeout.cancel(zoomPromise); } return zoomPromise = $timeout(function() { _gMap.setZoom(newValue); return settingZoomFromScope = false; }, ((_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.zoomMs : void 0 : void 0) + 20, false); }); scope.$watch('bounds', function(newValue, oldValue) { var bounds, ne, sw, _ref1, _ref2, _ref3, _ref4; if (newValue === oldValue) { return; } if (((newValue != null ? (_ref1 = newValue.northeast) != null ? _ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (_ref2 = newValue.northeast) != null ? _ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (_ref3 = newValue.southwest) != null ? _ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (_ref4 = newValue.southwest) != null ? _ref4.longitude : void 0 : void 0) == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _gMap.fitBounds(bounds); }); return ['options', 'styles'].forEach(function(toWatch) { return scope.$watch(toWatch, function(newValue, oldValue) { var watchItem; watchItem = this.exp; if (_.isEqual(newValue, oldValue)) { return; } if (watchItem === 'options') { opts.options = newValue; } else { opts.options[watchItem] = newValue; } if (_gMap != null) { return _gMap.setOptions(opts); } }, true); }); }; })(this)); }; return Map; })(BaseObject); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [ "uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) { var Marker; return Marker = (function(_super) { __extends(Marker, _super); function Marker() { this.link = __bind(this.link, this); Marker.__super__.constructor.call(this); this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; $log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Marker'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { var mapPromise; mapPromise = IMarker.mapPromise(scope, ctrl); mapPromise.then((function(_this) { return function(map) { var doClick, doDrawSelf, gManager, keys, m, trackModel; gManager = new MarkerManager(map); keys = _.object(IMarker.keys, IMarker.keys); m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false); m.deferred.promise.then(function(gMarker) { return scope.deferred.resolve(gMarker); }); if (scope.control != null) { return scope.control.getGMarkers = gManager.getGMarkers; } }; })(this)); return scope.$on('$destroy', (function(_this) { return function() { var gManager; if (typeof gManager !== "undefined" && gManager !== null) { gManager.clear(); } return gManager = null; }; })(this)); }; return Marker; })(IMarker); } ]); }).call(this); ;(function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [ "uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) { var Markers; return Markers = (function(_super) { __extends(Markers, _super); function Markers() { Markers.__super__.constructor.call(this); this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; Plural.extend(this, { doCluster: '=docluster', clusterOptions: '=clusteroptions', clusterEvents: '=clusterevents', modelsByRef: '=modelsbyref' }); $log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Markers'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { var parentModel, ready; parentModel = void 0; ready = function() { return scope.deferred.resolve(); }; return IMarker.mapPromise(scope, ctrl).then(function(map) { var mapScope; mapScope = ctrl.getScope(); mapScope.$watch('idleAndZoomChanged', function() { return _.defer(parentModel.gManager.draw); }); parentModel = new MarkersParentModel(scope, element, attrs, map); Plural.link(scope, parentModel); if (scope.control != null) { scope.control.getGMarkers = function() { var _ref; return (_ref = parentModel.gManager) != null ? _ref.getGMarkers() : void 0; }; scope.control.getChildMarkers = function() { return parentModel.plurals; }; } return _.last(parentModel.existingPieces._content).then(function() { return ready(); }); }); }; return Markers; })(IMarker); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [ function() { var _initControl; _initControl = function(scope, parent) { if (scope.control == null) { return; } scope.control.updateModels = function(models) { scope.models = models; return parent.createChildScopes(false); }; scope.control.newModels = function(models) { scope.models = models; return parent.rebuildAll(scope, true, true); }; scope.control.clean = function() { return parent.rebuildAll(scope, false, true); }; scope.control.getPlurals = function() { return parent.plurals; }; scope.control.getManager = function() { return parent.gManager; }; scope.control.hasManager = function() { return (parent.gManager != null) === true; }; return scope.control.managerDraw = function() { var _ref; if (scope.control.hasManager()) { return (_ref = scope.control.getManager()) != null ? _ref.draw() : void 0; } }; }; return { extend: function(obj, obj2) { return _.extend(obj.scope || {}, obj2 || {}, { idKey: '=idkey', doRebuildAll: '=dorebuildall', models: '=models', chunk: '=chunk', cleanchunk: '=cleanchunk', control: '=control' }); }, link: function(scope, parent) { return _initControl(scope, parent); } }; } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [ 'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) { var Polygon; return Polygon = (function(_super) { __extends(Polygon, _super); function Polygon() { this.link = __bind(this.link, this); return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.link = function(scope, element, attrs, mapCtrl) { var children, promise; children = []; promise = IPolygon.mapPromise(scope, mapCtrl); if (scope.control != null) { scope.control.getInstance = this; scope.control.polygons = children; scope.control.promise = promise; } return promise.then((function(_this) { return function(map) { return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygon; })(IPolygon); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [ 'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) { var Polygons; return Polygons = (function(_super) { __extends(Polygons, _super); function Polygons() { this.link = __bind(this.link, this); Polygons.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polygons.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polygons: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polygons: no models found to create from'); } return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygons; })(Interface); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [ 'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) { var Polyline; return Polyline = (function(_super) { __extends(Polyline, _super); function Polyline() { this.link = __bind(this.link, this); return Polyline.__super__.constructor.apply(this, arguments); } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) { _this.$log.warn('polyline: no valid path attribute found'); } return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS); }; })(this)); }; return Polyline; })(IPolyline); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [ 'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) { var Polylines; return Polylines = (function(_super) { __extends(Polylines, _super); function Polylines() { this.link = __bind(this.link, this); Polylines.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polylines.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polylines: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polylines: no models found to create from'); } return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polylines; })(IPolyline); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) { return _.extend(IRectangle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new RectangleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [ 'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) { var Window; return Window = (function(_super) { __extends(Window, _super); Window.include(GmapUtil); function Window() { this.link = __bind(this.link, this); Window.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; $log.debug(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var markerCtrl, markerScope; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; this.mapPromise = IWindow.mapPromise(scope, ctrls[0]); return this.mapPromise.then((function(_this) { return function(mapCtrl) { var isIconVisibleOnClick; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } if (!markerCtrl) { _this.init(scope, element, isIconVisibleOnClick, mapCtrl); return; } return markerScope.deferred.promise.then(function(gMarker) { return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope); }); }; })(this)); }; Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) { var childWindow, defaults, gMarker, hasScopeCoords, opts; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && this.validateCoords(scope.coords); if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) { gMarker = markerScope.getGMarker(); } opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults; if (mapCtrl != null) { childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element); this.childWindows.push(childWindow); scope.$on('$destroy', (function(_this) { return function() { _this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) { return child1.scope.$id === child2.scope.$id; }); return _this.childWindows.length = 0; }; })(this)); } if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.gObject; }); }; })(this); scope.control.getChildWindows = (function(_this) { return function() { return _this.childWindows; }; })(this); scope.control.getPlurals = scope.control.getChildWindows; scope.control.showWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.showWindow(); }); }; })(this); scope.control.hideWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.hideWindow(); }); }; })(this); } if ((this.onChildCreation != null) && (childWindow != null)) { return this.onChildCreation(childWindow); } }; return Window; })(IWindow); } ]); }).call(this); ;(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [ 'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) { /* Windows directive where many windows map to the models property */ var Windows; return Windows = (function(_super) { __extends(Windows, _super); function Windows() { this.init = __bind(this.init, this); this.link = __bind(this.link, this); Windows.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; Plural.extend(this); $log.debug(this); } Windows.prototype.link = function(scope, element, attrs, ctrls) { var mapScope, markerCtrl, markerScope; mapScope = ctrls[0].getScope(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; return mapScope.deferred.promise.then((function(_this) { return function(map) { var promise, _ref; promise = (markerScope != null ? (_ref = markerScope.deferred) != null ? _ref.promise : void 0 : void 0) || uiGmapPromise.resolve(); return promise.then(function() { var pieces, _ref1; pieces = (_ref1 = _this.parentModel) != null ? _ref1.existingPieces : void 0; if (pieces) { return pieces.then(function() { return _this.init(scope, element, attrs, ctrls, map, markerScope); }); } else { return _this.init(scope, element, attrs, ctrls, map, markerScope); } }); }; })(this)); }; Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) { var parentModel; parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope); Plural.link(scope, parentModel); if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return parentModel.plurals.map(function(child) { return child.gObject; }); }; })(this); return scope.control.getChildWindows = (function(_this) { return function() { return parentModel.plurals; }; })(this); } }; return Windows; })(IWindow); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [ "uiGmapMap", function(Map) { return new Map(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [ '$timeout', 'uiGmapMarker', function($timeout, Marker) { return new Marker($timeout); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [ '$timeout', 'uiGmapMarkers', function($timeout, Markers) { return new Markers($timeout); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [ 'uiGmapPolygon', function(Polygon) { return new Polygon(); } ]); }).call(this); ; /* @authors Julian Popescu - https://github.com/jpopesculian Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [ "uiGmapCircle", function(Circle) { return Circle; } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [ "uiGmapPolyline", function(Polyline) { return new Polyline(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [ 'uiGmapPolylines', function(Polylines) { return new Polylines(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Chentsu Lin - https://github.com/ChenTsuLin */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [ "uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) { return Rectangle; } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [ "$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) { return new Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) { return new Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); ; /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [ '$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) { var Layer; Layer = (function() { function Layer() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>'; this.replace = true; this.scope = { show: '=show', type: '=type', namespace: '=namespace', options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (scope.onCreated != null) { return new LayerParentModel(scope, element, attrs, map, scope.onCreated); } else { return new LayerParentModel(scope, element, attrs, map); } }; })(this)); }; return Layer; })(); return new Layer(); } ]); }).call(this); ; /* @authors Adam Kreitals, kreitals@hotmail.com */ /* mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [ "uiGmapControl", function(Control) { return new Control(); } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [ 'uiGmapDragZoom', function(DragZoom) { return DragZoom; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [ "uiGmapDrawingManager", function(DrawingManager) { return DrawingManager; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready * Brunt of the work is in DrawFreeHandChildModel */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [ 'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) { return new FreeDrawPolygons(); } ]); }).call(this); ; /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [ "$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) { var MapType; MapType = (function() { function MapType() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", options: '=options', refresh: '=refresh', id: '@' }; } MapType.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new MapTypeParentModel(scope, element, attrs, map); }; })(this)); }; return MapType; })(); return new MapType(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [ 'uiGmapPolygons', function(Polygons) { return new Polygons(); } ]); }).call(this); ; /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready - Carrie Kengle - http://about.me/carrie */ /* Places Search Box directive This directive is used to create a Places Search Box. This directive creates a new scope. {attribute input required} HTMLInputElement {attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification) */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [ 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) { var SearchBox; SearchBox = (function() { SearchBox.prototype.require = 'ngModel'; function SearchBox() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>'; this.replace = true; this.scope = { template: '=template', events: '=events', position: '=?position', options: '=?options', parentdiv: '=?parentdiv', ngModel: "=?" }; } SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) { return GoogleMapApi.then((function(_this) { return function(maps) { return $http.get(scope.template, { cache: $templateCache }).success(function(template) { if (angular.isUndefined(scope.events)) { _this.$log.error('searchBox: the events property is required'); return; } return mapCtrl.getScope().deferred.promise.then(function(map) { var ctrlPosition; ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT'; if (!maps.ControlPosition[ctrlPosition]) { _this.$log.error('searchBox: invalid position property'); return; } return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope)); }); }); }; })(this)); }; return SearchBox; })(); return new SearchBox(); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [ '$animate', 'uiGmapLogger', function($animate, $log) { return { scope: { 'uiGmapShow': '=', 'uiGmapAfterShow': '&', 'uiGmapAfterHide': '&' }, link: function(scope, element) { var angular_post_1_3_handle, angular_pre_1_3_handle, handle; angular_post_1_3_handle = function(animateAction, cb) { return $animate[animateAction](element, 'ng-hide').then(function() { return cb(); }); }; angular_pre_1_3_handle = function(animateAction, cb) { return $animate[animateAction](element, 'ng-hide', cb); }; handle = function(animateAction, cb) { if (angular.version.major > 1) { return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\""); } if (angular.version.major === 1 && angular.version.minor < 3) { return angular_pre_1_3_handle(animateAction, cb); } return angular_post_1_3_handle(animateAction, cb); }; return scope.$watch('uiGmapShow', function(show) { if (show) { handle('removeClass', scope.uiGmapAfterShow); } if (!show) { return handle('addClass', scope.uiGmapAfterHide); } }); } }; } ]); }).call(this); ; /* @authors: - Nicholas McCready - https://twitter.com/nmccready */ /* StreetViewPanorama Directive to care of basic initialization of StreetViewPanorama */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapStreetViewPanorama', [ 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function(GoogleMapApi, $log, GmapUtil, EventsHelper) { var name; name = 'uiGmapStreetViewPanorama'; return { restrict: 'EMA', template: '<div class="angular-google-map-street-view-panorama"></div>', replace: true, scope: { focalcoord: '=', radius: '=?', events: '=?', options: '=?', control: '=?', povoptions: '=?', imagestatus: '=' }, link: function(scope, element, attrs) { return GoogleMapApi.then((function(_this) { return function(maps) { var clean, create, didCreateOptionsFromDirective, firstTime, handleSettings, listeners, opts, pano, povOpts, sv; pano = void 0; sv = void 0; didCreateOptionsFromDirective = false; listeners = void 0; opts = null; povOpts = null; clean = function() { EventsHelper.removeEvents(listeners); if (pano != null) { pano.unbind('position'); pano.setVisible(false); } if (sv != null) { if ((sv != null ? sv.setVisible : void 0) != null) { sv.setVisible(false); } return sv = void 0; } }; handleSettings = function(perspectivePoint, focalPoint) { var heading; heading = google.maps.geometry.spherical.computeHeading(perspectivePoint, focalPoint); didCreateOptionsFromDirective = true; scope.radius = scope.radius || 50; povOpts = angular.extend({ heading: heading, zoom: 1, pitch: 0 }, scope.povoptions || {}); opts = opts = angular.extend({ navigationControl: false, addressControl: false, linksControl: false, position: perspectivePoint, pov: povOpts, visible: true }, scope.options || {}); return didCreateOptionsFromDirective = false; }; create = function() { var focalPoint; if (!scope.focalcoord) { $log.error("" + name + ": focalCoord needs to be defined"); return; } if (!scope.radius) { $log.error("" + name + ": needs a radius to set the camera view from its focal target."); return; } clean(); if (sv == null) { sv = new google.maps.StreetViewService(); } if (scope.events) { listeners = EventsHelper.setEvents(sv, scope, scope); } focalPoint = GmapUtil.getCoords(scope.focalcoord); return sv.getPanoramaByLocation(focalPoint, scope.radius, function(streetViewPanoramaData, status) { var ele, perspectivePoint, _ref; if (scope.imagestatus != null) { scope.imagestatus = status; } if (((_ref = scope.events) != null ? _ref.image_status_changed : void 0) != null) { scope.events.image_status_changed(sv, 'image_status_changed', scope, status); } if (status === "OK") { perspectivePoint = streetViewPanoramaData.location.latLng; handleSettings(perspectivePoint, focalPoint); ele = element[0]; return pano = new google.maps.StreetViewPanorama(ele, opts); } }); }; if (scope.control != null) { scope.control.getOptions = function() { return opts; }; scope.control.getPovOptions = function() { return povOpts; }; scope.control.getGObject = function() { return sv; }; } scope.$watch('options', function(newValue, oldValue) { if (newValue === oldValue || newValue === opts || didCreateOptionsFromDirective) { return; } return create(); }); firstTime = true; scope.$watch('focalcoord', function(newValue, oldValue) { if (newValue === oldValue && !firstTime) { return; } if (newValue == null) { return; } firstTime = false; return create(); }); return scope.$on('$destroy', function() { return clean(); }); }; })(this)); } }; } ]); }).call(this); ;angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapuuid', function() { //BEGIN REPLACE /* Version: core-1.0 The MIT License: Copyright (c) 2012 LiosK. */ function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c}; //END REPLACE return UUID; }); ;// wrap the utility libraries needed in ./lib // http://google-maps-utility-library-v3.googlecode.com/svn/ angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapGoogleMapsUtilV3', function () { return { init: _.once(function () { //BEGIN REPLACE /** * @name InfoBox * @version 1.1.13 [March 19, 2014] * @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google) * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] * @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class. * <p> * An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several * additional properties for advanced styling. An InfoBox can also be used as a map label. * <p> * An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>. */ /*! * * 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 browser:true */ /*global google */ /** * @name InfoBoxOptions * @class This class represents the optional parameter passed to the {@link InfoBox} constructor. * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node). * @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>. * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum. * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox * (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>) * to the map pixel corresponding to <tt>position</tt>. * @property {LatLng} position The geographic location at which to display the InfoBox. * @property {number} zIndex The CSS z-index style value for the InfoBox. * Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property. * @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container. * @property {Object} [boxStyle] An object literal whose properties define specific CSS * style values to be applied to the InfoBox. Style values defined here override those that may * be defined in the <code>boxClass</code> style sheet. If this property is changed after the * InfoBox has been created, all previously set styles (except those defined in the style sheet) * are removed from the InfoBox before the new style values are applied. * @property {string} closeBoxMargin The CSS margin style value for the close box. * The default is "2px" (a 2-pixel margin on all sides). * @property {string} closeBoxURL The URL of the image representing the close box. * Note: The default is the URL for Google's standard close box. * Set this property to "" if no close box is required. * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the * map edge after an auto-pan. * @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>. * [Deprecated in favor of the <tt>visible</tt> property.] * @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>. * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code> * location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned). * @property {string} pane The pane where the InfoBox is to appear (default is "floatPane"). * Set the pane to "mapPane" if the InfoBox is being used as a map label. * Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object. * @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout, * mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox * (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set * this property to <tt>true</tt> if the InfoBox is being used as a map label. */ /** * Creates an InfoBox with the options specified in {@link InfoBoxOptions}. * Call <tt>InfoBox.open</tt> to add the box to the map. * @constructor * @param {InfoBoxOptions} [opt_opts] */ function InfoBox(opt_opts) { opt_opts = opt_opts || {}; google.maps.OverlayView.apply(this, arguments); // Standard options (in common with google.maps.InfoWindow): // this.content_ = opt_opts.content || ""; this.disableAutoPan_ = opt_opts.disableAutoPan || false; this.maxWidth_ = opt_opts.maxWidth || 0; this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0); this.position_ = opt_opts.position || new google.maps.LatLng(0, 0); this.zIndex_ = opt_opts.zIndex || null; // Additional options (unique to InfoBox): // this.boxClass_ = opt_opts.boxClass || "infoBox"; this.boxStyle_ = opt_opts.boxStyle || {}; this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px"; this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif"; if (opt_opts.closeBoxURL === "") { this.closeBoxURL_ = ""; } this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1); if (typeof opt_opts.visible === "undefined") { if (typeof opt_opts.isHidden === "undefined") { opt_opts.visible = true; } else { opt_opts.visible = !opt_opts.isHidden; } } this.isHidden_ = !opt_opts.visible; this.alignBottom_ = opt_opts.alignBottom || false; this.pane_ = opt_opts.pane || "floatPane"; this.enableEventPropagation_ = opt_opts.enableEventPropagation || false; this.div_ = null; this.closeListener_ = null; this.moveListener_ = null; this.contextListener_ = null; this.eventListeners_ = null; this.fixedWidthSet_ = null; } /* InfoBox extends OverlayView in the Google Maps API v3. */ InfoBox.prototype = new google.maps.OverlayView(); /** * Creates the DIV representing the InfoBox. * @private */ InfoBox.prototype.createInfoBoxDiv_ = function () { var i; var events; var bw; var me = this; // This handler prevents an event in the InfoBox from being passed on to the map. // var cancelHandler = function (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; // This handler ignores the current event in the InfoBox and conditionally prevents // the event from being passed on to the map. It is used for the contextmenu event. // var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }; if (!this.div_) { this.div_ = document.createElement("div"); this.setBoxStyle_(); if (typeof this.content_.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + this.content_; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(this.content_); } // Add the InfoBox DIV to the DOM this.getPanes()[this.pane_].appendChild(this.div_); this.addClickHandler_(); if (this.div_.style.width) { this.fixedWidthSet_ = true; } else { if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) { this.div_.style.width = this.maxWidth_; this.div_.style.overflow = "auto"; this.fixedWidthSet_ = true; } else { // The following code is needed to overcome problems with MSIE bw = this.getBoxWidths_(); this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px"; this.fixedWidthSet_ = false; } } this.panBox_(this.disableAutoPan_); if (!this.enableEventPropagation_) { this.eventListeners_ = []; // Cancel event propagation. // // Note: mousemove not included (to resolve Issue 152) events = ["mousedown", "mouseover", "mouseout", "mouseup", "click", "dblclick", "touchstart", "touchend", "touchmove"]; for (i = 0; i < events.length; i++) { this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler)); } // Workaround for Google bug that causes the cursor to change to a pointer // when the mouse moves over a marker underneath InfoBox. this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) { this.style.cursor = "default"; })); } this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler); /** * This event is fired when the DIV containing the InfoBox's content is attached to the DOM. * @name InfoBox#domready * @event */ google.maps.event.trigger(this, "domready"); } }; /** * Returns the HTML <IMG> tag for the close box. * @private */ InfoBox.prototype.getCloseBoxImg_ = function () { var img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; // Do this because Opera chokes on style='float: right;' img += " style='"; img += " position: relative;"; // Required by MSIE img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; /** * Adds the click handler to the InfoBox close box. * @private */ InfoBox.prototype.addClickHandler_ = function () { var closeBox; if (this.closeBoxURL_ !== "") { closeBox = this.div_.firstChild; this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_()); } else { this.closeListener_ = null; } }; /** * Returns the function to call when the user clicks the close box of an InfoBox. * @private */ InfoBox.prototype.getCloseClickHandler_ = function () { var me = this; return function (e) { // 1.0.3 fix: Always prevent propagation of a close box click to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } /** * This event is fired when the InfoBox's close box is clicked. * @name InfoBox#closeclick * @event */ google.maps.event.trigger(me, "closeclick"); me.close(); }; }; /** * Pans the map so that the InfoBox appears entirely within the map's visible area. * @private */ InfoBox.prototype.panBox_ = function (disablePan) { var map; var bounds; var xOffset = 0, yOffset = 0; if (!disablePan) { map = this.getMap(); if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama if (!map.getBounds().contains(this.position_)) { // Marker not in visible area of map, so set center // of map to the marker position first. map.setCenter(this.position_); } bounds = map.getBounds(); var mapDiv = map.getDiv(); var mapWidth = mapDiv.offsetWidth; var mapHeight = mapDiv.offsetHeight; var iwOffsetX = this.pixelOffset_.width; var iwOffsetY = this.pixelOffset_.height; var iwWidth = this.div_.offsetWidth; var iwHeight = this.div_.offsetHeight; var padX = this.infoBoxClearance_.width; var padY = this.infoBoxClearance_.height; var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_); if (pixPosition.x < (-iwOffsetX + padX)) { xOffset = pixPosition.x + iwOffsetX - padX; } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) { xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth; } if (this.alignBottom_) { if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) { yOffset = pixPosition.y + iwOffsetY - padY - iwHeight; } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwOffsetY + padY - mapHeight; } } else { if (pixPosition.y < (-iwOffsetY + padY)) { yOffset = pixPosition.y + iwOffsetY - padY; } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight; } } if (!(xOffset === 0 && yOffset === 0)) { // Move the map to the shifted center. // var c = map.getCenter(); map.panBy(xOffset, yOffset); } } } }; /** * Sets the style of the InfoBox by setting the style sheet and applying * other specific styles requested. * @private */ InfoBox.prototype.setBoxStyle_ = function () { var i, boxStyle; if (this.div_) { // Apply style values from the style sheet defined in the boxClass parameter: this.div_.className = this.boxClass_; // Clear existing inline style values: this.div_.style.cssText = ""; // Apply style values defined in the boxStyle parameter: boxStyle = this.boxStyle_; for (i in boxStyle) { if (boxStyle.hasOwnProperty(i)) { this.div_.style[i] = boxStyle[i]; } } // Fix for iOS disappearing InfoBox problem. // See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad this.div_.style.WebkitTransform = "translateZ(0)"; // Fix up opacity style for benefit of MSIE: // if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") { // See http://www.quirksmode.org/css/opacity.html this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\""; this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")"; } // Apply required styles: // this.div_.style.position = "absolute"; this.div_.style.visibility = 'hidden'; if (this.zIndex_ !== null) { this.div_.style.zIndex = this.zIndex_; } } }; /** * Get the widths of the borders of the InfoBox. * @private * @return {Object} widths object (top, bottom left, right) */ InfoBox.prototype.getBoxWidths_ = function () { var computedStyle; var bw = {top: 0, bottom: 0, left: 0, right: 0}; var box = this.div_; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; } } else if (document.documentElement.currentStyle) { // MSIE if (box.currentStyle) { // The current styles may not be in pixel units, but assume they are (bad!) bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0; } } return bw; }; /** * Invoked when <tt>close</tt> is called. Do not call it directly. */ InfoBox.prototype.onRemove = function () { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the InfoBox based on the current map projection and zoom level. */ InfoBox.prototype.draw = function () { this.createInfoBoxDiv_(); var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_); this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px"; if (this.alignBottom_) { this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px"; } else { this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px"; } if (this.isHidden_) { this.div_.style.visibility = "hidden"; } else { this.div_.style.visibility = "visible"; } }; /** * Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>, * <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt> * properties have no affect until the current InfoBox is <tt>close</tt>d and a new one * is <tt>open</tt>ed. * @param {InfoBoxOptions} opt_opts */ InfoBox.prototype.setOptions = function (opt_opts) { if (typeof opt_opts.boxClass !== "undefined") { // Must be first this.boxClass_ = opt_opts.boxClass; this.setBoxStyle_(); } if (typeof opt_opts.boxStyle !== "undefined") { // Must be second this.boxStyle_ = opt_opts.boxStyle; this.setBoxStyle_(); } if (typeof opt_opts.content !== "undefined") { this.setContent(opt_opts.content); } if (typeof opt_opts.disableAutoPan !== "undefined") { this.disableAutoPan_ = opt_opts.disableAutoPan; } if (typeof opt_opts.maxWidth !== "undefined") { this.maxWidth_ = opt_opts.maxWidth; } if (typeof opt_opts.pixelOffset !== "undefined") { this.pixelOffset_ = opt_opts.pixelOffset; } if (typeof opt_opts.alignBottom !== "undefined") { this.alignBottom_ = opt_opts.alignBottom; } if (typeof opt_opts.position !== "undefined") { this.setPosition(opt_opts.position); } if (typeof opt_opts.zIndex !== "undefined") { this.setZIndex(opt_opts.zIndex); } if (typeof opt_opts.closeBoxMargin !== "undefined") { this.closeBoxMargin_ = opt_opts.closeBoxMargin; } if (typeof opt_opts.closeBoxURL !== "undefined") { this.closeBoxURL_ = opt_opts.closeBoxURL; } if (typeof opt_opts.infoBoxClearance !== "undefined") { this.infoBoxClearance_ = opt_opts.infoBoxClearance; } if (typeof opt_opts.isHidden !== "undefined") { this.isHidden_ = opt_opts.isHidden; } if (typeof opt_opts.visible !== "undefined") { this.isHidden_ = !opt_opts.visible; } if (typeof opt_opts.enableEventPropagation !== "undefined") { this.enableEventPropagation_ = opt_opts.enableEventPropagation; } if (this.div_) { this.draw(); } }; /** * Sets the content of the InfoBox. * The content can be plain text or an HTML DOM node. * @param {string|Node} content */ InfoBox.prototype.setContent = function (content) { this.content_ = content; if (this.div_) { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } // Odd code required to make things work with MSIE. // if (!this.fixedWidthSet_) { this.div_.style.width = ""; } if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } // Perverse code required to make things work with MSIE. // (Ensures the close box does, in fact, float to the right.) // if (!this.fixedWidthSet_) { this.div_.style.width = this.div_.offsetWidth + "px"; if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } } this.addClickHandler_(); } /** * This event is fired when the content of the InfoBox changes. * @name InfoBox#content_changed * @event */ google.maps.event.trigger(this, "content_changed"); }; /** * Sets the geographic location of the InfoBox. * @param {LatLng} latlng */ InfoBox.prototype.setPosition = function (latlng) { this.position_ = latlng; if (this.div_) { this.draw(); } /** * This event is fired when the position of the InfoBox changes. * @name InfoBox#position_changed * @event */ google.maps.event.trigger(this, "position_changed"); }; /** * Sets the zIndex style for the InfoBox. * @param {number} index */ InfoBox.prototype.setZIndex = function (index) { this.zIndex_ = index; if (this.div_) { this.div_.style.zIndex = index; } /** * This event is fired when the zIndex of the InfoBox changes. * @name InfoBox#zindex_changed * @event */ google.maps.event.trigger(this, "zindex_changed"); }; /** * Sets the visibility of the InfoBox. * @param {boolean} isVisible */ InfoBox.prototype.setVisible = function (isVisible) { this.isHidden_ = !isVisible; if (this.div_) { this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible"); } }; /** * Returns the content of the InfoBox. * @returns {string} */ InfoBox.prototype.getContent = function () { return this.content_; }; /** * Returns the geographic location of the InfoBox. * @returns {LatLng} */ InfoBox.prototype.getPosition = function () { return this.position_; }; /** * Returns the zIndex for the InfoBox. * @returns {number} */ InfoBox.prototype.getZIndex = function () { return this.zIndex_; }; /** * Returns a flag indicating whether the InfoBox is visible. * @returns {boolean} */ InfoBox.prototype.getVisible = function () { var isVisible; if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) { isVisible = false; } else { isVisible = !this.isHidden_; } return isVisible; }; /** * Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.show = function () { this.isHidden_ = false; if (this.div_) { this.div_.style.visibility = "visible"; } }; /** * Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.hide = function () { this.isHidden_ = true; if (this.div_) { this.div_.style.visibility = "hidden"; } }; /** * Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt> * (usually a <tt>google.maps.Marker</tt>) is specified, the position * of the InfoBox is set to the position of the <tt>anchor</tt>. If the * anchor is dragged to a new location, the InfoBox moves as well. * @param {Map|StreetViewPanorama} map * @param {MVCObject} [anchor] */ InfoBox.prototype.open = function (map, anchor) { var me = this; if (anchor) { this.position_ = anchor.getPosition(); this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () { me.setPosition(this.getPosition()); }); } this.setMap(map); if (this.div_) { this.panBox_(); } }; /** * Removes the InfoBox from the map. */ InfoBox.prototype.close = function () { var i; if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } if (this.eventListeners_) { for (i = 0; i < this.eventListeners_.length; i++) { google.maps.event.removeListener(this.eventListeners_[i]); } this.eventListeners_ = null; } if (this.moveListener_) { google.maps.event.removeListener(this.moveListener_); this.moveListener_ = null; } if (this.contextListener_) { google.maps.event.removeListener(this.contextListener_); this.contextListener_ = null; } this.setMap(null); }; /** * @name KeyDragZoom for V3 * @version 2.0.9 [December 17, 2012] NOT YET RELEASED * @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com] * @fileoverview This library adds a drag zoom capability to a V3 Google map. * When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code> * while dragging a box around an area of interest will zoom the map in to that area when * the mouse button is released. Optionally, a visual control can also be supplied for turning * a drag zoom operation on and off. * Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code> * <p> * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2, * it causes a context menu to appear when running on the Macintosh. * <p> * Note that if the map's container has a border around it, the border widths must be specified * in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation. * <p>NL: 2009-05-28: initial port to core API V3. * <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove). * <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position. * <br>GL: 2010-06-15: added a visual control option. */ /*! * * 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 () { /*jslint browser:true */ /*global window,google */ /* Utility functions use "var funName=function()" syntax to allow use of the */ /* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */ /** * Converts "thin", "medium", and "thick" to pixel widths * in an MSIE environment. Not called for other browsers * because getComputedStyle() returns pixel widths automatically. * @param {string} widthValue The value of the border width parameter. */ var toPixels = function (widthValue) { var px; switch (widthValue) { case "thin": px = "2px"; break; case "medium": px = "4px"; break; case "thick": px = "6px"; break; default: px = widthValue; } return px; }; /** * Get the widths of the borders of an HTML element. * * @param {Node} h The HTML element. * @return {Object} The width object {top, bottom left, right}. */ var getBorderWidths = function (h) { var computedStyle; var bw = {}; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; return bw; } } else if (document.documentElement.currentStyle) { // MSIE if (h.currentStyle) { // The current styles may not be in pixel units so try to convert (bad!) bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0; bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0; bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0; bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0; return bw; } } // Shouldn't get this far for any modern browser bw.top = parseInt(h.style["border-top-width"], 10) || 0; bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0; bw.left = parseInt(h.style["border-left-width"], 10) || 0; bw.right = parseInt(h.style["border-right-width"], 10) || 0; return bw; }; // Page scroll values for use by getMousePosition. To prevent flickering on MSIE // they are calculated only when the document actually scrolls, not every time the // mouse moves (as they would be if they were calculated inside getMousePosition). var scroll = { x: 0, y: 0 }; var getScrollValue = function (e) { scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft); scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop); }; getScrollValue(); /** * Get the position of the mouse relative to the document. * @param {Event} e The mouse event. * @return {Object} The position object {left, top}. */ var getMousePosition = function (e) { var posX = 0, posY = 0; e = e || window.event; if (typeof e.pageX !== "undefined") { posX = e.pageX; posY = e.pageY; } else if (typeof e.clientX !== "undefined") { // MSIE posX = e.clientX + scroll.x; posY = e.clientY + scroll.y; } return { left: posX, top: posY }; }; /** * Get the position of an HTML element relative to the document. * @param {Node} h The HTML element. * @return {Object} The position object {left, top}. */ var getElementPosition = function (h) { var posX = h.offsetLeft; var posY = h.offsetTop; var parent = h.offsetParent; // Add offsets for all ancestors in the hierarchy while (parent !== null) { // Adjust for scrolling elements which may affect the map position. // // See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific // // "...make sure that every element [on a Web page] with an overflow // of anything other than visible also has a position style set to // something other than the default static..." if (parent !== document.body && parent !== document.documentElement) { posX -= parent.scrollLeft; posY -= parent.scrollTop; } // See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5 // Example: http://notebook.kulchenko.com/maps/gridmove var m = parent; // This is the "normal" way to get offset information: var moffx = m.offsetLeft; var moffy = m.offsetTop; // This covers those cases where a transform is used: if (!moffx && !moffy && window.getComputedStyle) { var matrix = document.defaultView.getComputedStyle(m, null).MozTransform || document.defaultView.getComputedStyle(m, null).WebkitTransform; if (matrix) { if (typeof matrix === "string") { var parms = matrix.split(","); moffx += parseInt(parms[4], 10) || 0; moffy += parseInt(parms[5], 10) || 0; } } } posX += moffx; posY += moffy; parent = parent.offsetParent; } return { left: posX, top: posY }; }; /** * Set the properties of an object to those from another object. * @param {Object} obj The target object. * @param {Object} vals The source object. */ var setVals = function (obj, vals) { if (obj && vals) { for (var x in vals) { if (vals.hasOwnProperty(x)) { obj[x] = vals[x]; } } } return obj; }; /** * Set the opacity. If op is not passed in, this function just performs an MSIE fix. * @param {Node} h The HTML element. * @param {number} op The opacity value (0-1). */ var setOpacity = function (h, op) { if (typeof op !== "undefined") { h.style.opacity = op; } if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") { h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")"; } }; /** * @name KeyDragZoomOptions * @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>. * @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>. * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2, * it causes a context menu to appear when running on the Macintosh. Also note that the * <code>alt</code> hot key refers to the Option key on a Macintosh. * @property {Object} [boxStyle={border: "4px solid #736AFF"}] * An object literal defining the CSS styles of the zoom box. * Border widths must be specified in pixel units (or as thin, medium, or thick). * @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}] * An object literal defining the CSS styles of the veil pane which covers the map when a drag * zoom is activated. The previous name for this property was <code>paneStyle</code> but the use * of this name is now deprecated. * @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is * selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area * selection tool. * @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used. * @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual * control. To prevent the visual control from being printed, set this property to the name of * a class, defined inside a <code>@media print</code> rule, which sets the CSS * <code>display</code> style to <code>none</code>. * @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP] * The position of the visual control. * @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values * provided by this property are the offsets (in pixels) from the location at which the control * would normally be drawn to the desired drawing location. * @property {number} [visualPositionIndex=null] The index of the visual control. * The index is for controlling the placement of the control relative to other controls at the * position given by <code>visualPosition</code>; controls with a lower index are placed first. * Use a negative value to place the control <i>before</i> any default controls. No index is * generally required. * @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"] * The URL of the sprite image used for showing the visual control in the on, off, and hot * (i.e., when the mouse is over the control) states. The three images within the sprite must * be the same size and arranged in on-hot-off order in a single row with no spaces between images. * @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by * this property are the size (in pixels) of each of the images within <code>visualSprite</code>. * @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}] * An object literal defining the help tips that appear when * the mouse moves over the visual control. The <code>off</code> property is the tip to be shown * when the control is off and the <code>on</code> property is the tip to be shown when the * control is on. */ /** * @name DragZoom * @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key * or by turning on the visual control. * This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly. * Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners. * @param {Map} map The map to which the DragZoom object is to be attached. * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters. */ function DragZoom(map, opt_zoomOpts) { var me = this; var ov = new google.maps.OverlayView(); ov.onAdd = function () { me.init_(map, opt_zoomOpts); }; ov.draw = function () { }; ov.onRemove = function () { }; ov.setMap(map); this.prjov_ = ov; } /** * Initialize the tool. * @param {Map} map The map to which the DragZoom object is to be attached. * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters. */ DragZoom.prototype.init_ = function (map, opt_zoomOpts) { var i; var me = this; this.map_ = map; opt_zoomOpts = opt_zoomOpts || {}; this.key_ = opt_zoomOpts.key || "shift"; this.key_ = this.key_.toLowerCase(); this.borderWidths_ = getBorderWidths(this.map_.getDiv()); this.veilDiv_ = []; for (i = 0; i < 4; i++) { this.veilDiv_[i] = document.createElement("div"); // Prevents selection of other elements on the webpage // when a drag zoom operation is in progress: this.veilDiv_[i].onselectstart = function () { return false; }; // Apply default style values for the veil: setVals(this.veilDiv_[i].style, { backgroundColor: "gray", opacity: 0.25, cursor: "crosshair" }); // Apply style values specified in veilStyle parameter: setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle" setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle" // Apply mandatory style values: setVals(this.veilDiv_[i].style, { position: "absolute", overflow: "hidden", display: "none" }); // Workaround for Firefox Shift-Click problem: if (this.key_ === "shift") { this.veilDiv_[i].style.MozUserSelect = "none"; } setOpacity(this.veilDiv_[i]); // An IE fix: If the background is transparent it cannot capture mousedown // events, so if it is, change the background to white with 0 opacity. if (this.veilDiv_[i].style.backgroundColor === "transparent") { this.veilDiv_[i].style.backgroundColor = "white"; setOpacity(this.veilDiv_[i], 0); } this.map_.getDiv().appendChild(this.veilDiv_[i]); } this.noZoom_ = opt_zoomOpts.noZoom || false; this.visualEnabled_ = opt_zoomOpts.visualEnabled || false; this.visualClass_ = opt_zoomOpts.visualClass || ""; this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP; this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0); this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null; this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"; this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20); this.visualTips_ = opt_zoomOpts.visualTips || {}; this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode"; this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode"; this.boxDiv_ = document.createElement("div"); // Apply default style values for the zoom box: setVals(this.boxDiv_.style, { border: "4px solid #736AFF" }); // Apply style values specified in boxStyle parameter: setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle); // Apply mandatory style values: setVals(this.boxDiv_.style, { position: "absolute", display: "none" }); setOpacity(this.boxDiv_); this.map_.getDiv().appendChild(this.boxDiv_); this.boxBorderWidths_ = getBorderWidths(this.boxDiv_); this.listeners_ = [ google.maps.event.addDomListener(document, "keydown", function (e) { me.onKeyDown_(e); }), google.maps.event.addDomListener(document, "keyup", function (e) { me.onKeyUp_(e); }), google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(document, "mousedown", function (e) { me.onMouseDownDocument_(e); }), google.maps.event.addDomListener(document, "mousemove", function (e) { me.onMouseMove_(e); }), google.maps.event.addDomListener(document, "mouseup", function (e) { me.onMouseUp_(e); }), google.maps.event.addDomListener(window, "scroll", getScrollValue) ]; this.hotKeyDown_ = false; this.mouseDown_ = false; this.dragging_ = false; this.startPt_ = null; this.endPt_ = null; this.mapWidth_ = null; this.mapHeight_ = null; this.mousePosn_ = null; this.mapPosn_ = null; if (this.visualEnabled_) { this.buttonDiv_ = this.initControl_(this.visualPositionOffset_); if (this.visualPositionIndex_ !== null) { this.buttonDiv_.index = this.visualPositionIndex_; } this.map_.controls[this.visualPosition_].push(this.buttonDiv_); this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1; } }; /** * Initializes the visual control and returns its DOM element. * @param {Size} offset The offset of the control from its normal position. * @return {Node} The DOM element containing the visual control. */ DragZoom.prototype.initControl_ = function (offset) { var control; var image; var me = this; control = document.createElement("div"); control.className = this.visualClass_; control.style.position = "relative"; control.style.overflow = "hidden"; control.style.height = this.visualSize_.height + "px"; control.style.width = this.visualSize_.width + "px"; control.title = this.visualTips_.off; image = document.createElement("img"); image.src = this.visualSprite_; image.style.position = "absolute"; image.style.left = -(this.visualSize_.width * 2) + "px"; image.style.top = 0 + "px"; control.appendChild(image); control.onclick = function (e) { me.hotKeyDown_ = !me.hotKeyDown_; if (me.hotKeyDown_) { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px"; me.buttonDiv_.title = me.visualTips_.on; me.activatedByControl_ = true; google.maps.event.trigger(me, "activate"); } else { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px"; me.buttonDiv_.title = me.visualTips_.off; google.maps.event.trigger(me, "deactivate"); } me.onMouseMove_(e); // Updates the veil }; control.onmouseover = function () { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px"; }; control.onmouseout = function () { if (me.hotKeyDown_) { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px"; me.buttonDiv_.title = me.visualTips_.on; } else { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px"; me.buttonDiv_.title = me.visualTips_.off; } }; control.ondragstart = function () { return false; }; setVals(control.style, { cursor: "pointer", marginTop: offset.height + "px", marginLeft: offset.width + "px" }); return control; }; /** * Returns <code>true</code> if the hot key is being pressed when an event occurs. * @param {Event} e The keyboard event. * @return {boolean} Flag indicating whether the hot key is down. */ DragZoom.prototype.isHotKeyDown_ = function (e) { var isHot; e = e || window.event; isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl"); if (!isHot) { // Need to look at keyCode for Opera because it // doesn't set the shiftKey, altKey, ctrlKey properties // unless a non-modifier event is being reported. // // See http://cross-browser.com/x/examples/shift_mode.php // Also see http://unixpapa.com/js/key.html switch (e.keyCode) { case 16: if (this.key_ === "shift") { isHot = true; } break; case 17: if (this.key_ === "ctrl") { isHot = true; } break; case 18: if (this.key_ === "alt") { isHot = true; } break; } } return isHot; }; /** * Returns <code>true</code> if the mouse is on top of the map div. * The position is captured in onMouseMove_. * @return {boolean} */ DragZoom.prototype.isMouseOnMap_ = function () { var mousePosn = this.mousePosn_; if (mousePosn) { var mapPosn = this.mapPosn_; var mapDiv = this.map_.getDiv(); return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) && mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight); } else { // if user never moved mouse return false; } }; /** * Show the veil if the hot key is down and the mouse is over the map, * otherwise hide the veil. */ DragZoom.prototype.setVeilVisibility_ = function () { var i; if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) { var mapDiv = this.map_.getDiv(); this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right); this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom); if (this.activatedByControl_) { // Veil covers entire map (except control) var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width; var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height; var width = this.visualSize_.width; var height = this.visualSize_.height; // Left veil rectangle: this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.width = left + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; // Right veil rectangle: this.veilDiv_[1].style.top = "0px"; this.veilDiv_[1].style.left = (left + width) + "px"; this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px"; this.veilDiv_[1].style.height = this.mapHeight_ + "px"; // Top veil rectangle: this.veilDiv_[2].style.top = "0px"; this.veilDiv_[2].style.left = left + "px"; this.veilDiv_[2].style.width = width + "px"; this.veilDiv_[2].style.height = top + "px"; // Bottom veil rectangle: this.veilDiv_[3].style.top = (top + height) + "px"; this.veilDiv_[3].style.left = left + "px"; this.veilDiv_[3].style.width = width + "px"; this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px"; for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "block"; } } else { this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.width = this.mapWidth_ + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; for (i = 1; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.width = "0px"; this.veilDiv_[i].style.height = "0px"; } for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "block"; } } } else { for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "none"; } } }; /** * Handle key down. Show the veil if the hot key has been pressed. * @param {Event} e The keyboard event. */ DragZoom.prototype.onKeyDown_ = function (e) { if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.hotKeyDown_ = true; this.activatedByControl_ = false; this.setVeilVisibility_(); /** * This event is fired when the hot key is pressed. * @name DragZoom#activate * @event */ google.maps.event.trigger(this, "activate"); } }; /** * Get the <code>google.maps.Point</code> of the mouse position. * @param {Event} e The mouse event. * @return {Point} The mouse position. */ DragZoom.prototype.getMousePoint_ = function (e) { var mousePosn = getMousePosition(e); var p = new google.maps.Point(); p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left; p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top; p.x = Math.min(p.x, this.mapWidth_); p.y = Math.min(p.y, this.mapHeight_); p.x = Math.max(p.x, 0); p.y = Math.max(p.y, 0); return p; }; /** * Handle mouse down. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseDown_ = function (e) { if (this.map_ && this.hotKeyDown_) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.dragging_ = true; this.startPt_ = this.endPt_ = this.getMousePoint_(e); this.boxDiv_.style.width = this.boxDiv_.style.height = "0px"; var prj = this.prjov_.getProjection(); var latlng = prj.fromContainerPixelToLatLng(this.startPt_); /** * This event is fired when the drag operation begins. * The parameter passed is the geographic position of the starting point. * @name DragZoom#dragstart * @param {LatLng} latlng The geographic position of the starting point. * @event */ google.maps.event.trigger(this, "dragstart", latlng); } }; /** * Handle mouse down at the document level. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseDownDocument_ = function (e) { this.mouseDown_ = true; }; /** * Handle mouse move. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseMove_ = function (e) { this.mousePosn_ = getMousePosition(e); if (this.dragging_) { this.endPt_ = this.getMousePoint_(e); var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); // For benefit of MSIE 7/8 ensure following values are not negative: var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)); var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)); // Left veil rectangle: this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.width = left + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; // Right veil rectangle: this.veilDiv_[1].style.top = "0px"; this.veilDiv_[1].style.left = (left + width) + "px"; this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px"; this.veilDiv_[1].style.height = this.mapHeight_ + "px"; // Top veil rectangle: this.veilDiv_[2].style.top = "0px"; this.veilDiv_[2].style.left = left + "px"; this.veilDiv_[2].style.width = width + "px"; this.veilDiv_[2].style.height = top + "px"; // Bottom veil rectangle: this.veilDiv_[3].style.top = (top + height) + "px"; this.veilDiv_[3].style.left = left + "px"; this.veilDiv_[3].style.width = width + "px"; this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px"; // Selection rectangle: this.boxDiv_.style.top = top + "px"; this.boxDiv_.style.left = left + "px"; this.boxDiv_.style.width = boxWidth + "px"; this.boxDiv_.style.height = boxHeight + "px"; this.boxDiv_.style.display = "block"; /** * This event is fired repeatedly while the user drags a box across the area of interest. * The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code> * (for performance reasons), relative to the map container. Also passed is the projection object * so that the event listener, if necessary, can convert the pixel positions to geographic * coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>. * @name DragZoom#drag * @param {Point} southwestPixel The southwest point of the selection area. * @param {Point} northeastPixel The northeast point of the selection area. * @param {MapCanvasProjection} prj The projection object. * @event */ google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection()); } else if (!this.mouseDown_) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.setVeilVisibility_(); } }; /** * Handle mouse up. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseUp_ = function (e) { var z; var me = this; this.mouseDown_ = false; if (this.dragging_) { if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) { this.onKeyUp_(e); // Cancel event return; } var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); // Google Maps API bug: setCenter() doesn't work as expected if the map has a // border on the left or top. The code here includes a workaround for this problem. var kGoogleCenteringBug = true; if (kGoogleCenteringBug) { left += this.borderWidths_.left; top += this.borderWidths_.top; } var prj = this.prjov_.getProjection(); var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height)); var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top)); var bnds = new google.maps.LatLngBounds(sw, ne); if (this.noZoom_) { this.boxDiv_.style.display = "none"; } else { // Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens. z = this.map_.getZoom(); this.map_.fitBounds(bnds); if (this.map_.getZoom() < z) { this.map_.setZoom(z); } // Redraw box after zoom: var swPt = prj.fromLatLngToContainerPixel(sw); var nePt = prj.fromLatLngToContainerPixel(ne); if (kGoogleCenteringBug) { swPt.x -= this.borderWidths_.left; swPt.y -= this.borderWidths_.top; nePt.x -= this.borderWidths_.left; nePt.y -= this.borderWidths_.top; } this.boxDiv_.style.left = swPt.x + "px"; this.boxDiv_.style.top = nePt.y + "px"; this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px"; this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px"; // Hide box asynchronously after 1 second: setTimeout(function () { me.boxDiv_.style.display = "none"; }, 1000); } this.dragging_ = false; this.onMouseMove_(e); // Updates the veil /** * This event is fired when the drag operation ends. * The parameter passed is the geographic bounds of the selected area. * Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends. * @name DragZoom#dragend * @param {LatLngBounds} bnds The geographic bounds of the selected area. * @event */ google.maps.event.trigger(this, "dragend", bnds); // if the hot key isn't down, the drag zoom must have been activated by turning // on the visual control. In this case, finish up by simulating a key up event. if (!this.isHotKeyDown_(e)) { this.onKeyUp_(e); } } }; /** * Handle key up. * @param {Event} e The keyboard event. */ DragZoom.prototype.onKeyUp_ = function (e) { var i; var left, top, width, height, prj, sw, ne; var bnds = null; if (this.map_ && this.hotKeyDown_) { this.hotKeyDown_ = false; if (this.dragging_) { this.boxDiv_.style.display = "none"; this.dragging_ = false; // Calculate the bounds when drag zoom was cancelled left = Math.min(this.startPt_.x, this.endPt_.x); top = Math.min(this.startPt_.y, this.endPt_.y); width = Math.abs(this.startPt_.x - this.endPt_.x); height = Math.abs(this.startPt_.y - this.endPt_.y); prj = this.prjov_.getProjection(); sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height)); ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top)); bnds = new google.maps.LatLngBounds(sw, ne); } for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "none"; } if (this.visualEnabled_) { this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px"; this.buttonDiv_.title = this.visualTips_.off; this.buttonDiv_.style.display = ""; } /** * This event is fired when the hot key is released. * The parameter passed is the geographic bounds of the selected area immediately * before the hot key was released. * @name DragZoom#deactivate * @param {LatLngBounds} bnds The geographic bounds of the selected area immediately * before the hot key was released. * @event */ google.maps.event.trigger(this, "deactivate", bnds); } }; /** * @name google.maps.Map * @class These are new methods added to the Google Maps JavaScript API V3's * <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a> * class. */ /** * Enables drag zoom. The user can zoom to an area of interest by holding down the hot key * <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning * on the visual control then dragging a box around the area. * @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters. */ google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) { this.dragZoom_ = new DragZoom(this, opt_zoomOpts); }; /** * Disables drag zoom. */ google.maps.Map.prototype.disableKeyDragZoom = function () { var i; var d = this.dragZoom_; if (d) { for (i = 0; i < d.listeners_.length; ++i) { google.maps.event.removeListener(d.listeners_[i]); } this.getDiv().removeChild(d.boxDiv_); for (i = 0; i < d.veilDiv_.length; i++) { this.getDiv().removeChild(d.veilDiv_[i]); } if (d.visualEnabled_) { // Remove the custom control: this.controls[d.visualPosition_].removeAt(d.controlIndex_); } d.prjov_.setMap(null); this.dragZoom_ = null; } }; /** * Returns <code>true</code> if the drag zoom feature has been enabled. * @return {boolean} */ google.maps.Map.prototype.keyDragZoomEnabled = function () { return this.dragZoom_ !== null; }; /** * Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called. * With this object you can use <code>google.maps.event.addListener</code> to attach event listeners * for the "activate", "deactivate", "dragstart", "drag", and "dragend" events. * @return {DragZoom} */ google.maps.Map.prototype.getDragZoomObject = function () { return this.dragZoom_; }; })(); /** * @name MarkerClustererPlus for Google Maps V3 * @version 2.1.1 [November 4, 2013] * @author Gary Little * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of markers. * <p> * This is an enhanced V3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/" * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little. * <p> * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>, * and <code>calculator</code> properties as well as support for four more events. It also allows * greater control over the styling of the text that appears on the cluster marker. The * documentation has been significantly improved and the overall code has been simplified and * polished. Very large numbers of markers can now be managed without causing Javascript timeout * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been * deprecated. The new name is <code>click</code>, so please change your application code now. */ /** * 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. */ /** * @name ClusterIconStyle * @class This class represents the object for values in the <code>styles</code> array passed * to the {@link MarkerClusterer} constructor. The element in this array that is used to * style the cluster icon is determined by calling the <code>calculator</code> function. * * @property {string} url The URL of the cluster icon image file. Required. * @property {number} height The display height (in pixels) of the cluster icon. Required. * @property {number} width The display width (in pixels) of the cluster icon. Required. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code> * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code> * increases to the right of center. The default is <code>[0, 0]</code>. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the * spot on the cluster icon that is to be aligned with the cluster position. The format is * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default * anchor position is the center of the cluster icon. * @property {string} [textColor="black"] The color of the label text shown on the * cluster icon. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the * cluster icon. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code> * property for the label text shown on the cluster icon. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code> * property for the label text shown on the cluster icon. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code> * property for the label text shown on the cluster icon. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code> * property for the label text shown on the cluster icon. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code> * (the same format as for the CSS <code>background-position</code> property). You must set * this property appropriately when the image defined by <code>url</code> represents a sprite * containing multiple images. Note that the position <i>must</i> be specified in px units. */ /** * @name ClusterIconInfo * @class This class is an object containing general information about a cluster icon. This is * the object that a <code>calculator</code> function returns. * * @property {string} text The text of the label to be shown on the cluster icon. * @property {number} index The index plus 1 of the element in the <code>styles</code> * array to be used to style the cluster icon. * @property {string} title The tooltip to display when the mouse moves over the cluster icon. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the * value of the <code>title</code> property passed to the MarkerClusterer. */ /** * A cluster icon. * * @constructor * @extends google.maps.OverlayView * @param {Cluster} cluster The cluster with which the icon is to be associated. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. * @private */ function ClusterIcon(cluster, styles) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.cluster_ = cluster; this.className_ = cluster.getMarkerClusterer().getClusterClass(); this.styles_ = styles; this.center_ = null; this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(cluster.getMap()); // Note: this causes onAdd to be called } /** * Adds the icon to the DOM. */ ClusterIcon.prototype.onAdd = function () { var cClusterIcon = this; var cMouseDownInCluster; var cDraggingMapByCluster; this.div_ = document.createElement("div"); this.div_.className = this.className_; if (this.visible_) { this.show(); } this.getPanes().overlayMouseTarget.appendChild(this.div_); // Fix for Issue 157 this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () { cDraggingMapByCluster = cMouseDownInCluster; }); google.maps.event.addDomListener(this.div_, "mousedown", function () { cMouseDownInCluster = true; cDraggingMapByCluster = false; }); google.maps.event.addDomListener(this.div_, "click", function (e) { cMouseDownInCluster = false; if (!cDraggingMapByCluster) { var theBounds; var mz; var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when a cluster marker is clicked. * @name MarkerClusterer#click * @param {Cluster} c The cluster that was clicked. * @event */ google.maps.event.trigger(mc, "click", cClusterIcon.cluster_); google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name // The default click handler follows. Disable it by setting // the zoomOnClick property to false. if (mc.getZoomOnClick()) { // Zoom into the cluster. mz = mc.getMaxZoom(); theBounds = cClusterIcon.cluster_.getBounds(); mc.getMap().fitBounds(theBounds); // There is a fix for Issue 170 here: setTimeout(function () { mc.getMap().fitBounds(theBounds); // Don't zoom beyond the max zoom level if (mz !== null && (mc.getMap().getZoom() > mz)) { mc.getMap().setZoom(mz + 1); } }, 100); } // Prevent event propagation to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }); google.maps.event.addDomListener(this.div_, "mouseover", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves over a cluster marker. * @name MarkerClusterer#mouseover * @param {Cluster} c The cluster that the mouse moved over. * @event */ google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_); }); google.maps.event.addDomListener(this.div_, "mouseout", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves out of a cluster marker. * @name MarkerClusterer#mouseout * @param {Cluster} c The cluster that the mouse moved out of. * @event */ google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_); }); }; /** * Removes the icon from the DOM. */ ClusterIcon.prototype.onRemove = function () { if (this.div_ && this.div_.parentNode) { this.hide(); google.maps.event.removeListener(this.boundsChangedListener_); google.maps.event.clearInstanceListeners(this.div_); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the icon. */ ClusterIcon.prototype.draw = function () { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + "px"; this.div_.style.left = pos.x + "px"; } }; /** * Hides the icon. */ ClusterIcon.prototype.hide = function () { if (this.div_) { this.div_.style.display = "none"; } this.visible_ = false; }; /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; /** * Sets the icon styles to the appropriate element in the styles array. * * @param {ClusterIconInfo} sums The icon label text and styles index. */ ClusterIcon.prototype.useStyle = function (sums) { this.sums_ = sums; var index = Math.max(0, sums.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style.url; this.height_ = style.height; this.width_ = style.width; this.anchorText_ = style.anchorText || [0, 0]; this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)]; this.textColor_ = style.textColor || "black"; this.textSize_ = style.textSize || 11; this.textDecoration_ = style.textDecoration || "none"; this.fontWeight_ = style.fontWeight || "bold"; this.fontStyle_ = style.fontStyle || "normal"; this.fontFamily_ = style.fontFamily || "Arial,sans-serif"; this.backgroundPosition_ = style.backgroundPosition || "0 0"; }; /** * Sets the position at which to center the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function (center) { this.center_ = center; }; /** * Creates the cssText style parameter based on the position of the icon. * * @param {google.maps.Point} pos The position of the icon. * @return {string} The CSS style text. */ ClusterIcon.prototype.createCss = function (pos) { var style = []; style.push("cursor: pointer;"); style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;"); style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;"); return style.join(""); }; /** * Returns the position at which to place the DIV depending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. */ ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= this.anchorIcon_[1]; pos.y -= this.anchorIcon_[0]; pos.x = parseInt(pos.x, 10); pos.y = parseInt(pos.y, 10); return pos; }; /** * Creates a single cluster that manages a group of proximate markers. * Used internally, do not call this constructor directly. * @constructor * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this * cluster is associated. */ function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); } /** * Returns the number of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {number} The number of markers in the cluster. */ Cluster.prototype.getSize = function () { return this.markers_.length; }; /** * Returns the array of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {Array} The array of markers in the cluster. */ Cluster.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the center of the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {google.maps.LatLng} The center of the cluster. */ Cluster.prototype.getCenter = function () { return this.center_; }; /** * Returns the map with which the cluster is associated. * * @return {google.maps.Map} The map. * @ignore */ Cluster.prototype.getMap = function () { return this.map_; }; /** * Returns the <code>MarkerClusterer</code> object with which the cluster is associated. * * @return {MarkerClusterer} The associated marker clusterer. * @ignore */ Cluster.prototype.getMarkerClusterer = function () { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ Cluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ Cluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = []; delete this.markers_; }; /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ Cluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. for (i = 0; i < mCount; i++) { this.markers_[i].setMap(null); } } else { marker.setMap(null); } this.updateIcon_(); return true; }; /** * Determines if a marker lies within the cluster's bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. * @ignore */ Cluster.prototype.isMarkerInClusterBounds = function (marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Calculates the extended bounds of the cluster with the grid. */ Cluster.prototype.calculateBounds_ = function () { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Updates the cluster icon. */ Cluster.prototype.updateIcon_ = function () { var mCount = this.markers_.length; var mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { this.clusterIcon_.hide(); return; } if (mCount < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.useStyle(sums); this.clusterIcon_.show(); }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) { var i; if (this.markers_.indexOf) { return this.markers_.indexOf(marker) !== -1; } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { return true; } } } return false; }; /** * @name MarkerClustererOptions * @class This class represents the optional parameter passed to * the {@link MarkerClusterer} constructor. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or * <code>null</code> if clustering is to be enabled at all zoom levels. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is * clicked. You may want to set this to <code>false</code> if you have installed a handler * for the <code>click</code> event and it deals with zooming on its own. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be * the average position of all markers in the cluster. If set to <code>false</code>, the * cluster marker is positioned at the location of the first marker added to the cluster. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster * before the markers are hidden and a cluster marker appears. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You * may want to set this to <code>true</code> to ensure that hidden markers are not included * in the marker count that appears on a cluster marker (this count is the value of the * <code>text</code> property of the result returned by the default <code>calculator</code>). * If set to <code>true</code> and you change the visibility of a marker being clustered, be * sure to also call <code>MarkerClusterer.repaint()</code>. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a * different tooltip for each cluster marker.) * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine * the text to be displayed on a cluster marker and the index indicating which style to use * for the cluster marker. The input parameters for the function are (1) the array of markers * represented by a cluster marker and (2) the number of cluster icon styles. It returns a * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a * <code>text</code> property which is the number of markers in the cluster and an * <code>index</code> property which is one higher than the lowest integer such that * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles * array, whichever is less. The <code>styles</code> array element used has an index of * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code> * for a cluster icon representing 125 markers so the element used in the <code>styles</code> * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code> * property that contains the text of the tooltip to be used for the cluster marker. If * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code> * property for the MarkerClusterer. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles * for the cluster markers. Use this class to define CSS styles that are not set up by the code * that processes the <code>styles</code> array. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles * of the cluster markers to be used. The element to be used to style a given cluster marker * is determined by the function defined by the <code>calculator</code> property. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived * from the values for <code>imagePath</code>, <code>imageExtension</code>, and * <code>imageSizes</code>. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that * have sizes that are some multiple (typically double) of their actual display size. Icons such * as these look better when viewed on high-resolution monitors such as Apple's Retina displays. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the * number of markers to be processed in a single batch when using a browser other than * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead). * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is * being used, markers are processed in several batches with a small delay inserted between * each batch in an attempt to avoid Javascript timeout errors. Set this property to the * number of markers to be processed in a single batch; select as high a number as you can * without causing a timeout error in the browser. This number might need to be as low as 100 * if 15,000 markers are being managed, for example. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH] * The full URL of the root name of the group of image files to use for cluster icons. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code> * where n is the image file number (1, 2, etc.). * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION] * The extension name for the cluster icon image files (e.g., <code>"png"</code> or * <code>"jpg"</code>). * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES] * An array of numbers containing the widths of the group of * <code>imagePath</code>n.<code>imageExtension</code> image files. * (The images are assumed to be square.) */ /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. * @constructor * @extends google.maps.OverlayView * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster. * @param {MarkerClustererOptions} [opt_options] The optional parameters. */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); opt_markers = opt_markers || []; opt_options = opt_options || {}; this.markers_ = []; this.clusters_ = []; this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; this.gridSize_ = opt_options.gridSize || 60; this.minClusterSize_ = opt_options.minimumClusterSize || 2; this.maxZoom_ = opt_options.maxZoom || null; this.styles_ = opt_options.styles || []; this.title_ = opt_options.title || ""; this.zoomOnClick_ = true; if (opt_options.zoomOnClick !== undefined) { this.zoomOnClick_ = opt_options.zoomOnClick; } this.averageCenter_ = false; if (opt_options.averageCenter !== undefined) { this.averageCenter_ = opt_options.averageCenter; } this.ignoreHidden_ = false; if (opt_options.ignoreHidden !== undefined) { this.ignoreHidden_ = opt_options.ignoreHidden; } this.enableRetinaIcons_ = false; if (opt_options.enableRetinaIcons !== undefined) { this.enableRetinaIcons_ = opt_options.enableRetinaIcons; } this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH; this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION; this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES; this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR; this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE; this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE; this.clusterClass_ = opt_options.clusterClass || "cluster"; if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize_ = this.batchSizeIE_; } this.setupStyles_(); this.addMarkers(opt_markers, true); this.setMap(map); // Note: this causes onAdd to be called } /** * Implementation of the onAdd interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function () { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }), google.maps.event.addListener(this.getMap(), "idle", function () { cMarkerClusterer.redraw_(); }) ]; }; /** * Implementation of the onRemove interface method. * Removes map event listeners and all cluster icons from the DOM. * All managed markers are also put back on the map. * @ignore */ MarkerClusterer.prototype.onRemove = function () { var i; // Put all the managed markers back on the map: for (i = 0; i < this.markers_.length; i++) { if (this.markers_[i].getMap() !== this.activeMap_) { this.markers_[i].setMap(this.activeMap_); } } // Remove all clusters: for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Remove map event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; }; /** * Implementation of the draw interface method. * @ignore */ MarkerClusterer.prototype.draw = function () {}; /** * Sets up the styles object. */ MarkerClusterer.prototype.setupStyles_ = function () { var i, size; if (this.styles_.length > 0) { return; } for (i = 0; i < this.imageSizes_.length; i++) { size = this.imageSizes_[i]; this.styles_.push({ url: this.imagePath_ + (i + 1) + "." + this.imageExtension_, height: size, width: size }); } }; /** * Fits the map to the bounds of the markers managed by the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function () { var i; var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } this.getMap().fitBounds(bounds); }; /** * Returns the value of the <code>gridSize</code> property. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function () { return this.gridSize_; }; /** * Sets the value of the <code>gridSize</code> property. * * @param {number} gridSize The grid size. */ MarkerClusterer.prototype.setGridSize = function (gridSize) { this.gridSize_ = gridSize; }; /** * Returns the value of the <code>minimumClusterSize</code> property. * * @return {number} The minimum cluster size. */ MarkerClusterer.prototype.getMinimumClusterSize = function () { return this.minClusterSize_; }; /** * Sets the value of the <code>minimumClusterSize</code> property. * * @param {number} minimumClusterSize The minimum cluster size. */ MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) { this.minClusterSize_ = minimumClusterSize; }; /** * Returns the value of the <code>maxZoom</code> property. * * @return {number} The maximum zoom level. */ MarkerClusterer.prototype.getMaxZoom = function () { return this.maxZoom_; }; /** * Sets the value of the <code>maxZoom</code> property. * * @param {number} maxZoom The maximum zoom level. */ MarkerClusterer.prototype.setMaxZoom = function (maxZoom) { this.maxZoom_ = maxZoom; }; /** * Returns the value of the <code>styles</code> property. * * @return {Array} The array of styles defining the cluster markers to be used. */ MarkerClusterer.prototype.getStyles = function () { return this.styles_; }; /** * Sets the value of the <code>styles</code> property. * * @param {Array.<ClusterIconStyle>} styles The array of styles to use. */ MarkerClusterer.prototype.setStyles = function (styles) { this.styles_ = styles; }; /** * Returns the value of the <code>title</code> property. * * @return {string} The content of the title text. */ MarkerClusterer.prototype.getTitle = function () { return this.title_; }; /** * Sets the value of the <code>title</code> property. * * @param {string} title The value of the title property. */ MarkerClusterer.prototype.setTitle = function (title) { this.title_ = title; }; /** * Returns the value of the <code>zoomOnClick</code> property. * * @return {boolean} True if zoomOnClick property is set. */ MarkerClusterer.prototype.getZoomOnClick = function () { return this.zoomOnClick_; }; /** * Sets the value of the <code>zoomOnClick</code> property. * * @param {boolean} zoomOnClick The value of the zoomOnClick property. */ MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) { this.zoomOnClick_ = zoomOnClick; }; /** * Returns the value of the <code>averageCenter</code> property. * * @return {boolean} True if averageCenter property is set. */ MarkerClusterer.prototype.getAverageCenter = function () { return this.averageCenter_; }; /** * Sets the value of the <code>averageCenter</code> property. * * @param {boolean} averageCenter The value of the averageCenter property. */ MarkerClusterer.prototype.setAverageCenter = function (averageCenter) { this.averageCenter_ = averageCenter; }; /** * Returns the value of the <code>ignoreHidden</code> property. * * @return {boolean} True if ignoreHidden property is set. */ MarkerClusterer.prototype.getIgnoreHidden = function () { return this.ignoreHidden_; }; /** * Sets the value of the <code>ignoreHidden</code> property. * * @param {boolean} ignoreHidden The value of the ignoreHidden property. */ MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) { this.ignoreHidden_ = ignoreHidden; }; /** * Returns the value of the <code>enableRetinaIcons</code> property. * * @return {boolean} True if enableRetinaIcons property is set. */ MarkerClusterer.prototype.getEnableRetinaIcons = function () { return this.enableRetinaIcons_; }; /** * Sets the value of the <code>enableRetinaIcons</code> property. * * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property. */ MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) { this.enableRetinaIcons_ = enableRetinaIcons; }; /** * Returns the value of the <code>imageExtension</code> property. * * @return {string} The value of the imageExtension property. */ MarkerClusterer.prototype.getImageExtension = function () { return this.imageExtension_; }; /** * Sets the value of the <code>imageExtension</code> property. * * @param {string} imageExtension The value of the imageExtension property. */ MarkerClusterer.prototype.setImageExtension = function (imageExtension) { this.imageExtension_ = imageExtension; }; /** * Returns the value of the <code>imagePath</code> property. * * @return {string} The value of the imagePath property. */ MarkerClusterer.prototype.getImagePath = function () { return this.imagePath_; }; /** * Sets the value of the <code>imagePath</code> property. * * @param {string} imagePath The value of the imagePath property. */ MarkerClusterer.prototype.setImagePath = function (imagePath) { this.imagePath_ = imagePath; }; /** * Returns the value of the <code>imageSizes</code> property. * * @return {Array} The value of the imageSizes property. */ MarkerClusterer.prototype.getImageSizes = function () { return this.imageSizes_; }; /** * Sets the value of the <code>imageSizes</code> property. * * @param {Array} imageSizes The value of the imageSizes property. */ MarkerClusterer.prototype.setImageSizes = function (imageSizes) { this.imageSizes_ = imageSizes; }; /** * Returns the value of the <code>calculator</code> property. * * @return {function} the value of the calculator property. */ MarkerClusterer.prototype.getCalculator = function () { return this.calculator_; }; /** * Sets the value of the <code>calculator</code> property. * * @param {function(Array.<google.maps.Marker>, number)} calculator The value * of the calculator property. */ MarkerClusterer.prototype.setCalculator = function (calculator) { this.calculator_ = calculator; }; /** * Returns the value of the <code>batchSizeIE</code> property. * * @return {number} the value of the batchSizeIE property. */ MarkerClusterer.prototype.getBatchSizeIE = function () { return this.batchSizeIE_; }; /** * Sets the value of the <code>batchSizeIE</code> property. * * @param {number} batchSizeIE The value of the batchSizeIE property. */ MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) { this.batchSizeIE_ = batchSizeIE; }; /** * Returns the value of the <code>clusterClass</code> property. * * @return {string} the value of the clusterClass property. */ MarkerClusterer.prototype.getClusterClass = function () { return this.clusterClass_; }; /** * Sets the value of the <code>clusterClass</code> property. * * @param {string} clusterClass The value of the clusterClass property. */ MarkerClusterer.prototype.setClusterClass = function (clusterClass) { this.clusterClass_ = clusterClass; }; /** * Returns the array of markers managed by the clusterer. * * @return {Array} The array of markers managed by the clusterer. */ MarkerClusterer.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the number of markers managed by the clusterer. * * @return {number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function () { return this.markers_.length; }; /** * Returns the current array of clusters formed by the clusterer. * * @return {Array} The array of clusters formed by the clusterer. */ MarkerClusterer.prototype.getClusters = function () { return this.clusters_; }; /** * Returns the number of clusters formed by the clusterer. * * @return {number} The number of clusters formed by the clusterer. */ MarkerClusterer.prototype.getTotalClusters = function () { return this.clusters_.length; }; /** * Adds a marker to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw_(); } }; /** * Adds an array of markers to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {Array.<google.maps.Marker>} markers The markers to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) { var key; for (key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo_(markers[key]); } } if (!opt_nodraw) { this.redraw_(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.pushMarkerTo_ = function (marker) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { var cMarkerClusterer = this; google.maps.event.addListener(marker, "dragend", function () { if (cMarkerClusterer.ready_) { this.isAdded = false; cMarkerClusterer.repaint(); } }); } marker.isAdded = false; this.markers_.push(marker); }; /** * Removes a marker from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the * marker was removed from the clusterer. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if the marker was removed from the clusterer. */ MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes an array of markers from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers * were removed from the clusterer. * * @param {Array.<google.maps.Marker>} markers The markers to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if markers were removed from the clusterer. */ MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) { var i, r; var removed = false; for (i = 0; i < markers.length; i++) { r = this.removeMarker_(markers[i]); removed = removed || r; } if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ MarkerClusterer.prototype.removeMarker_ = function (marker) { var i; var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { index = i; break; } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false; } marker.setMap(null); this.markers_.splice(index, 1); // Remove the marker from the list of managed markers return true; }; /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ MarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = []; }; /** * Recalculates and redraws all the marker clusters from scratch. * Call this after changing any properties. */ MarkerClusterer.prototype.repaint = function () { var oldClusters = this.clusters_.slice(); this.clusters_ = []; this.resetViewport_(false); this.redraw_(); // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function () { var i; for (i = 0; i < oldClusters.length; i++) { oldClusters[i].remove(); } }, 0); }; /** * Returns the current bounds extended by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. * @ignore */ MarkerClusterer.prototype.getExtendedBounds = function (bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Redraws all the clusters. */ MarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ MarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. for (i = 0; i < this.markers_.length; i++) { marker = this.markers_[i]; marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } }; /** * Calculates the distance between two latlng locations in km. * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @see http://www.movable-type.co.uk/scripts/latlong.html */ MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) { var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Determines if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. */ MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ MarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * The default function for determining the label text and style * for a cluster icon. * * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster. * @param {number} numStyles The number of marker styles available. * @return {ClusterIconInfo} The information resource for the cluster. * @constant * @ignore */ MarkerClusterer.CALCULATOR = function (markers, numStyles) { var index = 0; var title = ""; var count = markers.length.toString(); var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index, title: title }; }; /** * The number of markers to process in one batch. * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE = 2000; /** * The number of markers to process in one batch (IE only). * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE_IE = 500; /** * The default root name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m"; /** * The default extension name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_EXTENSION = "png"; /** * The default array of sizes for the marker cluster images. * * @type {Array.<number>} * @constant */ MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90]; /** * @name MarkerWithLabel for V3 * @version 1.1.10 [April 8, 2014] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * 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 browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. * @private */ function inherits(childCtor, parentCtor) { /* @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /* @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; this.labelDiv_.parentNode.removeChild(this.labelDiv_); this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.innerHTML = ""; // Remove current content this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); }; //END REPLACE window.InfoBox = InfoBox; window.Cluster = Cluster; window.ClusterIcon = ClusterIcon; window.MarkerClusterer = MarkerClusterer; window.MarkerLabel_ = MarkerLabel_; window.MarkerWithLabel = MarkerWithLabel; }) }; }); ;/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapDataStructures', function() { return { Graph: __webpack_require__(1).Graph, Queue: __webpack_require__(1).Queue }; }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { (function() { module.exports = { Graph: __webpack_require__(2), Heap: __webpack_require__(3), LinkedList: __webpack_require__(4), Map: __webpack_require__(5), Queue: __webpack_require__(6), RedBlackTree: __webpack_require__(7), Trie: __webpack_require__(8) }; }).call(this); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* Graph implemented as a modified incidence list. O(1) for every typical operation except `removeNode()` at O(E) where E is the number of edges. ## Overview example: ```js var graph = new Graph; graph.addNode('A'); // => a node object. For more info, log the output or check // the documentation for addNode graph.addNode('B'); graph.addNode('C'); graph.addEdge('A', 'C'); // => an edge object graph.addEdge('A', 'B'); graph.getEdge('B', 'A'); // => undefined. Directed edge! graph.getEdge('A', 'B'); // => the edge object previously added graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property // of an edge object. Feel free to attach // other properties graph.getInEdgesOf('B'); // => array of edge objects, in this case only one; // connecting A to B graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward // the node itself are only counted once forEachNode(function(nodeObject) { console.log(node); }); forEachEdge(function(edgeObject) { console.log(edgeObject); }); graph.removeNode('C'); // => 'C'. The edge between A and C also removed graph.removeEdge('A', 'B'); // => the edge object removed ``` ## Properties: - nodeSize: total number of nodes. - edgeSize: total number of edges. */ (function() { var Graph, __hasProp = {}.hasOwnProperty; Graph = (function() { function Graph() { this._nodes = {}; this.nodeSize = 0; this.edgeSize = 0; } Graph.prototype.addNode = function(id) { /* The `id` is a unique identifier for the node, and should **not** change after it's added. It will be used for adding, retrieving and deleting related edges too. **Note** that, internally, the ids are kept in an object. JavaScript's object hashes the id `'2'` and `2` to the same key, so please stick to a simple id data type such as number or string. _Returns:_ the node object. Feel free to attach additional custom properties on it for graph algorithms' needs. **Undefined if node id already exists**, as to avoid accidental overrides. */ if (!this._nodes[id]) { this.nodeSize++; return this._nodes[id] = { _outEdges: {}, _inEdges: {} }; } }; Graph.prototype.getNode = function(id) { /* _Returns:_ the node object. Feel free to attach additional custom properties on it for graph algorithms' needs. */ return this._nodes[id]; }; Graph.prototype.removeNode = function(id) { /* _Returns:_ the node object removed, or undefined if it didn't exist in the first place. */ var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1; nodeToRemove = this._nodes[id]; if (!nodeToRemove) { return; } else { _ref = nodeToRemove._outEdges; for (outEdgeId in _ref) { if (!__hasProp.call(_ref, outEdgeId)) continue; this.removeEdge(id, outEdgeId); } _ref1 = nodeToRemove._inEdges; for (inEdgeId in _ref1) { if (!__hasProp.call(_ref1, inEdgeId)) continue; this.removeEdge(inEdgeId, id); } this.nodeSize--; delete this._nodes[id]; } return nodeToRemove; }; Graph.prototype.addEdge = function(fromId, toId, weight) { var edgeToAdd, fromNode, toNode; if (weight == null) { weight = 1; } /* `fromId` and `toId` are the node id specified when it was created using `addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively makes this an unweighted graph. Under the hood, `weight` is just a normal property of the edge object. _Returns:_ the edge object created. Feel free to attach additional custom properties on it for graph algorithms' needs. **Or undefined** if the nodes of id `fromId` or `toId` aren't found, or if an edge already exists between the two nodes. */ if (this.getEdge(fromId, toId)) { return; } fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; if (!fromNode || !toNode) { return; } edgeToAdd = { weight: weight }; fromNode._outEdges[toId] = edgeToAdd; toNode._inEdges[fromId] = edgeToAdd; this.edgeSize++; return edgeToAdd; }; Graph.prototype.getEdge = function(fromId, toId) { /* _Returns:_ the edge object, or undefined if the nodes of id `fromId` or `toId` aren't found. */ var fromNode, toNode; fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; if (!fromNode || !toNode) { } else { return fromNode._outEdges[toId]; } }; Graph.prototype.removeEdge = function(fromId, toId) { /* _Returns:_ the edge object removed, or undefined of edge wasn't found. */ var edgeToDelete, fromNode, toNode; fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; edgeToDelete = this.getEdge(fromId, toId); if (!edgeToDelete) { return; } delete fromNode._outEdges[toId]; delete toNode._inEdges[fromId]; this.edgeSize--; return edgeToDelete; }; Graph.prototype.getInEdgesOf = function(nodeId) { /* _Returns:_ an array of edge objects that are directed toward the node, or empty array if no such edge or node exists. */ var fromId, inEdges, toNode, _ref; toNode = this._nodes[nodeId]; inEdges = []; _ref = toNode != null ? toNode._inEdges : void 0; for (fromId in _ref) { if (!__hasProp.call(_ref, fromId)) continue; inEdges.push(this.getEdge(fromId, nodeId)); } return inEdges; }; Graph.prototype.getOutEdgesOf = function(nodeId) { /* _Returns:_ an array of edge objects that go out of the node, or empty array if no such edge or node exists. */ var fromNode, outEdges, toId, _ref; fromNode = this._nodes[nodeId]; outEdges = []; _ref = fromNode != null ? fromNode._outEdges : void 0; for (toId in _ref) { if (!__hasProp.call(_ref, toId)) continue; outEdges.push(this.getEdge(nodeId, toId)); } return outEdges; }; Graph.prototype.getAllEdgesOf = function(nodeId) { /* **Note:** not the same as concatenating `getInEdgesOf()` and `getOutEdgesOf()`. Some nodes might have an edge pointing toward itself. This method solves that duplication. _Returns:_ an array of edge objects linked to the node, no matter if they're outgoing or coming. Duplicate edge created by self-pointing nodes are removed. Only one copy stays. Empty array if node has no edge. */ var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1; inEdges = this.getInEdgesOf(nodeId); outEdges = this.getOutEdgesOf(nodeId); if (inEdges.length === 0) { return outEdges; } selfEdge = this.getEdge(nodeId, nodeId); for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { if (inEdges[i] === selfEdge) { _ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1]; inEdges.pop(); break; } } return inEdges.concat(outEdges); }; Graph.prototype.forEachNode = function(operation) { /* Traverse through the graph in an arbitrary manner, visiting each node once. Pass a function of the form `fn(nodeObject, nodeId)`. _Returns:_ undefined. */ var nodeId, nodeObject, _ref; _ref = this._nodes; for (nodeId in _ref) { if (!__hasProp.call(_ref, nodeId)) continue; nodeObject = _ref[nodeId]; operation(nodeObject, nodeId); } }; Graph.prototype.forEachEdge = function(operation) { /* Traverse through the graph in an arbitrary manner, visiting each edge once. Pass a function of the form `fn(edgeObject)`. _Returns:_ undefined. */ var edgeObject, nodeId, nodeObject, toId, _ref, _ref1; _ref = this._nodes; for (nodeId in _ref) { if (!__hasProp.call(_ref, nodeId)) continue; nodeObject = _ref[nodeId]; _ref1 = nodeObject._outEdges; for (toId in _ref1) { if (!__hasProp.call(_ref1, toId)) continue; edgeObject = _ref1[toId]; operation(edgeObject); } } }; return Graph; })(); module.exports = Graph; }).call(this); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* Minimum heap, i.e. smallest node at root. **Note:** does not accept null or undefined. This is by design. Those values cause comparison problems and might report false negative during extraction. ## Overview example: ```js var heap = new Heap([5, 6, 3, 4]); heap.add(10); // => 10 heap.removeMin(); // => 3 heap.peekMin(); // => 4 ``` ## Properties: - size: total number of items. */ (function() { var Heap, _leftChild, _parent, _rightChild; Heap = (function() { function Heap(dataToHeapify) { var i, item, _i, _j, _len, _ref; if (dataToHeapify == null) { dataToHeapify = []; } /* Pass an optional array to be heapified. Takes only O(n) time. */ this._data = [void 0]; for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) { item = dataToHeapify[_i]; if (item != null) { this._data.push(item); } } if (this._data.length > 1) { for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) { this._upHeap(i); } } this.size = this._data.length - 1; } Heap.prototype.add = function(value) { /* **Remember:** rejects null and undefined for mentioned reasons. _Returns:_ the value added. */ if (value == null) { return; } this._data.push(value); this._upHeap(this._data.length - 1); this.size++; return value; }; Heap.prototype.removeMin = function() { /* _Returns:_ the smallest item (the root). */ var min; if (this._data.length === 1) { return; } this.size--; if (this._data.length === 2) { return this._data.pop(); } min = this._data[1]; this._data[1] = this._data.pop(); this._downHeap(); return min; }; Heap.prototype.peekMin = function() { /* Check the smallest item without removing it. _Returns:_ the smallest item (the root). */ return this._data[1]; }; Heap.prototype._upHeap = function(index) { var valueHolder, _ref; valueHolder = this._data[index]; while (this._data[index] < this._data[_parent(index)] && index > 1) { _ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1]; index = _parent(index); } }; Heap.prototype._downHeap = function() { var currentIndex, smallerChildIndex, _ref; currentIndex = 1; while (_leftChild(currentIndex < this._data.length)) { smallerChildIndex = _leftChild(currentIndex); if (smallerChildIndex < this._data.length - 1) { if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) { smallerChildIndex = _rightChild(currentIndex); } } if (this._data[smallerChildIndex] < this._data[currentIndex]) { _ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1]; currentIndex = smallerChildIndex; } else { break; } } }; return Heap; })(); _parent = function(index) { return index >> 1; }; _leftChild = function(index) { return index << 1; }; _rightChild = function(index) { return (index << 1) + 1; }; module.exports = Heap; }).call(this); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* Doubly Linked. ## Overview example: ```js var list = new LinkedList([5, 4, 9]); list.add(12); // => 12 list.head.next.value; // => 4 list.tail.value; // => 12 list.at(-1); // => 12 list.removeAt(2); // => 9 list.remove(4); // => 4 list.indexOf(5); // => 0 list.add(5, 1); // => 5. Second 5 at position 1. list.indexOf(5, 1); // => 1 ``` ## Properties: - head: first item. - tail: last item. - size: total number of items. - item.value: value passed to the item when calling `add()`. - item.prev: previous item. - item.next: next item. */ (function() { var LinkedList; LinkedList = (function() { function LinkedList(valuesToAdd) { var value, _i, _len; if (valuesToAdd == null) { valuesToAdd = []; } /* Can pass an array of elements to link together during `new LinkedList()` initiation. */ this.head = { prev: void 0, value: void 0, next: void 0 }; this.tail = { prev: void 0, value: void 0, next: void 0 }; this.size = 0; for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) { value = valuesToAdd[_i]; this.add(value); } } LinkedList.prototype.at = function(position) { /* Get the item at `position` (optional). Accepts negative index: ```js myList.at(-1); // Returns the last element. ``` However, passing a negative index that surpasses the boundary will return undefined: ```js myList = new LinkedList([2, 6, 8, 3]) myList.at(-5); // Undefined. myList.at(-4); // 2. ``` _Returns:_ item gotten, or undefined if not found. */ var currentNode, i, _i, _j, _ref; if (!((-this.size <= position && position < this.size))) { return; } position = this._adjust(position); if (position * 2 < this.size) { currentNode = this.head; for (i = _i = 1; _i <= position; i = _i += 1) { currentNode = currentNode.next; } } else { currentNode = this.tail; for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) { currentNode = currentNode.prev; } } return currentNode; }; LinkedList.prototype.add = function(value, position) { var currentNode, nodeToAdd, _ref, _ref1, _ref2; if (position == null) { position = this.size; } /* Add a new item at `position` (optional). Defaults to adding at the end. `position`, just like in `at()`, can be negative (within the negative boundary). Position specifies the place the value's going to be, and the old node will be pushed higher. `add(-2)` on list of size 7 is the same as `add(5)`. _Returns:_ item added. */ if (!((-this.size <= position && position <= this.size))) { return; } nodeToAdd = { value: value }; position = this._adjust(position); if (this.size === 0) { this.head = nodeToAdd; } else { if (position === 0) { _ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2]; } else { currentNode = this.at(position - 1); _ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3]; } } if (position === this.size) { this.tail = nodeToAdd; } this.size++; return value; }; LinkedList.prototype.removeAt = function(position) { var currentNode, valueToReturn, _ref; if (position == null) { position = this.size - 1; } /* Remove an item at index `position` (optional). Defaults to the last item. Index can be negative (within the boundary). _Returns:_ item removed. */ if (!((-this.size <= position && position < this.size))) { return; } if (this.size === 0) { return; } position = this._adjust(position); if (this.size === 1) { valueToReturn = this.head.value; this.head.value = this.tail.value = void 0; } else { if (position === 0) { valueToReturn = this.head.value; this.head = this.head.next; this.head.prev = void 0; } else { currentNode = this.at(position); valueToReturn = currentNode.value; currentNode.prev.next = currentNode.next; if ((_ref = currentNode.next) != null) { _ref.prev = currentNode.prev; } if (position === this.size - 1) { this.tail = currentNode.prev; } } } this.size--; return valueToReturn; }; LinkedList.prototype.remove = function(value) { /* Remove the item using its value instead of position. **Will remove the fist occurrence of `value`.** _Returns:_ the value, or undefined if value's not found. */ var currentNode; if (value == null) { return; } currentNode = this.head; while (currentNode && currentNode.value !== value) { currentNode = currentNode.next; } if (!currentNode) { return; } if (this.size === 1) { this.head.value = this.tail.value = void 0; } else if (currentNode === this.head) { this.head = this.head.next; this.head.prev = void 0; } else if (currentNode === this.tail) { this.tail = this.tail.prev; this.tail.next = void 0; } else { currentNode.prev.next = currentNode.next; currentNode.next.prev = currentNode.prev; } this.size--; return value; }; LinkedList.prototype.indexOf = function(value, startingPosition) { var currentNode, position; if (startingPosition == null) { startingPosition = 0; } /* Find the index of an item, similarly to `array.indexOf()`. Defaults to start searching from the beginning, by can start at another position by passing `startingPosition`. This parameter can also be negative; but unlike the other methods of this class, `startingPosition` (optional) can be as small as desired; a value of -999 for a list of size 5 will start searching normally, at the beginning. **Note:** searches forwardly, **not** backwardly, i.e: ```js var myList = new LinkedList([2, 3, 1, 4, 3, 5]) myList.indexOf(3, -3); // Returns 4, not 1 ``` _Returns:_ index of item found, or -1 if not found. */ if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) { return -1; } startingPosition = Math.max(0, this._adjust(startingPosition)); currentNode = this.at(startingPosition); position = startingPosition; while (currentNode) { if (currentNode.value === value) { break; } currentNode = currentNode.next; position++; } if (position === this.size) { return -1; } else { return position; } }; LinkedList.prototype._adjust = function(position) { if (position < 0) { return this.size + position; } else { return position; } }; return LinkedList; })(); module.exports = LinkedList; }).call(this); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* Kind of a stopgap measure for the upcoming [JavaScript Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets) **Note:** due to JavaScript's limitations, hashing something other than Boolean, Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a hidden unique property into the object. This means `set`, `get`, `has` and `delete` must employ the same object, and not a mere identical copy as in the case of, say, a string. ## Overview example: ```js var map = new Map({'alice': 'wonderland', 20: 'ok'}); map.set('20', 5); // => 5 map.get('20'); // => 5 map.has('alice'); // => true map.delete(20) // => true var arr = [1, 2]; map.add(arr, 'goody'); // => 'goody' map.has(arr); // => true map.has([1, 2]); // => false. Needs to compare by reference map.forEach(function(key, value) { console.log(key, value); }); ``` ## Properties: - size: The total number of `(key, value)` pairs. */ (function() { var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType, __hasProp = {}.hasOwnProperty; SPECIAL_TYPE_KEY_PREFIX = '_mapId_'; Map = (function() { Map._mapIdTracker = 0; Map._newMapId = function() { return this._mapIdTracker++; }; function Map(objectToMap) { /* Pass an optional object whose (key, value) pair will be hashed. **Careful** not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's native object behavior will crush the first 5 property before it gets to constructor. */ var key, value; this._content = {}; this._itemId = 0; this._id = Map._newMapId(); this.size = 0; for (key in objectToMap) { if (!__hasProp.call(objectToMap, key)) continue; value = objectToMap[key]; this.set(key, value); } } Map.prototype.hash = function(key, makeHash) { var propertyForMap, type; if (makeHash == null) { makeHash = false; } /* The hash function for hashing keys is public. Feel free to replace it with your own. The `makeHash` parameter is optional and accepts a boolean (defaults to `false`) indicating whether or not to produce a new hash (for the first use, naturally). _Returns:_ the hash. */ type = _extractDataType(key); if (_isSpecialType(key)) { propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id; if (makeHash && !key[propertyForMap]) { key[propertyForMap] = this._itemId++; } return propertyForMap + '_' + key[propertyForMap]; } else { return type + '_' + key; } }; Map.prototype.set = function(key, value) { /* _Returns:_ value. */ if (!this.has(key)) { this.size++; } this._content[this.hash(key, true)] = [value, key]; return value; }; Map.prototype.get = function(key) { /* _Returns:_ value corresponding to the key, or undefined if not found. */ var _ref; return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0; }; Map.prototype.has = function(key) { /* Check whether a value exists for the key. _Returns:_ true or false. */ return this.hash(key) in this._content; }; Map.prototype["delete"] = function(key) { /* Remove the (key, value) pair. _Returns:_ **true or false**. Unlike most of this library, this method doesn't return the deleted value. This is so that it conforms to the future JavaScript `map.delete()`'s behavior. */ var hashedKey; hashedKey = this.hash(key); if (hashedKey in this._content) { delete this._content[hashedKey]; if (_isSpecialType(key)) { delete key[SPECIAL_TYPE_KEY_PREFIX + this._id]; } this.size--; return true; } return false; }; Map.prototype.forEach = function(operation) { /* Traverse through the map. Pass a function of the form `fn(key, value)`. _Returns:_ undefined. */ var key, value, _ref; _ref = this._content; for (key in _ref) { if (!__hasProp.call(_ref, key)) continue; value = _ref[key]; operation(value[1], value[0]); } }; return Map; })(); _isSpecialType = function(key) { var simpleHashableTypes, simpleType, type, _i, _len; simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function']; type = _extractDataType(key); for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) { simpleType = simpleHashableTypes[_i]; if (type === simpleType) { return false; } } return true; }; _extractDataType = function(type) { return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1]; }; module.exports = Map; }).call(this); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* Amortized O(1) dequeue! ## Overview example: ```js var queue = new Queue([1, 6, 4]); queue.enqueue(10); // => 10 queue.dequeue(); // => 1 queue.dequeue(); // => 6 queue.dequeue(); // => 4 queue.peek(); // => 10 queue.dequeue(); // => 10 queue.peek(); // => undefined ``` ## Properties: - size: The total number of items. */ (function() { var Queue; Queue = (function() { function Queue(initialArray) { if (initialArray == null) { initialArray = []; } /* Pass an optional array to be transformed into a queue. The item at index 0 is the first to be dequeued. */ this._content = initialArray; this._dequeueIndex = 0; this.size = this._content.length; } Queue.prototype.enqueue = function(item) { /* _Returns:_ the item. */ this.size++; this._content.push(item); return item; }; Queue.prototype.dequeue = function() { /* _Returns:_ the dequeued item. */ var itemToDequeue; if (this.size === 0) { return; } this.size--; itemToDequeue = this._content[this._dequeueIndex]; this._dequeueIndex++; if (this._dequeueIndex * 2 > this._content.length) { this._content = this._content.slice(this._dequeueIndex); this._dequeueIndex = 0; } return itemToDequeue; }; Queue.prototype.peek = function() { /* Check the next item to be dequeued, without removing it. _Returns:_ the item. */ return this._content[this._dequeueIndex]; }; return Queue; })(); module.exports = Queue; }).call(this); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* Credit to Wikipedia's article on [Red-black tree](http://en.wikipedia.org/wiki/Red–black_tree) **Note:** doesn't handle duplicate entries, undefined and null. This is by design. ## Overview example: ```js var rbt = new RedBlackTree([7, 5, 1, 8]); rbt.add(2); // => 2 rbt.add(10); // => 10 rbt.has(5); // => true rbt.peekMin(); // => 1 rbt.peekMax(); // => 10 rbt.removeMin(); // => 1 rbt.removeMax(); // => 10 rbt.remove(8); // => 8 ``` ## Properties: - size: The total number of items. */ (function() { var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf; NODE_FOUND = 0; NODE_TOO_BIG = 1; NODE_TOO_SMALL = 2; STOP_SEARCHING = 3; RED = 1; BLACK = 2; RedBlackTree = (function() { function RedBlackTree(valuesToAdd) { var value, _i, _len; if (valuesToAdd == null) { valuesToAdd = []; } /* Pass an optional array to be turned into binary tree. **Note:** does not accept duplicate, undefined and null. */ this._root; this.size = 0; for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) { value = valuesToAdd[_i]; if (value != null) { this.add(value); } } } RedBlackTree.prototype.add = function(value) { /* Again, make sure to not pass a value already in the tree, or undefined, or null. _Returns:_ value added. */ var currentNode, foundNode, nodeToInsert, _ref; if (value == null) { return; } this.size++; nodeToInsert = { value: value, _color: RED }; if (!this._root) { this._root = nodeToInsert; } else { foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else { if (value < node.value) { if (node._left) { return NODE_TOO_BIG; } else { nodeToInsert._parent = node; node._left = nodeToInsert; return STOP_SEARCHING; } } else { if (node._right) { return NODE_TOO_SMALL; } else { nodeToInsert._parent = node; node._right = nodeToInsert; return STOP_SEARCHING; } } } }); if (foundNode != null) { return; } } currentNode = nodeToInsert; while (true) { if (currentNode === this._root) { currentNode._color = BLACK; break; } if (currentNode._parent._color === BLACK) { break; } if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) { currentNode._parent._color = BLACK; _uncleOf(currentNode)._color = BLACK; _grandParentOf(currentNode)._color = RED; currentNode = _grandParentOf(currentNode); continue; } if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) { this._rotateLeft(currentNode._parent); currentNode = currentNode._left; } else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) { this._rotateRight(currentNode._parent); currentNode = currentNode._right; } currentNode._parent._color = BLACK; _grandParentOf(currentNode)._color = RED; if (_isLeft(currentNode)) { this._rotateRight(_grandParentOf(currentNode)); } else { this._rotateLeft(_grandParentOf(currentNode)); } break; } return value; }; RedBlackTree.prototype.has = function(value) { /* _Returns:_ true or false. */ var foundNode; foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else if (value < node.value) { return NODE_TOO_BIG; } else { return NODE_TOO_SMALL; } }); if (foundNode) { return true; } else { return false; } }; RedBlackTree.prototype.peekMin = function() { /* Check the minimum value without removing it. _Returns:_ the minimum value. */ var _ref; return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0; }; RedBlackTree.prototype.peekMax = function() { /* Check the maximum value without removing it. _Returns:_ the maximum value. */ var _ref; return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0; }; RedBlackTree.prototype.remove = function(value) { /* _Returns:_ the value removed, or undefined if the value's not found. */ var foundNode; foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else if (value < node.value) { return NODE_TOO_BIG; } else { return NODE_TOO_SMALL; } }); if (!foundNode) { return; } this._removeNode(this._root, foundNode); this.size--; return value; }; RedBlackTree.prototype.removeMin = function() { /* _Returns:_ smallest item removed, or undefined if tree's empty. */ var nodeToRemove, valueToReturn; nodeToRemove = _peekMinNode(this._root); if (!nodeToRemove) { return; } valueToReturn = nodeToRemove.value; this._removeNode(this._root, nodeToRemove); return valueToReturn; }; RedBlackTree.prototype.removeMax = function() { /* _Returns:_ biggest item removed, or undefined if tree's empty. */ var nodeToRemove, valueToReturn; nodeToRemove = _peekMaxNode(this._root); if (!nodeToRemove) { return; } valueToReturn = nodeToRemove.value; this._removeNode(this._root, nodeToRemove); return valueToReturn; }; RedBlackTree.prototype._removeNode = function(root, node) { var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; if (node._left && node._right) { successor = _peekMinNode(node._right); node.value = successor.value; node = successor; } successor = node._left || node._right; if (!successor) { successor = { color: BLACK, _right: void 0, _left: void 0, isLeaf: true }; } successor._parent = node._parent; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = successor; } if (node._color === BLACK) { if (successor._color === RED) { successor._color = BLACK; if (!successor._parent) { this._root = successor; } } else { while (true) { if (!successor._parent) { if (!successor.isLeaf) { this._root = successor; } else { this._root = void 0; } break; } sibling = _siblingOf(successor); if ((sibling != null ? sibling._color : void 0) === RED) { successor._parent._color = RED; sibling._color = BLACK; if (_isLeft(successor)) { this._rotateLeft(successor._parent); } else { this._rotateRight(successor._parent); } } sibling = _siblingOf(successor); if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) { if (sibling != null) { sibling._color = RED; } if (successor.isLeaf) { successor._parent[_leftOrRight(successor)] = void 0; } successor = successor._parent; continue; } if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) { if (sibling != null) { sibling._color = RED; } successor._parent._color = BLACK; break; } if ((sibling != null ? sibling._color : void 0) === BLACK) { if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) { sibling._color = RED; if ((_ref4 = sibling._left) != null) { _ref4._color = BLACK; } this._rotateRight(sibling); } else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) { sibling._color = RED; if ((_ref6 = sibling._right) != null) { _ref6._color = BLACK; } this._rotateLeft(sibling); } break; } sibling = _siblingOf(successor); sibling._color = successor._parent._color; if (_isLeft(successor)) { sibling._right._color = BLACK; this._rotateRight(successor._parent); } else { sibling._left._color = BLACK; this._rotateLeft(successor._parent); } } } } if (successor.isLeaf) { return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0; } }; RedBlackTree.prototype._rotateLeft = function(node) { var _ref, _ref1; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = node._right; } node._right._parent = node._parent; node._parent = node._right; node._right = node._right._left; node._parent._left = node; if ((_ref1 = node._right) != null) { _ref1._parent = node; } if (node._parent._parent == null) { return this._root = node._parent; } }; RedBlackTree.prototype._rotateRight = function(node) { var _ref, _ref1; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = node._left; } node._left._parent = node._parent; node._parent = node._left; node._left = node._left._right; node._parent._right = node; if ((_ref1 = node._left) != null) { _ref1._parent = node; } if (node._parent._parent == null) { return this._root = node._parent; } }; return RedBlackTree; })(); _isLeft = function(node) { return node === node._parent._left; }; _leftOrRight = function(node) { if (_isLeft(node)) { return '_left'; } else { return '_right'; } }; _findNode = function(startingNode, comparator) { var comparisonResult, currentNode, foundNode; currentNode = startingNode; foundNode = void 0; while (currentNode) { comparisonResult = comparator(currentNode); if (comparisonResult === NODE_FOUND) { foundNode = currentNode; break; } if (comparisonResult === NODE_TOO_BIG) { currentNode = currentNode._left; } else if (comparisonResult === NODE_TOO_SMALL) { currentNode = currentNode._right; } else if (comparisonResult === STOP_SEARCHING) { break; } } return foundNode; }; _peekMinNode = function(startingNode) { return _findNode(startingNode, function(node) { if (node._left) { return NODE_TOO_BIG; } else { return NODE_FOUND; } }); }; _peekMaxNode = function(startingNode) { return _findNode(startingNode, function(node) { if (node._right) { return NODE_TOO_SMALL; } else { return NODE_FOUND; } }); }; _grandParentOf = function(node) { var _ref; return (_ref = node._parent) != null ? _ref._parent : void 0; }; _uncleOf = function(node) { if (!_grandParentOf(node)) { return; } if (_isLeft(node._parent)) { return _grandParentOf(node)._right; } else { return _grandParentOf(node)._left; } }; _siblingOf = function(node) { if (_isLeft(node)) { return node._parent._right; } else { return node._parent._left; } }; module.exports = RedBlackTree; }).call(this); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* Good for fast insertion/removal/lookup of strings. ## Overview example: ```js var trie = new Trie(['bear', 'beer']); trie.add('hello'); // => 'hello' trie.add('helloha!'); // => 'helloha!' trie.has('bears'); // => false trie.longestPrefixOf('beatrice'); // => 'bea' trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!'] trie.remove('beers'); // => undefined. 'beer' still exists trie.remove('Beer') // => undefined. Case-sensitive trie.remove('beer') // => 'beer'. Removed ``` ## Properties: - size: The total number of words. */ (function() { var Queue, Trie, WORD_END, _hasAtLeastNChildren, __hasProp = {}.hasOwnProperty; Queue = __webpack_require__(6); WORD_END = 'end'; Trie = (function() { function Trie(words) { var word, _i, _len; if (words == null) { words = []; } /* Pass an optional array of strings to be inserted initially. */ this._root = {}; this.size = 0; for (_i = 0, _len = words.length; _i < _len; _i++) { word = words[_i]; this.add(word); } } Trie.prototype.add = function(word) { /* Add a whole string to the trie. _Returns:_ the word added. Will return undefined (without adding the value) if the word passed is null or undefined. */ var currentNode, letter, _i, _len; if (word == null) { return; } this.size++; currentNode = this._root; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { currentNode[letter] = {}; } currentNode = currentNode[letter]; } currentNode[WORD_END] = true; return word; }; Trie.prototype.has = function(word) { /* __Returns:_ true or false. */ var currentNode, letter, _i, _len; if (word == null) { return false; } currentNode = this._root; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { return false; } currentNode = currentNode[letter]; } if (currentNode[WORD_END]) { return true; } else { return false; } }; Trie.prototype.longestPrefixOf = function(word) { /* Find all words containing the prefix. The word itself counts as a prefix. ```js var trie = new Trie; trie.add('hello'); trie.longestPrefixOf('he'); // 'he' trie.longestPrefixOf('hello'); // 'hello' trie.longestPrefixOf('helloha!'); // 'hello' ``` _Returns:_ the prefix string, or empty string if no prefix found. */ var currentNode, letter, prefix, _i, _len; if (word == null) { return ''; } currentNode = this._root; prefix = ''; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { break; } prefix += letter; currentNode = currentNode[letter]; } return prefix; }; Trie.prototype.wordsWithPrefix = function(prefix) { /* Find all words containing the prefix. The word itself counts as a prefix. **Watch out for edge cases.** ```js var trie = new Trie; trie.wordsWithPrefix(''); // []. Check later case below. trie.add(''); trie.wordsWithPrefix(''); // [''] trie.add('he'); trie.add('hello'); trie.add('hell'); trie.add('bear'); trie.add('z'); trie.add('zebra'); trie.wordsWithPrefix('hel'); // ['hell', 'hello'] ``` _Returns:_ an array of strings, or empty array if no word found. */ var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref; if (prefix == null) { return []; } (prefix != null) || (prefix = ''); words = []; currentNode = this._root; for (_i = 0, _len = prefix.length; _i < _len; _i++) { letter = prefix[_i]; currentNode = currentNode[letter]; if (currentNode == null) { return []; } } queue = new Queue(); queue.enqueue([currentNode, '']); while (queue.size !== 0) { _ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1]; if (node[WORD_END]) { words.push(prefix + accumulatedLetters); } for (letter in node) { if (!__hasProp.call(node, letter)) continue; subNode = node[letter]; queue.enqueue([subNode, accumulatedLetters + letter]); } } return words; }; Trie.prototype.remove = function(word) { /* _Returns:_ the string removed, or undefined if the word in its whole doesn't exist. **Note:** this means removing `beers` when only `beer` exists will return undefined and conserve `beer`. */ var currentNode, i, letter, prefix, _i, _j, _len, _ref; if (word == null) { return; } currentNode = this._root; prefix = []; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { return; } currentNode = currentNode[letter]; prefix.push([letter, currentNode]); } if (!currentNode[WORD_END]) { return; } this.size--; delete currentNode[WORD_END]; if (_hasAtLeastNChildren(currentNode, 1)) { return word; } for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) { if (!_hasAtLeastNChildren(prefix[i][1], 1)) { delete prefix[i - 1][1][prefix[i][0]]; } else { break; } } if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) { delete this._root[prefix[0][0]]; } return word; }; return Trie; })(); _hasAtLeastNChildren = function(node, n) { var child, childCount; if (n === 0) { return true; } childCount = 0; for (child in node) { if (!__hasProp.call(node, child)) continue; childCount++; if (childCount >= n) { return true; } } return false; }; module.exports = Trie; }).call(this); /***/ } /******/ ]);;/** * Performance overrides on MarkerClusterer custom to Angular Google Maps * * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14. */ angular.module('uiGmapgoogle-maps.extensions') .service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) { return { init: _.once(function () { (function () { var __hasProp = {}.hasOwnProperty, __extends = function (child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.NgMapCluster = (function (_super) { __extends(NgMapCluster, _super); function NgMapCluster(opts) { NgMapCluster.__super__.constructor.call(this, opts); this.markers_ = new PropMap(); } /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ NgMapCluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { var oldMarker = this.markers_.get(marker.key); if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. this.markers_.each(function (m) { m.setMap(null); }); } else { marker.setMap(null); } //this.updateIcon_(); return true; }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) { return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key)); }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ NgMapCluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.getMarkers().each(function(m){ bounds.extend(m.getPosition()); }); return bounds; }; /** * Removes the cluster from the map. * * @ignore */ NgMapCluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = new PropMap(); delete this.markers_; }; return NgMapCluster; })(Cluster); window.NgMapMarkerClusterer = (function (_super) { __extends(NgMapMarkerClusterer, _super); function NgMapMarkerClusterer(map, opt_markers, opt_options) { NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options); this.markers_ = new PropMap(); } /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ NgMapMarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = new PropMap(); }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) { if (!this.markers_.get(marker.key)) { return false; } marker.setMap(null); this.markers_.remove(marker.key); // Remove the marker from the list of managed markers return true; }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringbegin', this); if (typeof this.timerRefStatic !== 'undefined') { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); var _ms = this.markers_.values(); for (i = iFirst; i < iLast; i++) { marker = _ms[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { // custom addition by ui-gmap // update icon for all clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].updateIcon_(); } delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringend', this); } }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new NgMapCluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Redraws all the clusters. */ NgMapMarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. this.markers_.each(function (marker) { marker.isAdded = false; if (opt_hide) { marker.setMap(null); } }); }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { if (property !== 'constructor') this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; //////////////////////////////////////////////////////////////////////////////// /* Other overrides relevant to MarkerClusterPlus */ //////////////////////////////////////////////////////////////////////////////// /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } // ADDED FOR RETINA SUPPORT else { img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;"; } // END ADD img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; //END OTHER OVERRIDES //////////////////////////////////////////////////////////////////////////////// return NgMapMarkerClusterer; })(MarkerClusterer); }).call(this); }) }; }]); }( window,angular)); //# sourceMappingURL=angular-google-maps_dev_mapped.js.map
app/javascript/mastodon/features/list_adder/components/account.js
tateisu/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import { injectIntl } from 'react-intl'; const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId }) => ({ account: getAccount(state, accountId), }); return mapStateToProps; }; export default @connect(makeMapStateToProps) @injectIntl class Account extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; render () { const { account } = this.props; return ( <div className='account'> <div className='account__wrapper'> <div className='account__display-name'> <div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div> <DisplayName account={account} /> </div> </div> </div> ); } }
ajax/libs/forerunnerdb/1.3.699/fdb-core+views.js
redmunds/cdnjs
(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(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":8,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = new Overload('Collection.prototype.setData', { '*': function (data) { return this.$main.call(this, data, {}); }, '*, object': function (data, options) { return this.$main.call(this, data, options); }, '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' 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: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when the update is * complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],7:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":6,"./Shared":31}],8:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":5,"./Collection.js":6,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":31}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":27}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":27}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":31}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":31}],30:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],31:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.699', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],33:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well this.rebuildActiveBucket(this._querySettings.options); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
ajax/libs/rxjs/2.2.22/rx.lite.extras.js
Timbioz/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx', 'exports'], function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, noop = helpers.noop, observableFromPromise = Observable.fromPromise, slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var argumentOutOfRange = 'Argument out of range'; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * 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 = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); return Rx; }));
src/svg-icons/image/photo-library.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhotoLibrary = (props) => ( <SvgIcon {...props}> <path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/> </SvgIcon> ); ImagePhotoLibrary = pure(ImagePhotoLibrary); ImagePhotoLibrary.displayName = 'ImagePhotoLibrary'; ImagePhotoLibrary.muiName = 'SvgIcon'; export default ImagePhotoLibrary;
ui/generic/_footer.js
sakulstra/firebase-nextjs-mobx
import React from 'react' import Link from 'next/prefetch' const Footer = () => ( <footer className='footer'> <Link href='/impressum'><a>Impressum</a></Link> </footer> ) export default Footer
ajax/libs/F2/1.3.3/f2.js
suy/cdnjs
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; } /*! JSON.org requires the following notice to accompany json2: Copyright (c) 2002 JSON.org http://json.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. 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. */ /* This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. 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); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. 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); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. 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, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /*! * jQuery JavaScript Library v1.8.3 * The jQuery Foundation and other contributors require the following notice to accompany jQuery: * * Copyright (c) 2013 jQuery Foundation and other contributors * * http://jquery.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } 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.8.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 core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return 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 = jQuery.merge( this.constructor(), 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 ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +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( core_slice.apply( this, arguments ), "slice", core_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: core_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 ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 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").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_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 && !core_hasOwn.call(obj, "constructor") && !core_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 || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { 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; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, 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 && core_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.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; 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 retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; 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 ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else 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 { // 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 top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; 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.5/.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", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // 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", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its 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" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/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: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // 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) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; 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 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.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%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // 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 marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // 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.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) 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[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && 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[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // 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 ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( 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, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = 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 ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, 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" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // 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( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, 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, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, 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( core_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 ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; 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 ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( 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( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated 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 + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); 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.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // 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, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( 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 ); } } 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; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } 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, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName 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 ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { 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; } } } }); // 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, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( 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 ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // 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 ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : 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.value = 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; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // 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; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // 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 rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; 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.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", 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 ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // 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.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === 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. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, 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; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.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 ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; 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 }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !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, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, 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 ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var 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; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // 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" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : 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 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, 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 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // 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 i, l, length, n, r, ret, self = this; 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; } } }); } ret = this.pushStack( "", "find", selector ); 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 i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, 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" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } 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 ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // 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; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !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 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).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; }, 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; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, 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, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (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() { var elem, i = 0; for ( ; (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 ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // 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 ); } }); } 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 ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } 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] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function 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(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.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; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // 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 // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } 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 elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { 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 ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!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 i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (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 { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; 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> 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; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.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; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // 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, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that 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, extra )) !== 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, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.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; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.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 === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // 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("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); 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) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there 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; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { 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 return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ 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(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // 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" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, 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 = {}, // 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 = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // 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 selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); 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.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 if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // 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 ); }); return this; }; // 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.on( 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; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, 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 // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // 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.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // 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 || strAbort; 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 ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // 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 ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } 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.fireWith( 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.add; // 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.always( 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( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // 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 and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // 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 ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // 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 ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // 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 xhrCallbacks, // #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; // 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 handle, i, xhr = s.xhr(); // 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 occurred // 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; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // 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 ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } 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 fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.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; } 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 || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /*! ========================================================= * bootstrap-modal.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Twitter, Inc. require the following notice to accompany Bootstrap: * * Copyright (c) 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work * except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or 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 ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element .show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function (that) { this.$element .hide() .trigger('hidden') this.backdrop() } , removeBackdrop: function () { this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) : this.removeBackdrop() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /*! * This file creates $ and jQuery variables within the F2 closure scope */ var $, jQuery = $ = window.jQuery.noConflict(true); /*! * Hij1nx requires the following notice to accompany EventEmitter: * * Copyright (c) 2011 hij1nx * * http://www.twitter.com/hij1nx * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ !function(exports, undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = new Object; } function configure(conf) { if (conf) { conf.delimiter && (this.delimiter = conf.delimiter); conf.wildcard && (this.wildcard = conf.wildcard); if (this.wildcard) { this.listenerTree = new Object; } } } function EventEmitter(conf) { this._events = new Object; configure.call(this, conf); } // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name) { if (!tree[name]) { tree[name] = new Object; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else if(typeof tree._listeners === 'function') { tree._listeners = [tree._listeners, listener]; } else if (isArray(tree._listeners)) { tree._listeners.push(listener); if (!tree._listeners.warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && tree._listeners.length > m) { tree._listeners.warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', tree._listeners.length); console.trace(); } } } return true; } name = type.shift(); } return true; }; // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { this._events || init.call(this); this._events.maxListeners = n; }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { this.many(event, 1, fn); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } fn.apply(this, arguments); }; listener._origin = fn; this.on(event, listener); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener') { if (!this._events.newListener) { return false; } } // Loop through the *_all* functions and invoke them. if (this._all) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; for (i = 0, l = this._all.length; i < l; i++) { this.event = type; this._all[i].apply(this, args); } } // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._all && !this._events.error && !(this.wildcard && this.listenerTree.error)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } var handler; if(this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; if (arguments.length === 1) { handler.call(this); } else if (arguments.length > 1) switch (arguments.length) { case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (handler) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { this.event = type; listeners[i].apply(this, args); } return (listeners.length > 0) || this._all; } else { return this._all; } }; EventEmitter.prototype.on = function(type, listener) { if (typeof type === 'function') { this.onAny(type); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if(this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if(typeof this._events[type] === 'function') { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } return this; }; EventEmitter.prototype.onAny = function(fn) { if(!this._all) { this._all = []; } if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } // Add the function to the event listener collection. this._all.push(fn); return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { return this; } if(this.wildcard) { leaf._listeners.splice(position, 1) } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); return this; } } } else { this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else { if (!this._events[type]) return this; this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if(this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; // if (typeof define === 'function' && define.amd) { // define('EventEmitter2', [], function() { // return EventEmitter; // }); // } else { exports.EventEmitter2 = EventEmitter; // } }(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window); /*! * Øyvind Sean Kinsey and others require the following notice to accompany easyXDM: * * http://easyxdm.net/ * Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) { /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */ var global = this; var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded var emptyFn = Function.prototype; var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4) var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global) var easyXDM = {}; var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite var IFRAME_PREFIX = "easyXDM_"; var HAS_NAME_PROPERTY_BUG; var useHash = false; // whether to use the hash over the query var flashVersion; // will be set if using flash var HAS_FLASH_THROTTLED_BUG; // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(object, property){ var t = typeof object[property]; return t == 'function' || (!!(t == 'object' && object[property])) || t == 'unknown'; } function isHostObject(object, property){ return !!(typeof(object[property]) == 'object' && object[property]); } // end // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ function isArray(o){ return Object.prototype.toString.call(o) === '[object Array]'; } // end function hasFlash(){ try { var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1); HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0; activeX = null; return true; } catch (notSupportedException) { return false; } } /* * Cross Browser implementation for adding and removing event listeners. */ var on, un; if (isHostMethod(window, "addEventListener")) { on = function(target, type, listener){ target.addEventListener(type, listener, false); }; un = function(target, type, listener){ target.removeEventListener(type, listener, false); }; } else if (isHostMethod(window, "attachEvent")) { on = function(object, sEvent, fpNotify){ object.attachEvent("on" + sEvent, fpNotify); }; un = function(object, sEvent, fpNotify){ object.detachEvent("on" + sEvent, fpNotify); }; } else { throw new Error("Browser not supported"); } /* * Cross Browser implementation of DOMContentLoaded. */ var domIsReady = false, domReadyQueue = [], readyState; if ("readyState" in document) { // If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and // 'interactive' (HTML5 specs, recent WebKit builds) states. // https://bugs.webkit.org/show_bug.cgi?id=45119 readyState = document.readyState; domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive")); } else { // If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately // when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not. // We only need a body to add elements to, so the existence of document.body is enough for us. domIsReady = !!document.body; } function dom_onReady(){ if (domIsReady) { return; } domIsReady = true; for (var i = 0; i < domReadyQueue.length; i++) { domReadyQueue[i](); } domReadyQueue.length = 0; } if (!domIsReady) { if (isHostMethod(window, "addEventListener")) { on(document, "DOMContentLoaded", dom_onReady); } else { on(document, "readystatechange", function(){ if (document.readyState == "complete") { dom_onReady(); } }); if (document.documentElement.doScroll && window === top) { var doScrollCheck = function(){ if (domIsReady) { return; } // http://javascript.nwbox.com/IEContentLoaded/ try { document.documentElement.doScroll("left"); } catch (e) { setTimeout(doScrollCheck, 1); return; } dom_onReady(); }; doScrollCheck(); } } // A fallback to window.onload, that will always work on(window, "load", dom_onReady); } /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {Object} scope An optional scope for the function to be called with. */ function whenReady(fn, scope){ if (domIsReady) { fn.call(scope); return; } domReadyQueue.push(function(){ fn.call(scope); }); } /** * Returns an instance of easyXDM from the parent window with * respect to the namespace. * * @return An instance of easyXDM (in the parent window) */ function getParentObject(){ var obj = parent; if (namespace !== "") { for (var i = 0, ii = namespace.split("."); i < ii.length; i++) { obj = obj[ii[i]]; } } return obj.easyXDM; } /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ function noConflict(ns){ window.easyXDM = _easyXDM; namespace = ns; if (namespace) { IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_"; } return easyXDM; } /* * Methods for working with URLs */ /** * Get the domain name from a url. * @param {String} url The url to extract the domain from. * @return The domain part of the url. * @type {String} */ function getDomainName(url){ return url.match(reURI)[3]; } /** * Get the port for a given URL, or "" if none * @param {String} url The url to extract the port from. * @return The port part of the url. * @type {String} */ function getPort(url){ return url.match(reURI)[4] || ""; } /** * Returns a string containing the schema, domain and if present the port * @param {String} url The url to extract the location from * @return {String} The location part of the url */ function getLocation(url){ var m = url.toLowerCase().match(reURI); var proto = m[2], domain = m[3], port = m[4] || ""; if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) { port = ""; } return proto + "//" + domain + port; } /** * Resolves a relative url into an absolute one. * @param {String} url The path to resolve. * @return {String} The resolved url. */ function resolveUrl(url){ // replace all // except the one in proto with / url = url.replace(reDoubleSlash, "$1/"); // If the url is a valid url we do nothing if (!url.match(/^(http||https):\/\//)) { // If this is a relative path var path = (url.substring(0, 1) === "/") ? "" : location.pathname; if (path.substring(path.length - 1) !== "/") { path = path.substring(0, path.lastIndexOf("/") + 1); } url = location.protocol + "//" + location.host + path + url; } // reduce all 'xyz/../' to just '' while (reParent.test(url)) { url = url.replace(reParent, ""); } return url; } /** * Appends the parameters to the given url.<br/> * The base url can contain existing query parameters. * @param {String} url The base url. * @param {Object} parameters The parameters to add. * @return {String} A new valid url with the parameters appended. */ function appendQueryParameters(url, parameters){ var hash = "", indexOf = url.indexOf("#"); if (indexOf !== -1) { hash = url.substring(indexOf); url = url.substring(0, indexOf); } var q = []; for (var key in parameters) { if (parameters.hasOwnProperty(key)) { q.push(key + "=" + encodeURIComponent(parameters[key])); } } return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash; } // build the query object either from location.query, if it contains the xdm_e argument, or from location.hash var query = (function(input){ input = input.substring(1).split("&"); var data = {}, pair, i = input.length; while (i--) { pair = input[i].split("="); data[pair[0]] = decodeURIComponent(pair[1]); } return data; }(/xdm_e=/.test(location.search) ? location.search : location.hash)); /* * Helper methods */ /** * Helper for checking if a variable/property is undefined * @param {Object} v The variable to test * @return {Boolean} True if the passed variable is undefined */ function undef(v){ return typeof v === "undefined"; } /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ var getJSON = function(){ var cached = {}; var obj = { a: [1, 2, 3] }, json = "{\"a\":[1,2,3]}"; if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) { // this is a working JSON instance return JSON; } if (Object.toJSON) { if (Object.toJSON(obj).replace((/\s/g), "") === json) { // this is a working stringify method cached.stringify = Object.toJSON; } } if (typeof String.prototype.evalJSON === "function") { obj = json.evalJSON(); if (obj.a && obj.a.length === 3 && obj.a[2] === 3) { // this is a working parse method cached.parse = function(str){ return str.evalJSON(); }; } } if (cached.stringify && cached.parse) { // Only memoize the result if we have valid instance getJSON = function(){ return cached; }; return cached; } return null; }; /** * Applies properties from the source object to the target object.<br/> * @param {Object} target The target of the properties. * @param {Object} source The source of the properties. * @param {Boolean} noOverwrite Set to True to only set non-existing properties. */ function apply(destination, source, noOverwrite){ var member; for (var prop in source) { if (source.hasOwnProperty(prop)) { if (prop in destination) { member = source[prop]; if (typeof member === "object") { apply(destination[prop], member, noOverwrite); } else if (!noOverwrite) { destination[prop] = source[prop]; } } else { destination[prop] = source[prop]; } } } return destination; } // This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName]. function testForNamePropertyBug(){ var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input")); input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name]; document.body.removeChild(form); } /** * Creates a frame and appends it to the DOM. * @param config {object} This object can have the following properties * <ul> * <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li> * <li> {object} attr The attributes that should be set on the frame.</li> * <li> {DOMElement} container Its parent element (Optional).</li> * <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li> * </ul> * @return The frames DOMElement * @type DOMElement */ function createFrame(config){ if (undef(HAS_NAME_PROPERTY_BUG)) { testForNamePropertyBug(); } var frame; // This is to work around the problems in IE6/7 with setting the name property. // Internally this is set as 'submitName' instead when using 'iframe.name = ...' // This is not required by easyXDM itself, but is to facilitate other use cases if (HAS_NAME_PROPERTY_BUG) { frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>"); } else { frame = document.createElement("IFRAME"); frame.name = config.props.name; } frame.id = frame.name = config.props.name; delete config.props.name; if (config.onLoad) { on(frame, "load", config.onLoad); } if (typeof config.container == "string") { config.container = document.getElementById(config.container); } if (!config.container) { // This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers. apply(frame.style, { position: "absolute", top: "-2000px" }); config.container = document.body; } // HACK for some reason, IE needs the source set // after the frame has been appended into the DOM // so remove the src, and set it afterwards var src = config.props.src; delete config.props.src; // transfer properties to the frame apply(frame, config.props); frame.border = frame.frameBorder = 0; frame.allowTransparency = true; config.container.appendChild(frame); // HACK see above frame.src = src; config.props.src = src; return frame; } /** * Check whether a domain is allowed using an Access Control List. * The ACL can contain * and ? as wildcards, or can be regular expressions. * If regular expressions they need to begin with ^ and end with $. * @param {Array/String} acl The list of allowed domains * @param {String} domain The domain to test. * @return {Boolean} True if the domain is allowed, false if not. */ function checkAcl(acl, domain){ // normalize into an array if (typeof acl == "string") { acl = [acl]; } var re, i = acl.length; while (i--) { re = acl[i]; re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$")); if (re.test(domain)) { return true; } } return false; } /* * Functions related to stacks */ /** * Prepares an array of stack-elements suitable for the current configuration * @param {Object} config The Transports configuration. See easyXDM.Socket for more. * @return {Array} An array of stack-elements with the TransportElement at index 0. */ function prepareTransportStack(config){ var protocol = config.protocol, stackEls; config.isHost = config.isHost || undef(query.xdm_p); useHash = config.hash || false; if (!config.props) { config.props = {}; } if (!config.isHost) { config.channel = query.xdm_c; config.secret = query.xdm_s; config.remote = query.xdm_e; protocol = query.xdm_p; if (config.acl && !checkAcl(config.acl, config.remote)) { throw new Error("Access denied for " + config.remote); } } else { config.remote = resolveUrl(config.remote); config.channel = config.channel || "default" + channelId++; config.secret = Math.random().toString(16).substring(2); if (undef(protocol)) { if (getLocation(location.href) == getLocation(config.remote)) { /* * Both documents has the same origin, lets use direct access. */ protocol = "4"; } else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) { /* * This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+ */ protocol = "1"; } else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) { /* * The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS */ protocol = "6"; } else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) { /* * This is supported in Gecko (Firefox 1+) */ protocol = "5"; } else if (config.remoteHelper) { /* * This is supported in all browsers that retains the value of window.name when * navigating from one domain to another, and where parent.frames[foo] can be used * to get access to a frame from the same domain */ config.remoteHelper = resolveUrl(config.remoteHelper); protocol = "2"; } else { /* * This is supported in all browsers where [window].location is writable for all * The resize event will be used if resize is supported and the iframe is not put * into a container, else polling will be used. */ protocol = "0"; } } } config.protocol = protocol; // for conditional branching switch (protocol) { case "0":// 0 = HashTransport apply(config, { interval: 100, delay: 2000, useResize: true, useParent: false, usePolling: false }, true); if (config.isHost) { if (!config.local) { // If no local is set then we need to find an image hosted on the current domain var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image; var i = images.length; while (i--) { image = images[i]; if (image.src.substring(0, domain.length) === domain) { config.local = image.src; break; } } if (!config.local) { // If no local was set, and we are unable to find a suitable file, then we resort to using the current window config.local = window; } } var parameters = { xdm_c: config.channel, xdm_p: 0 }; if (config.local === window) { // We are using the current window to listen to config.usePolling = true; config.useParent = true; config.local = location.protocol + "//" + location.host + location.pathname + location.search; parameters.xdm_e = config.local; parameters.xdm_pa = 1; // use parent } else { parameters.xdm_e = resolveUrl(config.local); } if (config.container) { config.useResize = false; parameters.xdm_po = 1; // use polling } config.remote = appendQueryParameters(config.remote, parameters); } else { apply(config, { channel: query.xdm_c, remote: query.xdm_e, useParent: !undef(query.xdm_pa), usePolling: !undef(query.xdm_po), useResize: config.useParent ? false : config.useResize }); } stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({ encode: true, maxLength: 4000 - config.remote.length }), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "1": stackEls = [new easyXDM.stack.PostMessageTransport(config)]; break; case "2": stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "3": stackEls = [new easyXDM.stack.NixTransport(config)]; break; case "4": stackEls = [new easyXDM.stack.SameOriginTransport(config)]; break; case "5": stackEls = [new easyXDM.stack.FrameElementTransport(config)]; break; case "6": if (!flashVersion) { hasFlash(); } stackEls = [new easyXDM.stack.FlashTransport(config)]; break; } // this behavior is responsible for buffering outgoing messages, and for performing lazy initialization stackEls.push(new easyXDM.stack.QueueBehavior({ lazy: config.lazy, remove: true })); return stackEls; } /** * Chains all the separate stack elements into a single usable stack.<br/> * If an element is missing a necessary method then it will have a pass-through method applied. * @param {Array} stackElements An array of stack elements to be linked. * @return {easyXDM.stack.StackElement} The last element in the chain. */ function chainStack(stackElements){ var stackEl, defaults = { incoming: function(message, origin){ this.up.incoming(message, origin); }, outgoing: function(message, recipient){ this.down.outgoing(message, recipient); }, callback: function(success){ this.up.callback(success); }, init: function(){ this.down.init(); }, destroy: function(){ this.down.destroy(); } }; for (var i = 0, len = stackElements.length; i < len; i++) { stackEl = stackElements[i]; apply(stackEl, defaults, true); if (i !== 0) { stackEl.down = stackElements[i - 1]; } if (i !== len - 1) { stackEl.up = stackElements[i + 1]; } } return stackEl; } /** * This will remove a stackelement from its stack while leaving the stack functional. * @param {Object} element The elment to remove from the stack. */ function removeFromStack(element){ element.up.down = element.down; element.down.up = element.up; element.up = element.down = null; } /* * Export the main object and any other methods applicable */ /** * @class easyXDM * A javascript library providing cross-browser, cross-domain messaging/RPC. * @version 2.4.15.118 * @singleton */ apply(easyXDM, { /** * The version of the library * @type {string} */ version: "2.4.15.118", /** * This is a map containing all the query parameters passed to the document. * All the values has been decoded using decodeURIComponent. * @type {object} */ query: query, /** * @private */ stack: {}, /** * Applies properties from the source object to the target object.<br/> * @param {object} target The target of the properties. * @param {object} source The source of the properties. * @param {boolean} noOverwrite Set to True to only set non-existing properties. */ apply: apply, /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ getJSONObject: getJSON, /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {object} scope An optional scope for the function to be called with. */ whenReady: whenReady, /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ noConflict: noConflict }); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.DomHelper * Contains methods for dealing with the DOM * @singleton */ easyXDM.DomHelper = { /** * Provides a consistent interface for adding eventhandlers * @param {Object} target The target to add the event to * @param {String} type The name of the event * @param {Function} listener The listener */ on: on, /** * Provides a consistent interface for removing eventhandlers * @param {Object} target The target to remove the event from * @param {String} type The name of the event * @param {Function} listener The listener */ un: un, /** * Checks for the presence of the JSON object. * If it is not present it will use the supplied path to load the JSON2 library. * This should be called in the documents head right after the easyXDM script tag. * http://json.org/json2.js * @param {String} path A valid path to json2.js */ requiresJSON: function(path){ if (!isHostObject(window, "JSON")) { // we need to encode the < in order to avoid an illegal token error // when the script is inlined in a document. document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>'); } } }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // (function(){ // The map containing the stored functions var _map = {}; /** * @class easyXDM.Fn * This contains methods related to function handling, such as storing callbacks. * @singleton * @namespace easyXDM */ easyXDM.Fn = { /** * Stores a function using the given name for reference * @param {String} name The name that the function should be referred by * @param {Function} fn The function to store * @namespace easyXDM.fn */ set: function(name, fn){ _map[name] = fn; }, /** * Retrieves the function referred to by the given name * @param {String} name The name of the function to retrieve * @param {Boolean} del If the function should be deleted after retrieval * @return {Function} The stored function * @namespace easyXDM.fn */ get: function(name, del){ var fn = _map[name]; if (del) { delete _map[name]; } return fn; } }; }()); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.Socket * This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/> * The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/> * Internally different stacks will be used depending on the browsers features and the available parameters. * <h2>How to set up</h2> * Setting up the provider: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; local: "name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * Setting up the consumer: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; remote: "http:&#47;&#47;remotedomain/page.html", * &nbsp; remoteHelper: "http:&#47;&#47;remotedomain/name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property * and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports. * @namespace easyXDM * @constructor * @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window. * @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed. * @cfg {String} remote (Consumer only) The url to the providers document. * @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000. * @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300. * @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional. * @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional. * @cfg {Function} onReady A method that should be called when the transport is ready. Optional. * @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional. * @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/> * This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $. * If none of the patterns match an Error will be thrown. * @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>. * Properties such as 'name' and 'src' will be overrided. Optional. */ easyXDM.Socket = function(config){ // create the stack var stack = chainStack(prepareTransportStack(config).concat([{ incoming: function(message, origin){ config.onMessage(message, origin); }, callback: function(success){ if (config.onReady) { config.onReady(success); } } }])), recipient = getLocation(config.remote); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; /** * Posts a message to the remote end of the channel * @param {String} message The message to send */ this.postMessage = function(message){ stack.outgoing(message, recipient); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.Rpc * Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation * of methods to be called from the remote end.<br/> * The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/> * This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods. * <h2>How to set up</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; &#47;&#47; this configuration is equal to that used by the Socket. * &nbsp; remote: "http:&#47;&#47;remotedomain/...", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the proxy * &nbsp; &nbsp; rpc.foo(... * &nbsp; } * },{ * &nbsp; local: {..}, * &nbsp; remote: {..} * }); * </code></pre> * * <h2>Exposing functions (procedures)</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: { * &nbsp; &nbsp; nameOfMethod: { * &nbsp; &nbsp; &nbsp; method: function(arg1, arg2, success, error){ * &nbsp; &nbsp; &nbsp; &nbsp; ... * &nbsp; &nbsp; &nbsp; } * &nbsp; &nbsp; }, * &nbsp; &nbsp; &#47;&#47; with shorthand notation * &nbsp; &nbsp; nameOfAnotherMethod: function(arg1, arg2, success, error){ * &nbsp; &nbsp; } * &nbsp; }, * &nbsp; remote: {...} * }); * </code></pre> * The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/> * To send a successfull result back you can use * <pre><code> * return foo; * </pre></code> * or * <pre><code> * success(foo); * </pre></code> * To return an error you can use * <pre><code> * throw new Error("foo error"); * </code></pre> * or * <pre><code> * error("foo error"); * </code></pre> * * <h2>Defining remotely exposed methods (procedures/notifications)</h2> * The definition of the remote end is quite similar: * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: { * &nbsp; &nbsp; nameOfMethod: {} * &nbsp; } * }); * </code></pre> * To call a remote method use * <pre><code> * rpc.nameOfMethod("arg1", "arg2", function(value) { * &nbsp; alert("success: " + value); * }, function(message) { * &nbsp; alert("error: " + message + ); * }); * </code></pre> * Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/> * When called with no callback a JSON-RPC 2.0 notification will be executed. * Be aware that you will not be notified of any errors with this method. * <br/> * <h2>Specifying a custom serializer</h2> * If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library * then you can specify a custom serializer using <code>serializer: foo</code> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: {...}, * &nbsp; serializer : { * &nbsp; &nbsp; parse: function(string){ ... }, * &nbsp; &nbsp; stringify: function(object) {...} * &nbsp; } * }); * </code></pre> * If <code>serializer</code> is set then the class will not attempt to use the native implementation. * @namespace easyXDM * @constructor * @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters. * @param {Object} jsonRpcConfig The description of the interface to implement. */ easyXDM.Rpc = function(config, jsonRpcConfig){ // expand shorthand notation if (jsonRpcConfig.local) { for (var method in jsonRpcConfig.local) { if (jsonRpcConfig.local.hasOwnProperty(method)) { var member = jsonRpcConfig.local[method]; if (typeof member === "function") { jsonRpcConfig.local[method] = { method: member }; } } } } // create the stack var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), { callback: function(success){ if (config.onReady) { config.onReady(success); } } }])); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.SameOriginTransport * SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/> * This can be useful for testing and for when the main application supports both internal and external sources. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.SameOriginTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send(message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: location.protocol + "//" + location.host + location.pathname, xdm_c: config.channel, xdm_p: 4 // 4 = SameOriginTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); easyXDM.Fn.set(config.channel, function(sendFn){ send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); return function(msg){ pub.up.incoming(msg, targetOrigin); }; }); } else { send = getParentObject().Fn.get(config.channel, true)(function(msg){ pub.up.incoming(msg, targetOrigin); }); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.FlashTransport * FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. * @cfg {String} secret the pre-shared secret used to secure the communication. * @cfg {String} swf The path to the swf file * @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden. * @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed */ easyXDM.stack.FlashTransport = function(config){ var pub, // the public interface frame, send, targetOrigin, swf, swfContainer; function onMessage(message, origin){ setTimeout(function(){ pub.up.incoming(message, targetOrigin); }, 0); } /** * This method adds the SWF to the DOM and prepares the initialization of the channel */ function addSwf(domain){ // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error. var url = config.swf + "?host=" + config.isHost; var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000); // prepare the init function that will fire once the swf is ready easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){ easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild; var queue = easyXDM.stack.FlashTransport[domain].queue; for (var i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; }); if (config.swfContainer) { swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer; } else { // create the container that will hold the swf swfContainer = document.createElement('div'); // http://bugs.adobe.com/jira/browse/FP-4796 // http://tech.groups.yahoo.com/group/flexcoders/message/162365 // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? { height: "20px", width: "20px", position: "fixed", right: 0, top: 0 } : { height: "1px", width: "1px", position: "absolute", overflow: "hidden", right: 0, top: 0 }); document.body.appendChild(swfContainer); } // create the object/embed var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace; swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" + "<param name='allowScriptAccess' value='always'></param>" + "<param name='wmode' value='transparent'>" + "<param name='movie' value='" + url + "'></param>" + "<param name='flashvars' value='" + flashVars + "'></param>" + "<embed type='application/x-shockwave-flash' FlashVars='" + flashVars + "' allowScriptAccess='always' wmode='transparent' src='" + url + "' height='1' width='1'></embed>" + "</object>"; } return (pub = { outgoing: function(message, domain, fn){ swf.postMessage(config.channel, message.toString()); if (fn) { fn(); } }, destroy: function(){ try { swf.destroyChannel(config.channel); } catch (e) { } swf = null; if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = config.remote; // Prepare the code that will be run after the swf has been intialized easyXDM.Fn.set("flash_" + config.channel + "_init", function(){ setTimeout(function(){ pub.up.callback(true); }); }); // set up the omMessage handler easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage); config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths var swfdomain = getDomainName(config.swf); var fn = function(){ // set init to true in case the fn was called was invoked from a separate instance easyXDM.stack.FlashTransport[swfdomain].init = true; swf = easyXDM.stack.FlashTransport[swfdomain].swf; // create the channel swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost); if (config.isHost) { // if Flash is going to be throttled and we want to avoid this if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) { apply(config.props, { position: "fixed", right: 0, top: 0, height: "20px", width: "20px" }); } // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 6, // 6 = FlashTransport xdm_s: config.secret }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } }; if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) { // if the swf is in place and we are the consumer fn(); } else { // if the swf does not yet exist if (!easyXDM.stack.FlashTransport[swfdomain]) { // add the queue to hold the init fn's easyXDM.stack.FlashTransport[swfdomain] = { queue: [fn] }; addSwf(swfdomain); } else { easyXDM.stack.FlashTransport[swfdomain].queue.push(fn); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.PostMessageTransport * PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/> * <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. */ easyXDM.stack.PostMessageTransport = function(config){ var pub, // the public interface frame, // the remote frame, if any callerWindow, // the window that we will call with targetOrigin; // the domain to communicate with /** * Resolves the origin from the event object * @private * @param {Object} event The messageevent * @return {String} The scheme, host and port of the origin */ function _getOrigin(event){ if (event.origin) { // This is the HTML5 property return getLocation(event.origin); } if (event.uri) { // From earlier implementations return getLocation(event.uri); } if (event.domain) { // This is the last option and will fail if the // origin is not using the same schema as we are return location.protocol + "//" + event.domain; } throw "Unable to retrieve the origin of the event"; } /** * This is the main implementation for the onMessage event.<br/> * It checks the validity of the origin and passes the message on if appropriate. * @private * @param {Object} event The messageevent */ function _window_onMessage(event){ var origin = _getOrigin(event); if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") { pub.up.incoming(event.data.substring(config.channel.length + 1), origin); } } return (pub = { outgoing: function(message, domain, fn){ callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin); if (fn) { fn(); } }, destroy: function(){ un(window, "message", _window_onMessage); if (frame) { callerWindow = null; frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // add the event handler for listening var waitForReady = function(event){ if (event.data == config.channel + "-ready") { // replace the eventlistener callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document; un(window, "message", waitForReady); on(window, "message", _window_onMessage); setTimeout(function(){ pub.up.callback(true); }, 0); } }; on(window, "message", waitForReady); // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 1 // 1 = PostMessage }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } else { // add the event handler for listening on(window, "message", _window_onMessage); callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document; callerWindow.postMessage(config.channel + "-ready", targetOrigin); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.FrameElementTransport * FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/> * Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.FrameElementTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send.call(this, message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 5 // 5 = FrameElementTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); frame.fn = function(sendFn){ delete frame.fn; send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); // remove the function so that it cannot be used to overwrite the send function later on return function(msg){ pub.up.incoming(msg, targetOrigin); }; }; } else { // This is to mitigate origin-spoofing if (document.referrer && getLocation(document.referrer) != query.xdm_e) { window.top.location = query.xdm_e; } send = window.frameElement.fn(function(msg){ pub.up.incoming(msg, targetOrigin); }); pub.up.callback(true); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.NameTransport * NameTransport uses the window.name property to relay data. * The <code>local</code> parameter needs to be set on both the consumer and provider,<br/> * and the <code>remoteHelper</code> parameter needs to be set on the consumer. * @constructor * @param {Object} config The transports configuration. * @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host. * @namespace easyXDM.stack */ easyXDM.stack.NameTransport = function(config){ var pub; // the public interface var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl; function _sendMessage(message){ var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel; callerWindow.contentWindow.sendMessage(message, url); } function _onReady(){ if (isHost) { if (++readyCount === 2 || !isHost) { pub.up.callback(true); } } else { _sendMessage("ready"); pub.up.callback(true); } } function _onMessage(message){ pub.up.incoming(message, remoteOrigin); } function _onLoad(){ if (callback) { setTimeout(function(){ callback(true); }, 0); } } return (pub = { outgoing: function(message, domain, fn){ callback = fn; _sendMessage(message); }, destroy: function(){ callerWindow.parentNode.removeChild(callerWindow); callerWindow = null; if (isHost) { remoteWindow.parentNode.removeChild(remoteWindow); remoteWindow = null; } }, onDOMReady: function(){ isHost = config.isHost; readyCount = 0; remoteOrigin = getLocation(config.remote); config.local = resolveUrl(config.local); if (isHost) { // Register the callback easyXDM.Fn.set(config.channel, function(message){ if (isHost && message === "ready") { // Replace the handler easyXDM.Fn.set(config.channel, _onMessage); _onReady(); } }); // Set up the frame that points to the remote instance remoteUrl = appendQueryParameters(config.remote, { xdm_e: config.local, xdm_c: config.channel, xdm_p: 2 }); apply(config.props, { src: remoteUrl + '#' + config.channel, name: IFRAME_PREFIX + config.channel + "_provider" }); remoteWindow = createFrame(config); } else { config.remoteHelper = config.remote; easyXDM.Fn.set(config.channel, _onMessage); } // Set up the iframe that will be used for the transport callerWindow = createFrame({ props: { src: config.local + "#_4" + config.channel }, onLoad: function onLoad(){ // Remove the handler var w = callerWindow || this; un(w, "load", onLoad); easyXDM.Fn.set(config.channel + "_load", _onLoad); (function test(){ if (typeof w.contentWindow.sendMessage == "function") { _onReady(); } else { setTimeout(test, 50); } }()); } }); }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.HashTransport * HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String/Window} local The url to the local file used for proxying messages, or the local window. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. * @cfg {Number} interval The interval used when polling for messages. */ easyXDM.stack.HashTransport = function(config){ var pub; var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow; var useParent, _remoteOrigin; function _sendMessage(message){ if (!_callerWindow) { return; } var url = config.remote + "#" + (_msgNr++) + "_" + message; ((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url; } function _handleHash(hash){ _lastMsg = hash; pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin); } /** * Checks location.hash for a new message and relays this to the receiver. * @private */ function _pollHash(){ if (!_listenerWindow) { return; } var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#"); if (indexOf != -1) { hash = href.substring(indexOf); } if (hash && hash != _lastMsg) { _handleHash(hash); } } function _attachListeners(){ _timer = setInterval(_pollHash, pollInterval); } return (pub = { outgoing: function(message, domain){ _sendMessage(message); }, destroy: function(){ window.clearInterval(_timer); if (isHost || !useParent) { _callerWindow.parentNode.removeChild(_callerWindow); } _callerWindow = null; }, onDOMReady: function(){ isHost = config.isHost; pollInterval = config.interval; _lastMsg = "#" + config.channel; _msgNr = 0; useParent = config.useParent; _remoteOrigin = getLocation(config.remote); if (isHost) { config.props = { src: config.remote, name: IFRAME_PREFIX + config.channel + "_provider" }; if (useParent) { config.onLoad = function(){ _listenerWindow = window; _attachListeners(); pub.up.callback(true); }; } else { var tries = 0, max = config.delay / 50; (function getRef(){ if (++tries > max) { throw new Error("Unable to reference listenerwindow"); } try { _listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"]; } catch (ex) { } if (_listenerWindow) { _attachListeners(); pub.up.callback(true); } else { setTimeout(getRef, 50); } }()); } _callerWindow = createFrame(config); } else { _listenerWindow = window; _attachListeners(); if (useParent) { _callerWindow = parent; pub.up.callback(true); } else { apply(config, { props: { src: config.remote + "#" + config.channel + new Date(), name: IFRAME_PREFIX + config.channel + "_consumer" }, onLoad: function(){ pub.up.callback(true); } }); _callerWindow = createFrame(config); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.ReliableBehavior * This is a behavior that tries to make the underlying transport reliable by using acknowledgements. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. */ easyXDM.stack.ReliableBehavior = function(config){ var pub, // the public interface callback; // the callback to execute when we have a confirmed success/failure var idOut = 0, idIn = 0, currentMessage = ""; return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(","); message = message.substring(indexOf + 1); if (ack[0] == idOut) { currentMessage = ""; if (callback) { callback(true); } } if (message.length > 0) { pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin); if (idIn != ack[1]) { idIn = ack[1]; pub.up.incoming(message, origin); } } }, outgoing: function(message, origin, fn){ currentMessage = message; callback = fn; pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.QueueBehavior * This is a behavior that enables queueing of messages. <br/> * It will buffer incoming messages and dispach these as fast as the underlying transport allows. * This will also fragment/defragment messages so that the outgoing message is never bigger than the * set length. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. Optional. * @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation. */ easyXDM.stack.QueueBehavior = function(config){ var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false; function dispatch(){ if (config.remove && queue.length === 0) { removeFromStack(pub); return; } if (waiting || queue.length === 0 || destroying) { return; } waiting = true; var message = queue.shift(); pub.down.outgoing(message.data, message.origin, function(success){ waiting = false; if (message.callback) { setTimeout(function(){ message.callback(success); }, 0); } dispatch(); }); } return (pub = { init: function(){ if (undef(config)) { config = {}; } if (config.maxLength) { maxLength = config.maxLength; doFragment = true; } if (config.lazy) { lazy = true; } else { pub.down.init(); } }, callback: function(success){ waiting = false; var up = pub.up; // in case dispatch calls removeFromStack dispatch(); up.callback(success); }, incoming: function(message, origin){ if (doFragment) { var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10); incoming += message.substring(indexOf + 1); if (seq === 0) { if (config.encode) { incoming = decodeURIComponent(incoming); } pub.up.incoming(incoming, origin); incoming = ""; } } else { pub.up.incoming(message, origin); } }, outgoing: function(message, origin, fn){ if (config.encode) { message = encodeURIComponent(message); } var fragments = [], fragment; if (doFragment) { // fragment into chunks while (message.length !== 0) { fragment = message.substring(0, maxLength); message = message.substring(fragment.length); fragments.push(fragment); } // enqueue the chunks while ((fragment = fragments.shift())) { queue.push({ data: fragments.length + "_" + fragment, origin: origin, callback: fragments.length === 0 ? fn : null }); } } else { queue.push({ data: message, origin: origin, callback: fn }); } if (lazy) { pub.down.init(); } else { dispatch(); } }, destroy: function(){ destroying = true; pub.down.destroy(); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.VerifyBehavior * This behavior will verify that communication with the remote end is possible, and will also sign all outgoing, * and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. * @cfg {Boolean} initiate If the verification should be initiated from this end. */ easyXDM.stack.VerifyBehavior = function(config){ var pub, mySecret, theirSecret, verified = false; function startVerification(){ mySecret = Math.random().toString(16).substring(2); pub.down.outgoing(mySecret); } return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"); if (indexOf === -1) { if (message === mySecret) { pub.up.callback(true); } else if (!theirSecret) { theirSecret = message; if (!config.initiate) { startVerification(); } pub.down.outgoing(message); } } else { if (message.substring(0, indexOf) === theirSecret) { pub.up.incoming(message.substring(indexOf + 1), origin); } } }, outgoing: function(message, origin, fn){ pub.down.outgoing(mySecret + "_" + message, origin, fn); }, callback: function(success){ if (config.initiate) { startVerification(); } } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.RpcBehavior * This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/> * Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything. * @namespace easyXDM.stack * @constructor * @param {Object} proxy The object to apply the methods to. * @param {Object} config The definition of the local and remote interface to implement. * @cfg {Object} local The local interface to expose. * @cfg {Object} remote The remote methods to expose through the proxy. * @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON. */ easyXDM.stack.RpcBehavior = function(proxy, config){ var pub, serializer = config.serializer || getJSON(); var _callbackCounter = 0, _callbacks = {}; /** * Serializes and sends the message * @private * @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added. */ function _send(data){ data.jsonrpc = "2.0"; pub.down.outgoing(serializer.stringify(data)); } /** * Creates a method that implements the given definition * @private * @param {Object} The method configuration * @param {String} method The name of the method * @return {Function} A stub capable of proxying the requested method call */ function _createMethod(definition, method){ var slice = Array.prototype.slice; return function(){ var l = arguments.length, callback, message = { method: method }; if (l > 0 && typeof arguments[l - 1] === "function") { //with callback, procedure if (l > 1 && typeof arguments[l - 2] === "function") { // two callbacks, success and error callback = { success: arguments[l - 2], error: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 2); } else { // single callback, success callback = { success: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 1); } _callbacks["" + (++_callbackCounter)] = callback; message.id = _callbackCounter; } else { // no callbacks, a notification message.params = slice.call(arguments, 0); } if (definition.namedParams && message.params.length === 1) { message.params = message.params[0]; } // Send the method request _send(message); }; } /** * Executes the exposed method * @private * @param {String} method The name of the method * @param {Number} id The callback id to use * @param {Function} method The exposed implementation * @param {Array} params The parameters supplied by the remote end */ function _executeMethod(method, id, fn, params){ if (!fn) { if (id) { _send({ id: id, error: { code: -32601, message: "Procedure not found." } }); } return; } var success, error; if (id) { success = function(result){ success = emptyFn; _send({ id: id, result: result }); }; error = function(message, data){ error = emptyFn; var msg = { id: id, error: { code: -32099, message: message } }; if (data) { msg.error.data = data; } _send(msg); }; } else { success = error = emptyFn; } // Call local method if (!isArray(params)) { params = [params]; } try { var result = fn.method.apply(fn.scope, params.concat([success, error])); if (!undef(result)) { success(result); } } catch (ex1) { error(ex1.message); } } return (pub = { incoming: function(message, origin){ var data = serializer.parse(message); if (data.method) { // A method call from the remote end if (config.handle) { config.handle(data, _send); } else { _executeMethod(data.method, data.id, config.local[data.method], data.params); } } else { // A method response from the other end var callback = _callbacks[data.id]; if (data.error) { if (callback.error) { callback.error(data.error); } } else if (callback.success) { callback.success(data.result); } delete _callbacks[data.id]; } }, init: function(){ if (config.remote) { // Implement the remote sides exposed methods for (var method in config.remote) { if (config.remote.hasOwnProperty(method)) { proxy[method] = _createMethod(config.remote[method], method); } } } pub.down.init(); }, destroy: function(){ for (var method in config.remote) { if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) { delete proxy[method]; } } pub.down.destroy(); } }); }; global.easyXDM = easyXDM; })(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent); /*! * F2 v1.3.3 04-07-2014 * Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org * * "F2" is 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. * * Please note that F2 ("Software") may contain third party material that Markit * On Demand Inc. has a license to use and include within the Software (the * "Third Party Material"). A list of the software comprising the Third Party Material * and the terms and conditions under which such Third Party Material is distributed * are reproduced in the ThirdPartyMaterial.md file available at: * * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md * * The inclusion of the Third Party Material in the Software does not grant, provide * nor result in you having acquiring any rights whatsoever, other than as stipulated * in the terms and conditions related to the specific Third Party Material, if any. * */ var F2; /** * Open F2 * @module f2 * @main f2 */ F2 = (function() { /** * Abosolutizes a relative URL * @method _absolutizeURI * @private * @param {e.g., location.href} base * @param {URL to absolutize} href * @returns {string} URL * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _absolutizeURI = function(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = _parseURI(href || ''); base = _parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; }; /** * Parses URI * @method _parseURI * @private * @param {The URL to parse} url * @returns {Parsed URL} string * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _parseURI = function(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); }; return { /** * A function to pass into F2.stringify which will prevent circular * reference errors when serializing objects * @method appConfigReplacer */ appConfigReplacer: function(key, value) { if (key == 'root' || key == 'ui' || key == 'height') { return undefined; } else { return value; } }, /** * The apps namespace is a place for app developers to put the javascript * class that is used to initialize their app. The javascript classes should * be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId. * It is recommended that the code be placed in a closure to help keep the * global namespace clean. * * If the class has an 'init' function, that function will be called * automatically by F2. * @property Apps * @type object * @example * F2.Apps["com_example_helloworld"] = (function() { * var App_Class = function(appConfig, appContent, root) { * this._app = appConfig; // the F2.AppConfig object * this._appContent = appContent // the F2.AppManifest.AppContent object * this.$root = $(root); // the root DOM Element that contains this app * } * * App_Class.prototype.init = function() { * // perform init actions * } * * return App_Class; * })(); * @example * F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) { * return { * init:function() { * // perform init actions * } * }; * }; * @for F2 */ Apps: {}, /** * Creates a namespace on F2 and copies the contents of an object into * that namespace optionally overwriting existing properties. * @method extend * @param {string} ns The namespace to create. Pass a falsy value to * add properties to the F2 namespace directly. * @param {object} obj The object to copy into the namespace. * @param {bool} overwrite True if object properties should be overwritten * @return {object} The created object */ extend: function (ns, obj, overwrite) { var isFunc = typeof obj === 'function'; var parts = ns ? ns.split('.') : []; var parent = this; obj = obj || {}; // ignore leading global if (parts[0] === 'F2') { parts = parts.slice(1); } // create namespaces for (var i = 0, len = parts.length; i < len; i++) { if (!parent[parts[i]]) { parent[parts[i]] = isFunc && i + 1 == len ? obj : {}; } parent = parent[parts[i]]; } // copy object into namespace if (!isFunc) { for (var prop in obj) { if (typeof parent[prop] === 'undefined' || overwrite) { parent[prop] = obj[prop]; } } } return parent; }, /** * Generates a somewhat random id * @method guid * @return {string} A random id * @for F2 */ guid: function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }, /** * Search for a value within an array. * @method inArray * @param {object} value The value to search for * @param {Array} array The array to search * @return {bool} True if the item is in the array */ inArray: function(value, array) { return jQuery.inArray(value, array) > -1; }, /** * Tests a URL to see if it's on the same domain (local) or not * @method isLocalRequest * @param {URL to test} url * @returns {bool} Whether the URL is local or not * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js */ isLocalRequest: function(url){ var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, urlLower = url.toLowerCase(), parts = rurl.exec( urlLower ), ajaxLocation, ajaxLocParts; 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; } ajaxLocation = ajaxLocation.toLowerCase(); // uh oh, the url must be relative // make it fully qualified and re-regex url if (!parts){ urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); parts = rurl.exec( urlLower ); } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation ) || []; // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) var matched = !(parts && (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); return matched; }, /** * Utility method to determine whether or not the argument passed in is or is not a native dom node. * @method isNativeDOMNode * @param {object} testObject The object you want to check as native dom node. * @return {bool} Returns true if the object passed is a native dom node. */ isNativeDOMNode: function(testObject) { var bIsNode = ( typeof Node === 'object' ? testObject instanceof Node : testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' ); var bIsElement = ( typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' ); return (bIsNode || bIsElement); }, /** * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). * @method log * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). * @param {object} [obj2]* An object to be logged * @example //Pass any object (string, int, array, object, bool) to .log() F2.log('foo'); F2.log(myArray); //Use a console method name as the first argument. F2.log('error', err); F2.log('info', 'The session ID is ' + sessionId); * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) */ log: function() { var _log; var _logMethod = 'log'; var method; var noop = function () { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); var args; while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } //if first arg is a console function, use it. //defaults to console.log() if (arguments && arguments.length > 1 && arguments[0] == method){ _logMethod = method; //remove console func from args args = Array.prototype.slice.call(arguments, 1); } } if (Function.prototype.bind) { _log = Function.prototype.bind.call(console[_logMethod], console); } else { _log = function() { Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); }; } _log.apply(this, (args || arguments)); }, /** * Wrapper to convert a JSON string to an object * @method parse * @param {string} str The JSON string to convert * @return {object} The parsed object */ parse: function(str) { return JSON.parse(str); }, /** * Wrapper to convert an object to JSON * * **Note: When using F2.stringify on an F2.AppConfig object, it is * recommended to pass F2.appConfigReplacer as the replacer function in * order to prevent circular serialization errors.** * @method stringify * @param {object} value The object to convert * @param {function|Array} replacer An optional parameter that determines * how object values are stringified for objects. It can be a function or an * array of strings. * @param {int|string} space An optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will be * packed without extra whitespace. If it is a number, it will specify the * number of spaces to indent at each level. If it is a string (such as '\t' * or '&nbsp;'), it contains the characters used to indent at each level. * @return {string} The JSON string */ stringify: function(value, replacer, space) { return JSON.stringify(value, replacer, space); }, /** * Function to get the F2 version number * @method version * @return {string} F2 version number */ version: function() { return '1.3.3'; } }; })(); /** * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. * *<p class="alert alert-block alert-warning"> *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated&mdash;but not removed&mdash;in version 1.2. They will be permanently removed in a future version of F2. *</p> * *<p class="alert alert-block alert-info"> *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. *</p> * * ### Order of Execution * * **App Rendering** * * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. * * * **App Removal** * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. * * **Error Handling** * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. * * @class F2.AppHandlers */ F2.extend('AppHandlers', (function() { // the hidden token that we will check against every time someone tries to add, remove, fire handler var _ct = F2.guid(); var _f2t = F2.guid(); var _handlerCollection = { appCreateRoot: [], appRenderBefore: [], appDestroyBefore: [], appRenderAfter: [], appDestroyAfter: [], appRender: [], appDestroy: [], appScriptLoadFailed: [] }; var _defaultMethods = { appRender: function(appConfig, appHtml) { var $root = null; // if no app root is defined use the app's outer most node if(!F2.isNativeDOMNode(appConfig.root)) { appConfig.root = jQuery(appHtml).get(0); // get a handle on the root in jQuery $root = jQuery(appConfig.root); } else { // get a handle on the root in jQuery $root = jQuery(appConfig.root); // append the app html to the root $root.append(appHtml); } // append the root to the body by default. jQuery('body').append($root); }, appDestroy: function(appInstance) { // call the apps destroy method, if it has one if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') { appInstance.app.destroy(); } // warn the Container and App Developer that even though they have a destroy method it hasn't been else if(appInstance && appInstance.app && appInstance.app.destroy) { F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); } // fade out and remove the root jQuery(appInstance.config.root).fadeOut(500, function() { jQuery(this).remove(); }); } }; var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) { // will throw an exception and stop execution if the token is invalid _validateToken(token); // create handler structure. Not all arguments properties will be populated/used. var handler = { func: (typeof(func_or_element)) ? func_or_element : null, namespace: sNamespace, domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null }; if(!handler.func && !handler.domNode) { throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); } if(handler.domNode && !bDomNodeAppropriate) { throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); } return handler; }; var _validateToken = function(sToken) { // check token against F2 and container if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } }; var _removeHandler = function(sToken, eventKey, sNamespace) { // will throw an exception and stop execution if the token is invalid _validateToken(sToken); if(!sNamespace && !eventKey) { return; } // remove by event key else if(!sNamespace && eventKey) { _handlerCollection[eventKey] = []; } // remove by namespace only else if(sNamespace && !eventKey) { sNamespace = sNamespace.toLowerCase(); for(var currentEventKey in _handlerCollection) { var eventCollection = _handlerCollection[currentEventKey]; var newEvents = []; for(var i = 0, ec = eventCollection.length; i < ec; i++) { var currentEventHandler = eventCollection[i]; if(currentEventHandler) { if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) { newEvents.push(currentEventHandler); } } } eventCollection = newEvents; } } else if(sNamespace && _handlerCollection[eventKey]) { sNamespace = sNamespace.toLowerCase(); var newHandlerCollection = []; for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) { var currentHandler = _handlerCollection[eventKey][iCounter]; if(currentHandler) { if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) { newHandlerCollection.push(currentHandler); } } } _handlerCollection[eventKey] = newHandlerCollection; } }; return { /** * Allows Container Developer to retrieve a unique token which must be passed to * all `on` and `off` methods. This function will self destruct and can only be called * one time. Container Developers must store the return value inside of a closure. * @method getToken **/ getToken: function() { // delete this method for security that way only the container has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.getToken; // return the token, which we validate against. return _ct; }, /** * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} * and additional internal methods. * @method __f2GetToken * @private **/ __f2GetToken: function() { // delete this method for security that way only the F2 internally has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.__f2GetToken; // return the token, which we validate against. return _f2t; }, /** * Allows F2 to trigger specific events internally. * @method __trigger * @private * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. **/ __trigger: function(token, eventKey) // additional arguments will likely be passed { // will throw an exception and stop execution if the token is invalid if(token != _f2t) { throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); } if(_handlerCollection && _handlerCollection[eventKey]) { // create a collection of arguments that are safe to pass to the callback. var passableArgs = []; // populate that collection with all arguments except token and eventKey for(var i = 2, j = arguments.length; i < j; i++) { passableArgs.push(arguments[i]); } if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) { _defaultMethods[eventKey].apply(F2, passableArgs); return this; } else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) { return this; } // fire all event listeners in the order that they were added. for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) { var handler = _handlerCollection[eventKey][iCounter]; // appRender where root is already defined if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) { var $appRoot = jQuery(arguments[2].root).append(arguments[3]); jQuery(handler.domNode).append($appRoot); } else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) { // set the root to the actual HTML of the app arguments[2].root = jQuery(arguments[3]).get(0); // appends the root to the dom node specified jQuery(handler.domNode).append(arguments[2].root); } else { handler.func.apply(F2, passableArgs); } } } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {HTMLElement} element Specific DOM element to which app gets appended. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRender', * document.getElementById('my_app') * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRender.myNamespace', * document.getElementById('my_app') * ); **/ /** * Allows Container Developer to add listener method that will be triggered when a specific event occurs. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRenderBefore' * function() { F2.log('before app rendered!'); } * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRenderBefore.myNamespace', * function() { F2.log('before app rendered!'); } * ); **/ on: function(token, eventKey, func_or_element) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _handlerCollection[eventKey].push( _createHandler( token, sNamespace, func_or_element, (eventKey == 'appRender') ) ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to remove listener methods for specific events * @method off * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all * listeners for the specified event type will be removed. * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.off(_token,'appRenderBefore'); * **/ off: function(token, eventKey) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _removeHandler( token, eventKey, sNamespace ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; } }; })()); F2.extend('Constants', { /** * A convenient collection of all available appHandler events. * @class F2.Constants.AppHandlers **/ AppHandlers: (function() { return { /** * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_CREATE_ROOT * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_CREATE_ROOT, * function(appConfig) * { * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER * appConfig.root = jQuery('<section></section>').get(0); * } * ); */ APP_CREATE_ROOT: 'appCreateRoot', /** * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_BEFORE, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_BEFORE: 'appRenderBefore', /** * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) * @property APP_RENDER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER, * function(appConfig, appHtml) * { * var $root = null; * * // if no app root is defined use the app's outer most node * if(!F2.isNativeDOMNode(appConfig.root)) * { * appConfig.root = jQuery(appHtml).get(0); * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * } * else * { * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * * // append the app html to the root * $root.append(appHtml); * } * * // append the root to the body by default. * jQuery('body').append($root); * } * ); */ APP_RENDER: 'appRender', /** * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_AFTER, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_AFTER: 'appRenderAfter', /** * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_BEFORE: 'appDestroyBefore', /** * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY, * function(appInstance) * { * // call the apps destroy method, if it has one * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') * { * appInstance.app.destroy(); * } * else if(appInstance && appInstance.app && appInstance.app.destroy) * { * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); * } * * // fade out and remove the root * jQuery(appInstance.config.root).fadeOut(500, function() { * jQuery(this).remove(); * }); * } * ); */ APP_DESTROY: 'appDestroy', /** * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_AFTER, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_AFTER: 'appDestroyAfter', /** * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) * @property APP_SCRIPT_LOAD_FAILED * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, * function(appConfig, scriptInfo) * { * F2.log(appConfig.appId); * } * ); */ APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' }; })() }); /** * Class stubs for documentation purposes * @main F2 */ F2.extend('', { /** * The App Class is an optional class that can be namespaced onto the * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The * [F2 Docs](../../app-development.html#app-class) * has more information on the usage of the App Class. * @class F2.App * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent * object * @param {Element} root The root DOM Element for the app */ App: function(appConfig, appContent, root) { return { /** * An optional init function that will automatically be called when * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. * @method init * @optional */ init:function() {} }; }, /** * The AppConfig object represents an app's meta data * @class F2.AppConfig */ AppConfig: { /** * The unique ID of the app. More information can be found * [here](../../app-development.html#f2-appid) * @property appId * @type string * @required */ appId: '', /** * An object that represents the context of an app * @property context * @type object */ context: {}, /** * True if the app should be requested in a single request with other apps. * @property enableBatchRequests * @type bool * @default false */ enableBatchRequests: false, /** * The height of the app. The initial height will be pulled from * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later * modified by calling * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used * for secure apps to be able to set the initial height of the iframe. * @property height * @type int */ height: 0, /** * The unique runtime ID of the app. * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property instanceId * @type string */ instanceId: '', /** * True if the app will be loaded in an iframe. This property * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object * sets isSecure = true. It will also be true if the * [container](../../container-development.html) has made the decision to * run apps in iframes. * @property isSecure * @type bool * @default false */ isSecure: false, /** * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} * object. * @property manifestUrl * @type string * @required */ manifestUrl: '', /** * The recommended maximum width in pixels that this app should be run. * **It is up to the [container](../../container-development.html) to * implement the logic to prevent an app from being run when the maxWidth * requirements are not met.** * @property maxWidth * @type int */ maxWidth: 0, /** * The recommended minimum grid size that this app should be run. This * value corresponds to the 12-grid system that is used by the * [container](../../container-development.html). This property should be * set by apps that require a certain number of columns in their layout. * @property minGridSize * @type int * @default 4 */ minGridSize: 4, /** * The recommended minimum width in pixels that this app should be run. **It * is up to the [container](../../container-development.html) to implement * the logic to prevent an app from being run when the minWidth requirements * are not met. * @property minWidth * @type int * @default 300 */ minWidth: 300, /** * The name of the app * @property name * @type string * @required */ name: '', /** * The root DOM element that contains the app * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property root * @type Element */ root: undefined, /** * The instance of F2.UI providing easy access to F2.UI methods * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property ui * @type F2.UI */ ui: undefined, /** * The views that this app supports. Available views * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The * presence of a view can be checked via * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: * * F2.inArray(F2.Constants.Views.SETTINGS, app.views) * * @property views * @type Array */ views: [] }, /** * The assets needed to render an app on the page * @class F2.AppManifest */ AppManifest: { /** * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} * objects * @property apps * @type Array * @required */ apps: [], /** * Any inline javascript tha should initially be run * @property inlineScripts * @type Array * @optional */ inlineScripts: [], /** * Urls to javascript files required by the app * @property scripts * @type Array * @optional */ scripts: [], /** * Urls to CSS files required by the app * @property styles * @type Array * @optional */ styles: [] }, /** * The AppContent object * @class F2.AppManifest.AppContent **/ AppContent: { /** * Arbitrary data to be passed along with the app * @property data * @type object * @optional */ data: {}, /** * The string of HTML representing the app * @property html * @type string * @required */ html: '', /** * A status message * @property status * @type string * @optional */ status: '' }, /** * An object containing configuration information for the * [container](../../container-development.html) * @class F2.ContainerConfig */ ContainerConfig: { /** * Allows the [container](../../container-development.html) to override how * an app's html is inserted into the page. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html * @method afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app * @return {Element} The DOM Element surrounding the app */ afterAppRender: function(appConfig, html) {}, /** * Allows the [container](../../container-development.html) to wrap an app * in extra html. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html. The extra html can provide links to edit app settings and remove an * app from the container. See * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that * should be applied to elements. * @method appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app */ appRender: function(appConfig, html) {}, /** * Allows the container to render html for an app before the AppManifest for * an app has loaded. This can be useful if the design calls for loading * icons to appear for each app before each app is loaded and rendered to * the page. * @method beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ beforeAppRender: function(appConfig) {}, /** * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. * @property debugMode * @type bool * @default false */ debugMode: false, /** * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. * @property scriptErrorTimeout * @type milliseconds * @default 7000 (7 seconds) */ scriptErrorTimeout: 7000, /** * Tells the container that it is currently running within * a secure app page * @property isSecureAppPage * @type bool */ isSecureAppPage: false, /** * Allows the container to specify which page is used when * loading a secure app. The page must reside on a different domain than the * container * @property secureAppPagePath * @type string * @for F2.ContainerConfig */ secureAppPagePath: '', /** * Specifies what views a container will provide buttons * or links to. Generally, the views will be switched via buttons or links * in the app's header. * @property supportedViews * @type Array * @required */ supportedViews: [], /** * An object containing configuration defaults for F2.UI * @class F2.ContainerConfig.UI */ UI: { /** * An object containing configuration defaults for the * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. * @class F2.ContainerConfig.UI.Mask */ Mask: { /** * The backround color of the overlay * @property backgroundColor * @type string * @default #FFF */ backgroundColor: '#FFF', /** * The path to the loading icon * @property loadingIcon * @type string */ loadingIcon: '', /** * The opacity of the background overlay * @property opacity * @type int * @default 0.6 */ opacity: 0.6, /** * Do not use inline styles for mask functinality. Instead classes will * be applied to the elements and it is up to the container provider to * implement the class definitions. * @property useClasses * @type bool * @default false */ useClasses: false, /** * The z-index to use for the overlay * @property zIndex * @type int * @default 2 */ zIndex: 2 } }, /** * Allows the container to fully override how the AppManifest request is * made inside of F2. * * @method xhr * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {function} success The function to be called if the request * succeeds * @param {function} error The function to be called if the request fails * @param {function} complete The function to be called when the request * finishes (after success and error callbacks have been executed) * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has * an `abort` function (such as the jqXHR object in jQuery) to abort the * request) * * @example * F2.init({ * xhr: function(url, appConfigs, success, error, complete) { * $.ajax({ * url: url, * type: 'POST', * data: { * params: F2.stringify(appConfigs, F2.appConfigReplacer) * }, * jsonp: false, // do not put 'callback=' in the query string * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name * dataType: 'json', * success: function(appManifest) { * // custom success logic * success(appManifest); // fire success callback * }, * error: function() { * // custom error logic * error(); // fire error callback * }, * complete: function() { * // custom complete logic * complete(); // fire complete callback * } * }); * } * }); * * @for F2.ContainerConfig */ //xhr: function(url, appConfigs, success, error, complete) {}, /** * Allows the container to override individual parts of the AppManifest * request. See properties and methods with the `xhr.` prefix. * @property xhr * @type Object * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ xhr: { /** * Allows the container to override the request data type (JSON or JSONP) * that is used for the request * @method xhr.dataType * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request data type that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ dataType: function(url, appConfigs) {}, /** * Allows the container to override the request method that is used (just * like the `type` parameter to `jQuery.ajax()`. * @method xhr.type * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request method that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ type: function(url, appConfigs) {}, /** * Allows the container to override the url that is used to request an * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} * @method xhr.url * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The url that should be used for the request * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ url: function(url, appConfigs) {} }, /** * Allows the container to override the script loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadScripts * @type function * * @example * F2.init({ * loadScripts: function(scripts,inlines,callback){ * //load scripts using $.load() for each script or require(scripts) * callback(); * } * }); */ loadScripts: function(scripts,inlines,callback){}, /** * Allows the container to override the stylesheet loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadStyles * @type function * * @example * F2.init({ * loadStyles: function(styles,callback){ * //load styles using $.load() for each stylesheet or another method * callback(); * } * }); */ loadStyles: function(styles,callback){} } }); /** * Constants used throughout the Open Financial Framework * @class F2.Constants * @static */ F2.extend('Constants', { /** * CSS class constants * @class F2.Constants.Css */ Css: (function() { /** @private */ var _PREFIX = 'f2-'; return { /** * The APP class should be applied to the DOM Element that surrounds the * entire app, including any extra html that surrounds the APP\_CONTAINER * that is inserted by the container. See the * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. * @property APP * @type string * @static * @final */ APP: _PREFIX + 'app', /** * The APP\_CONTAINER class should be applied to the outermost DOM Element * of the app. * @property APP_CONTAINER * @type string * @static * @final */ APP_CONTAINER: _PREFIX + 'app-container', /** * The APP\_TITLE class should be applied to the DOM Element that contains * the title for an app. If this class is not present, then * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. * @property APP_TITLE * @type string * @static * @final */ APP_TITLE: _PREFIX + 'app-title', /** * The APP\_VIEW class should be applied to the DOM Element that contains * a view for an app. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. * @property APP_VIEW * @type string * @static * @final */ APP_VIEW: _PREFIX + 'app-view', /** * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that * trigger an * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE * event. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. * @property APP_VIEW_TRIGGER * @type string * @static * @final */ APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', /** * The MASK class is applied to the overlay element that is created * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is * fired. * @property MASK * @type string * @static * @final */ MASK: _PREFIX + 'mask', /** * The MASK_CONTAINER class is applied to the Element that is passed into * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. * @property MASK_CONTAINER * @type string * @static * @final */ MASK_CONTAINER: _PREFIX + 'mask-container' }; })(), /** * Events constants * @class F2.Constants.Events */ Events: (function() { /** @private */ var _APP_EVENT_PREFIX = 'App.'; /** @private */ var _CONTAINER_EVENT_PREFIX = 'Container.'; return { /** * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an * app. It is up to the app developer to fire this event. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property APP_SYMBOL_CHANGE * @type string * @static * @final */ APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', /** * The APP\_WIDTH\_CHANGE event will be fired by the container when the * width of an app is changed. The app's instanceId should be concatenated * to this constant. * Returns an object with the gridSize and width in pixels: * * { gridSize:8, width:620 } * * @property APP_WIDTH_CHANGE * @type string * @static * @final */ APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', /** * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed * at the container level. This event should only be fired by the * container or container provider. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property CONTAINER_SYMBOL_CHANGE * @type string * @static * @final */ CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', /** * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when * the width of the container has changed. * @property CONTAINER_WIDTH_CHANGE * @type string * @static * @final */ CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange' }; })(), JSONP_CALLBACK: 'F2_jsonpCallback_', /** * Constants for use with cross-domain sockets * @class F2.Constants.Sockets * @protected */ Sockets: { /** * The EVENT message is sent whenever * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired * @property EVENT * @type string * @static * @final */ EVENT: '__event__', /** * The LOAD message is sent when an iframe socket initially loads. * Returns a JSON string that represents: * * [ App, AppManifest] * * @property LOAD * @type string * @static * @final */ LOAD: '__socketLoad__', /** * The RPC message is sent when a method is passed up from within a secure * app page. * @property RPC * @type string * @static * @final */ RPC: '__rpc__', /** * The RPC\_CALLBACK message is sent when a call back from an RPC method is * fired. * @property RPC_CALLBACK * @type string * @static * @final */ RPC_CALLBACK: '__rpcCallback__', /** * The UI\_RPC message is sent when a UI method called. * @property UI_RPC * @type string * @static * @final */ UI_RPC: '__uiRpc__' }, /** * The available view types to apps. The view should be specified by applying * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the * Element as well which defines what view type is represented. * The `hide` class can be applied to views that should be hidden by default. * @class F2.Constants.Views */ Views: { /** * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the * view. * @property DATA_ATTRIBUTE * @type string * @static * @final */ DATA_ATTRIBUTE: 'data-f2-view', /** * The ABOUT view gives details about the app. * @property ABOUT * @type string * @static * @final */ ABOUT: 'about', /** * The HELP view provides users with help information for using an app. * @property HELP * @type string * @static * @final */ HELP: 'help', /** * The HOME view is the main view for an app. This view should always * be provided by an app. * @property HOME * @type string * @static * @final */ HOME: 'home', /** * The REMOVE view is a special view that handles the removal of an app * from the container. * @property REMOVE * @type string * @static * @final */ REMOVE: 'remove', /** * The SETTINGS view provides users the ability to modify advanced settings * for an app. * @property SETTINGS * @type string * @static * @final */ SETTINGS: 'settings' } }); /** * Handles [Context](../../app-development.html#context) passing from * containers to apps and apps to apps. * @class F2.Events */ F2.extend('Events', (function() { // init EventEmitter var _events = new EventEmitter2({ wildcard:true }); // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); return { /** * Same as F2.Events.emit except that it will not send the event * to all sockets. * @method _socketEmit * @private * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ _socketEmit: function() { return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Execute each of the listeners that may be listening for the specified * event name in order with the list of arguments. * @method emit * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ emit: function() { F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Adds a listener that will execute n times for the event before being * removed. The listener is invoked only the first time the event is * fired, after which it is removed. * @method many * @param {string} event The event name * @param {int} timesToListen The number of times to execute the event * before being removed * @param {function} listener The function to be fired when the event is * emitted */ many: function(event, timesToListen, listener) { return _events.many(event, timesToListen, listener); }, /** * Remove a listener for the specified event. * @method off * @param {string} event The event name * @param {function} listener The function that will be removed */ off: function(event, listener) { return _events.off(event, listener); }, /** * Adds a listener for the specified event * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ on: function(event, listener){ return _events.on(event, listener); }, /** * Adds a one time listener for the event. The listener is invoked only * the first time the event is fired, after which it is removed. * @method once * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ once: function(event, listener) { return _events.once(event, listener); } }; })()); /** * Handles socket communication between the container and secure apps * @class F2.Rpc */ F2.extend('Rpc', (function(){ var _callbacks = {}; var _secureAppPagePath = ''; var _apps = {}; var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); /** * Creates a socket connection from the app to the container using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createAppToContainerSocket * @private */ var _createAppToContainerSocket = function() { var appConfig; // socket closure var isLoaded = false; // its possible for messages to be received before the socket load event has // happened. We'll save off these messages and replay them once the socket // is ready var messagePlayback = []; var socket = new easyXDM.Socket({ onMessage: function(message, origin){ // handle Socket Load if (!isLoaded && _rSocketLoad.test(message)) { message = message.replace(_rSocketLoad, ''); var appParts = F2.parse(message); // make sure we have the AppConfig and AppManifest if (appParts.length == 2) { appConfig = appParts[0]; // save socket _apps[appConfig.instanceId] = { config:appConfig, socket:socket }; // register app F2.registerApps([appConfig], [appParts[1]]); // socket message playback jQuery.each(messagePlayback, function(i, e) { _onMessage(appConfig, message, origin); }); isLoaded = true; } } else if (isLoaded) { // pass everyting else to _onMessage _onMessage(appConfig, message, origin); } else { //F2.log('socket not ready, queuing message', message); messagePlayback.push(message); } } }); }; /** * Creates a socket connection from the container to the app using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createContainerToAppSocket * @private * @param {appConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The F2.AppManifest object */ var _createContainerToAppSocket = function(appConfig, appManifest) { var container = jQuery(appConfig.root); if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { container.find('.' + F2.Constants.Css.APP_CONTAINER); } if (!container.length) { F2.log('Unable to locate app in order to establish secure connection.'); return; } var iframeProps = { scrolling:'no', style:{ width:'100%' } }; if (appConfig.height) { iframeProps.style.height = appConfig.height + 'px'; } var socket = new easyXDM.Socket({ remote: _secureAppPagePath, container: container.get(0), props:iframeProps, onMessage: function(message, origin) { // pass everything to _onMessage _onMessage(appConfig, message, origin); }, onReady: function() { socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); } }); return socket; }; /** * @method _createRpcCallback * @private * @param {string} instanceId The app's Instance ID * @param {function} callbackId The callback ID * @return {function} A function to make the RPC call */ var _createRpcCallback = function(instanceId, callbackId) { return function() { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC_CALLBACK, callbackId, [].slice.call(arguments).slice(2) ); }; }; /** * Handles messages that come across the sockets * @method _onMessage * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} message The socket message * @param {string} origin The originator */ var _onMessage = function(appConfig, message, origin) { var obj, func; function parseFunction(parent, functionName) { var path = String(functionName).split('.'); for (var i = 0; i < path.length; i++) { if (parent[path[i]] === undefined) { parent = undefined; break; } parent = parent[path[i]]; } return parent; } function parseMessage(regEx, message, instanceId) { var o = F2.parse(message.replace(regEx, '')); // if obj.callbacks // for each callback // for each params // if callback matches param // replace param with _createRpcCallback(app.instanceId, callback) if (o.params && o.params.length && o.callbacks && o.callbacks.length) { jQuery.each(o.callbacks, function(i, c) { jQuery.each(o.params, function(i, p) { if (c == p) { o.params[i] = _createRpcCallback(instanceId, c); } }); }); } return o; } // handle UI Call if (_rUiCall.test(message)) { obj = parseMessage(_rUiCall, message, appConfig.instanceId); func = parseFunction(appConfig.ui, obj.functionName); // if we found the function, call it if (func !== undefined) { func.apply(appConfig.ui, obj.params); } else { F2.log('Unable to locate UI RPC function: ' + obj.functionName); } // handle RPC } else if (_rRpc.test(message)) { obj = parseMessage(_rRpc, message, appConfig.instanceId); func = parseFunction(window, obj.functionName); if (func !== undefined) { func.apply(func, obj.params); } else { F2.log('Unable to locate RPC function: ' + obj.functionName); } // handle RPC Callback } else if (_rRpcCallback.test(message)) { obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); if (_callbacks[obj.functionName] !== undefined) { _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); delete _callbacks[obj.functionName]; } // handle Events } else if (_rEvents.test(message)) { obj = parseMessage(_rEvents, message, appConfig.instanceId); F2.Events._socketEmit.apply(F2.Events, obj); } }; /** * Registers a callback function * @method _registerCallback * @private * @param {function} callback The callback function * @return {string} The callback ID */ var _registerCallback = function(callback) { var callbackId = F2.guid(); _callbacks[callbackId] = callback; return callbackId; }; return { /** * Broadcast an RPC function to all sockets * @method broadcast * @param {string} messageType The message type * @param {Array} params The parameters to broadcast */ broadcast: function(messageType, params) { // check valid messageType var message = messageType + F2.stringify(params); jQuery.each(_apps, function(i, a) { a.socket.postMessage(message); }); }, /** * Calls a remote function * @method call * @param {string} instanceId The app's Instance ID * @param {string} messageType The message type * @param {string} functionName The name of the remote function * @param {Array} params An array of parameters to pass to the remote * function. Any functions found within the params will be treated as a * callback function. */ call: function(instanceId, messageType, functionName, params) { // loop through params and find functions and convert them to callbacks var callbacks = []; jQuery.each(params, function(i, e) { if (typeof e === 'function') { var cid = _registerCallback(e); params[i] = cid; callbacks.push(cid); } }); // check valid messageType _apps[instanceId].socket.postMessage( messageType + F2.stringify({ functionName:functionName, params:params, callbacks:callbacks }) ); }, /** * Init function which tells F2.Rpc whether it is running at the container- * level or the app-level. This method is generally called by * F2.{{#crossLink "F2/init"}}{{/crossLink}} * @method init * @param {string} [secureAppPagePath] The * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath * property */ init: function(secureAppPagePath) { _secureAppPagePath = secureAppPagePath; if (!_secureAppPagePath) { _createAppToContainerSocket(); } }, /** * Determines whether the Instance ID is considered to be 'remote'. This is * determined by checking if 1) the app has an open socket and 2) whether * F2.Rpc is running inside of an iframe * @method isRemote * @param {string} instanceId The Instance ID * @return {bool} True if there is an open socket */ isRemote: function(instanceId) { return ( // we have an app _apps[instanceId] !== undefined && // the app is secure _apps[instanceId].config.isSecure && // we can't access the iframe jQuery(_apps[instanceId].config.root).find('iframe').length === 0 ); }, /** * Creates a container-to-app or app-to-container socket for communication * @method register * @param {F2.AppConfig} [appConfig] The F2.AppConfig object * @param {F2.AppManifest} [appManifest] The F2.AppManifest object */ register: function(appConfig, appManifest) { if (!!appConfig && !!appManifest) { _apps[appConfig.instanceId] = { config:appConfig, socket:_createContainerToAppSocket(appConfig, appManifest) }; } else { F2.log('Unable to register socket connection. Please check container configuration.'); } } }; })()); F2.extend('UI', (function(){ var _containerConfig; /** * UI helper methods * @class F2.UI * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object */ var UI_Class = function(appConfig) { var _appConfig = appConfig; var $root = jQuery(appConfig.root); var _updateHeight = function(height) { height = height || jQuery(_appConfig.root).outerHeight(); if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'updateHeight', [ height ] ); } else { _appConfig.height = height; $root.find('iframe').height(_appConfig.height); } }; return { /** * Removes a overlay from an Element on the page * @method hideMask * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader */ hideMask: function(selector) { F2.UI.hideMask(_appConfig.instanceId, selector); }, /** * Helper methods for creating and using Modals * @class F2.UI.Modals * @for F2.UI */ Modals: (function(){ var _renderAlert = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Alert!</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button class="btn btn-primary btn-ok">OK</button>', '</div>', '</div>' ].join(''); }; var _renderConfirm = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Confirm</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button type="button" class="btn btn-primary btn-ok">OK</button>', '<button type="button" class="btn btn-cancel">Cancel</button">', '</div>', '</div>' ].join(''); }; return { /** * Display an alert message on the page * @method alert * @param {string} message The message to be displayed * @param {function} [callback] The callback to be fired when the user * closes the dialog * @for F2.UI.Modals */ alert: function(message, callback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.alert()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.alert', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderAlert(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-primary').on('click', function() { jQuery(modal).modal('hide').remove(); (callback || jQuery.noop)(); }); }) .modal({backdrop:true}); } }, /** * Display a confirm message on the page * @method confirm * @param {string} message The message to be displayed * @param {function} okCallback The function that will be called when the OK * button is pressed * @param {function} cancelCallback The function that will be called when * the Cancel button is pressed * @for F2.UI.Modals */ confirm: function(message, okCallback, cancelCallback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.confirm', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderConfirm(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-ok').on('click', function() { jQuery(modal).modal('hide').remove(); (okCallback || jQuery.noop)(); }); jQuery(modal).find('.btn-cancel').on('click', function() { jQuery(modal).modal('hide').remove(); (cancelCallback || jQuery.noop)(); }); }) .modal({backdrop:true}); } } }; })(), /** * Sets the title of the app as shown in the browser. Depending on the * container HTML, this method may do nothing if the container has not been * configured properly or else the container provider does not allow Title's * to be set. * @method setTitle * @params {string} title The title of the app * @for F2.UI */ setTitle: function(title) { if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'setTitle', [ title ] ); } else { jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); } }, /** * Display an ovarlay over an Element on the page * @method showMask * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ showMask: function(selector, showLoader) { F2.UI.showMask(_appConfig.instanceId, selector, showLoader); }, /** * For secure apps, this method updates the size of the iframe that * contains the app. **Note: It is recommended that app developers call * this method anytime Elements are added or removed from the DOM** * @method updateHeight * @params {int} height The height of the app */ updateHeight: _updateHeight, /** * Helper methods for creating and using Views * @class F2.UI.Views * @for F2.UI */ Views: (function(){ var _events = new EventEmitter2(); var _rValidEvents = /change/i; // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); var _isValid = function(eventName) { if (_rValidEvents.test(eventName)) { return true; } else { F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); return false; } }; return { /** * Change the current view for the app or add an event listener * @method change * @param {string|function} [input] If a string is passed in, the view * will be changed for the app. If a function is passed in, a change * event listener will be added. * @for F2.UI.Views */ change: function(input) { if (typeof input === 'function') { this.on('change', input); } else if (typeof input === 'string') { if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Views.change', [].slice.call(arguments) ); } else if (F2.inArray(input, _appConfig.views)) { jQuery('.' + F2.Constants.Css.APP_VIEW, $root) .addClass('hide') .filter('[data-f2-view="' + input + '"]', $root) .removeClass('hide'); _updateHeight(); _events.emit('change', input); } } }, /** * Removes a view event listener * @method off * @param {string} event The event name * @param {function} listener The function that will be removed * @for F2.UI.Views */ off: function(event, listener) { if (_isValid(event)) { _events.off(event, listener); } }, /** * Adds a view event listener * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted * @for F2.UI.Views */ on: function(event, listener) { if (_isValid(event)) { _events.on(event, listener); } } }; })() }; }; /** * Removes a overlay from an Element on the page * @method hideMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader * @for F2.UI */ UI_Class.hideMask = function(instanceId, selector) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.hideMask()'); return; } if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.hideMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector ] ); } else { var container = jQuery(selector); container.find('> .' + F2.Constants.Css.MASK).remove(); container.removeClass(F2.Constants.Css.MASK_CONTAINER); // if the element contains this data property, we need to reset static // position if (container.data(F2.Constants.Css.MASK_CONTAINER)) { container.css({'position':'static'}); } } }; /** * * @method init * @static * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ UI_Class.init = function(containerConfig) { _containerConfig = containerConfig; // set defaults _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); }; /** * Display an ovarlay over an Element on the page * @method showMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ UI_Class.showMask = function(instanceId, selector, showLoading) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.showMask()'); return; } if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.showMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector, showLoading ] ); } else { if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); } var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); var mask = jQuery('<div>') .height('100%' /*container.outerHeight()*/) .width('100%' /*container.outerWidth()*/) .addClass(F2.Constants.Css.MASK); // set inline styles if useClasses is false if (!_containerConfig.UI.Mask.useClasses) { mask.css({ 'background-color':_containerConfig.UI.Mask.backgroundColor, 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', 'background-position':'50% 50%', 'background-repeat':'no-repeat', 'display':'block', 'left':0, 'min-height':30, 'padding':0, 'position':'absolute', 'top':0, 'z-index':_containerConfig.UI.Mask.zIndex, 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', 'opacity':_containerConfig.UI.Mask.opacity }); } // only set the position if the container is currently static if (container.css('position') === 'static') { container.css({'position':'relative'}); // setting this data property tells hideMask to set the position // back to static container.data(F2.Constants.Css.MASK_CONTAINER, true); } // add the mask to the container container.append(mask); } }; return UI_Class; })()); /** * Root namespace of the F2 SDK * @module f2 * @class F2 */ F2.extend('', (function() { var _apps = {}; var _config = false; var _bUsesAppHandlers = false; var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); /** * Appends the app's html to the DOM * @method _afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html * @return {Element} The DOM Element that contains the app */ var _afterAppRender = function(appConfig, html) { var handler = _config.afterAppRender || function(appConfig, html) { return jQuery(html).appendTo('body'); }; var appContainer = handler(appConfig, html); if ( !! _config.afterAppRender && !appContainer) { F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); return; } else { // apply APP class and Instance ID jQuery(appContainer).addClass(F2.Constants.Css.APP); return appContainer.get(0); } }; /** * Renders the html for an app. * @method _appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html */ var _appRender = function(appConfig, html) { // apply APP_CONTAINER class html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); // optionally apply wrapper html if (_config.appRender) { html = _config.appRender(appConfig, html); } // apply APP class and instanceId return _outerHtml(html); }; /** * Rendering hook to allow containers to render some html prior to an app * loading * @method _beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ var _beforeAppRender = function(appConfig) { var handler = _config.beforeAppRender || jQuery.noop; return handler(appConfig); }; /** * Handler to inform the container that a script failed to load * @method _onScriptLoadFailure * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param scriptInfo The path of the script that failed to load or the exception info * for the inline script that failed to execute */ var _appScriptLoadFailed = function(appConfig, scriptInfo) { var handler = _config.appScriptLoadFailed || jQuery.noop; return handler(appConfig, scriptInfo); }; /** * Adds properties to the AppConfig object * @method _createAppConfig * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with * necessary properties */ var _createAppConfig = function(appConfig) { // make a copy of the app config to ensure that the original is not modified appConfig = jQuery.extend(true, {}, appConfig); // create the instanceId for the app appConfig.instanceId = appConfig.instanceId || F2.guid(); // default the views if not provided appConfig.views = appConfig.views || []; if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { appConfig.views.push(F2.Constants.Views.HOME); } return appConfig; }; /** * Adds properties to the ContainerConfig object to take advantage of defaults * @method _hydrateContainerConfig * @private * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ var _hydrateContainerConfig = function(containerConfig) { if (!containerConfig.scriptErrorTimeout) { containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; } if (containerConfig.debugMode !== true) { containerConfig.debugMode = F2.ContainerConfig.debugMode; } }; /** * Attach app events * @method _initAppEvents * @private */ var _initAppEvents = function(appConfig) { jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { event.preventDefault(); var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); // handle the special REMOVE view if (view == F2.Constants.Views.REMOVE) { F2.removeApp(appConfig.instanceId); } else { appConfig.ui.Views.change(view); } }); }; /** * Attach container Events * @method _initContainerEvents * @private */ var _initContainerEvents = function() { var resizeTimeout; var resizeHandler = function() { F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); }; jQuery(window).on('resize', function() { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(resizeHandler, 100); }); }; /** * Has the container been init? * @method _isInit * @private * @return {bool} True if the container has been init */ var _isInit = function() { return !!_config; }; /** * Instantiates each app from it's appConfig and stores that in a local private collection * @method _createAppInstance * @private * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects */ var _createAppInstance = function(appConfig, appContent) { // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // instantiate F2.App if (F2.Apps[appConfig.appId] !== undefined) { if (typeof F2.Apps[appConfig.appId] === 'function') { // IE setTimeout(function() { _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); if (_apps[appConfig.instanceId].app['init'] !== undefined) { _apps[appConfig.instanceId].app.init(); } }, 0); } else { F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); } } }; /** * Loads the app's html/css/javascript * @method loadApp * @private * @param {Array} appConfigs An array of * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects * @param {F2.AppManifest} [appManifest] The AppManifest object */ var _loadApps = function(appConfigs, appManifest) { appConfigs = [].concat(appConfigs); // check for secure app if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { _loadSecureApp(appConfigs[0], appManifest); return; } // check that the number of apps in manifest matches the number requested if (appConfigs.length != appManifest.apps.length) { F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); return; } // Fn for loading manifest Styles var _loadStyles = function(styles, cb) { // Attempt to use the user provided method if (_config.loadStyles) { _config.loadStyles(styles, cb); } else { // load styles, see #101 var stylesFragment = null, useCreateStyleSheet = !! document.createStyleSheet; jQuery.each(styles, function(i, e) { if (useCreateStyleSheet) { document.createStyleSheet(e); } else { stylesFragment = stylesFragment || []; stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>'); } }); if (stylesFragment) { jQuery('head').append(stylesFragment.join('')); } cb(); } }; // Fn for loading manifest Scripts var _loadScripts = function(scripts, cb) { // Attempt to use the user provided method if (_config.loadScripts) { _config.loadScripts(scripts, cb); } else { if (scripts.length) { var scriptCount = scripts.length; var scriptsLoaded = 0; // Check for IE10+ so that we don't rely on onreadystatechange var readyStates = ('addEventListener' in window) ? {} : { 'loaded': true, 'complete': true }; // Log and emit event for the failed (400,500) scripts var _error = function(e) { setTimeout(function() { var evtData = { src: e.target.src, appId: appConfigs[0].appId }; // Send error to console F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); // Emit event F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], evtData.src); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], evtData.src ); } }, _config.scriptErrorTimeout); // Defaults to 7000 }; // Load scripts and eval inlines once complete jQuery.each(scripts, function(i, e) { var doc = document, script = doc.createElement('script'), resourceUrl = e; // If in debugMode, add cache buster to each script URL if (_config.debugMode) { resourceUrl += '?cachebuster=' + new Date().getTime(); } // Scripts needed to be loaded in order they're defined in the AppManifest script.async = false; // Add other attrs script.src = resourceUrl; script.type = 'text/javascript'; script.charset = 'utf-8'; script.onerror = _error; // Use a closure for the load event so that we can dereference the original script script.onload = script.onreadystatechange = function(e) { e = e || window.event; // For older IE if (e.type == 'load' || readyStates[script.readyState]) { // Done, cleanup script.onload = script.onreadystatechange = script.onerror = null; // Dereference script script = null; // Are we done loading all scripts for this app? if (++scriptsLoaded === scriptCount) { cb(); } } }; doc.body.appendChild(script); }); } else { cb(); } } }; var _loadInlineScripts = function(inlines, cb) { // Attempt to use the user provided method if (_config.loadInlineScripts) { _config.loadInlineScripts(inlines, cb); } else { for (var i = 0, len = inlines.length; i < len; i++) { try { eval(inlines[i]); } catch (exception) { F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], exception); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], exception ); } } } cb(); } }; // Determine whether an element has been added to the page var elementInDocument = function(element) { if (element) { while (element.parentNode) { element = element.parentNode; if (element === document) { return true; } } } return false; }; // Fn for loading manifest app html var _loadHtml = function(apps) { jQuery.each(apps, function(i, a) { if (!_bUsesAppHandlers) { // load html and save the root node appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfigs[i], // the app config _outerHtml(a.html) ); var appId = appConfigs[i].appId; var root = appConfigs[i].root; if (!root) { throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); } if (!elementInDocument(root)) { throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfigs[i] // the app config ); if (!F2.isNativeDOMNode(root)) { throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); } $(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId); } // init events _initAppEvents(appConfigs[i]); }); }; // Pull out the manifest data var scripts = appManifest.scripts || []; var styles = appManifest.styles || []; var inlines = appManifest.inlineScripts || []; var apps = appManifest.apps || []; // Finally, load the styles, html, and scripts _loadStyles(styles, function() { // Put the html on the page _loadHtml(apps); // Add the script content to the page _loadScripts(scripts, function() { // Load any inline scripts _loadInlineScripts(inlines, function() { // Create the apps jQuery.each(appConfigs, function(i, a) { _createAppInstance(a, appManifest.apps[i]); }); }); }); }); }; /** * Loads the app's html/css/javascript into an iframe * @method loadSecureApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the * page. */ var _loadSecureApp = function(appConfig, appManifest) { // make sure the container is configured for secure apps if (_config.secureAppPagePath) { if (!_bUsesAppHandlers) { // create the html container for the iframe appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>')); } else { var $root = jQuery(appConfig.root); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfig, // the app config appManifest.html ); if ($root.parents('body:first').length === 0) { throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfig // the app config ); if (!appConfig.root) { throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } if (!F2.isNativeDOMNode(appConfig.root)) { throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId); } // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // init events _initAppEvents(appConfig); // create RPC socket F2.Rpc.register(appConfig, appManifest); } else { F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); } }; var _outerHtml = function(html) { return jQuery('<div></div>').append(html).html(); }; /** * Checks if the app is valid * @method _validateApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @returns {bool} True if the app is valid */ var _validateApp = function(appConfig) { // check for valid app configurations if (!appConfig.appId) { F2.log('"appId" missing from app object'); return false; } else if (!appConfig.root && !appConfig.manifestUrl) { F2.log('"manifestUrl" missing from app object'); return false; } return true; }; /** * Checks if the ContainerConfig is valid * @method _validateContainerConfig * @private * @returns {bool} True if the config is valid */ var _validateContainerConfig = function() { if (_config) { if (_config.xhr) { if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { throw ('ContainerConfig.xhr should be a function or an object'); } if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { throw ('ContainerConfig.xhr.dataType should be a function'); } if (_config.xhr.type && typeof _config.xhr.type !== 'function') { throw ('ContainerConfig.xhr.type should be a function'); } if (_config.xhr.url && typeof _config.xhr.url !== 'function') { throw ('ContainerConfig.xhr.url should be a function'); } } } return true; }; return { /** * Gets the current list of apps in the container * @method getContainerState * @returns {Array} An array of objects containing the appId */ getContainerState: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerState()'); return; } return jQuery.map(_apps, function(app) { return { appId: app.config.appId }; }); }, /** * Initializes the container. This method must be called before performing * any other actions in the container. * @method init * @param {F2.ContainerConfig} config The configuration object */ init: function(config) { _config = config || {}; _validateContainerConfig(); _hydrateContainerConfig(_config); // dictates whether we use the old logic or the new logic. // TODO: Remove in v2.0 _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); // only establish RPC connection if the container supports the secure app page if ( !! _config.secureAppPagePath || _config.isSecureAppPage) { F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false); } F2.UI.init(_config); if (!_config.isSecureAppPage) { _initContainerEvents(); } }, /** * Has the container been init? * @method isInit * @return {bool} True if the container has been init */ isInit: _isInit, /** * Begins the loading process for all apps and/or initialization process for pre-loaded apps. * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will * contain the app's unique instanceId within the container. If the * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered * to be a pre-loaded app and will be handled accordingly. Optionally, the * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those * assets will be used instead of making a request. * @method registerApps * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {Array} [appManifests] An array of * {{#crossLink "F2.AppManifest"}}{{/crossLink}} * objects. This array must be the same length as the apps array that is * objects. This array must be the same length as the apps array that is * passed in. This can be useful if apps are loaded on the server-side and * passed down to the client. * @example * Traditional App requests. * * // Traditional f2 app configs * var arConfigs = [ * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app2', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Pre-loaded and tradition apps mixed. * * // Pre-loaded apps and traditional f2 app configs * // you can preload the same app multiple times as long as you have a unique root for each * var arConfigs = [ * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-1', * manifestUrl: '' * }, * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-2', * manifestUrl: '' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Apps with predefined manifests. * * // Traditional f2 app configs * var arConfigs = [ * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app2', context: {}} * ]; * * // Pre requested manifest responses * var arManifests = [ * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App 2!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/App2Class.js'], * styles: ['http://www.domain.com/css/App2Styles.css'] * } * ]; * * F2.init(); * F2.registerApps(arConfigs, arManifests); */ registerApps: function(appConfigs, appManifests) { if (!_isInit()) { F2.log('F2.init() must be called before F2.registerApps()'); return; } else if (!appConfigs) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; } var appStack = []; var batches = {}; var callbackStack = {}; var haveManifests = false; appConfigs = [].concat(appConfigs); appManifests = [].concat(appManifests || []); haveManifests = !! appManifests.length; // appConfigs must have a length if (!appConfigs.length) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; // ensure that the array of apps and manifests are qual } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { F2.log('The length of "apps" does not equal the length of "appManifests"'); return; } // validate each app and assign it an instanceId // then determine which apps can be batched together jQuery.each(appConfigs, function(i, a) { // add properties and methods a = _createAppConfig(a); // Will set to itself, for preloaded apps, or set to null for apps that aren't already // on the page. a.root = a.root || null; // we validate the app after setting the root property because pre-load apps do no require // manifest url if (!_validateApp(a)) { return; // move to the next app } // save app _apps[a.instanceId] = { config: a }; // If the root property is defined then this app is considered to be preloaded and we will // run it through that logic. if (a.root) { if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) { F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); F2.log('AppConfig instance:', a); throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); } else if (jQuery(a.root).length != 1) { F2.log('AppConfig invalid for pre-load, root not unique'); F2.log('AppConfig instance:', a); F2.log('Number of dom node instances:', jQuery(a.root).length); throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); } // instantiate F2.App _createAppInstance(a); // init events _initAppEvents(a); // Continue on in the .each loop, no need to continue because the app is on the page // the js in initialized, and it is ready to role. return; // equivalent to continue in .each } if (!_bUsesAppHandlers) { // fire beforeAppRender a.root = _beforeAppRender(a); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_CREATE_ROOT, a // the app config ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_BEFORE, a // the app config ); } // if we have the manifest, go ahead and load the app if (haveManifests) { _loadApps(a, appManifests[i]); } else { // check if this app can be batched if (a.enableBatchRequests && !a.isSecure) { batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; batches[a.manifestUrl.toLowerCase()].push(a); } else { appStack.push({ apps: [a], url: a.manifestUrl }); } } }); // we don't have the manifests, go ahead and load them if (!haveManifests) { // add the batches to the appStack jQuery.each(batches, function(i, b) { appStack.push({ url: i, apps: b }); }); // if an app is being loaded more than once on the page, there is the // potential that the jsonp callback will be clobbered if the request // for the AppManifest for the app comes back at the same time as // another request for the same app. We'll create a callbackStack // that will ensure that requests for the same app are loaded in order // rather than at the same time jQuery.each(appStack, function(i, req) { // define the callback function based on the first app's App ID var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; // push the request onto the callback stack callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; callbackStack[jsonpCallback].push(req); }); // loop through each item in the callback stack and make the request // for the AppManifest. When the request is complete, pop the next // request off the stack and make the request. jQuery.each(callbackStack, function(i, requests) { var manifestRequest = function(jsonpCallback, req) { if (!req) { return; } // setup defaults and callbacks var url = req.url, type = 'GET', dataType = 'jsonp', completeFunc = function() { manifestRequest(i, requests.pop()); }, errorFunc = function() { jQuery.each(req.apps, function(idx, item) { F2.log('Removed failed ' + item.name + ' app', item); F2.removeApp(item.instanceId); }); }, successFunc = function(appManifest) { _loadApps(req.apps, appManifest); }; // optionally fire xhr overrides if (_config.xhr && _config.xhr.dataType) { dataType = _config.xhr.dataType(req.url, req.apps); if (typeof dataType !== 'string') { throw ('ContainerConfig.xhr.dataType should return a string'); } } if (_config.xhr && _config.xhr.type) { type = _config.xhr.type(req.url, req.apps); if (typeof type !== 'string') { throw ('ContainerConfig.xhr.type should return a string'); } } if (_config.xhr && _config.xhr.url) { url = _config.xhr.url(req.url, req.apps); if (typeof url !== 'string') { throw ('ContainerConfig.xhr.url should return a string'); } } // setup the default request function if an override is not present var requestFunc = _config.xhr; if (typeof requestFunc !== 'function') { requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { jQuery.ajax({ url: url, type: type, data: { params: F2.stringify(req.apps, F2.appConfigReplacer) }, jsonp: false, // do not put 'callback=' in the query string jsonpCallback: jsonpCallback, // Unique function name dataType: dataType, success: successCallback, error: function(jqxhr, settings, exception) { F2.log('Failed to load app(s)', exception.toString(), req.apps); errorCallback(); }, complete: completeCallback }); }; } requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); }; manifestRequest(i, requests.pop()); }); } }, /** * Removes all apps from the container * @method removeAllApps */ removeAllApps: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeAllApps()'); return; } jQuery.each(_apps, function(i, a) { F2.removeApp(a.config.instanceId); }); }, /** * Removes an app from the container * @method removeApp * @param {string} instanceId The app's instanceId */ removeApp: function(instanceId) { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeApp()'); return; } if (_apps[instanceId]) { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_BEFORE, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_AFTER, _apps[instanceId] // the app instance ); delete _apps[instanceId]; } } }; })()); exports.F2 = F2; if (typeof define !== 'undefined' && define.amd) { define(function() { return F2; }); } })(typeof exports !== 'undefined' ? exports : window);
test/fixtures/mjs-support/src/index.js
jdcrensh/create-react-app
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
webclient/auth/register.js
souravDutta123/Cognitive-Assistant
import React from 'react' import axios from 'axios'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import Divider from 'material-ui/Divider'; import FontIcon from 'material-ui/FontIcon'; import DatePicker from 'material-ui/DatePicker'; import Snackbar from 'material-ui/Snackbar'; import Paper from 'material-ui/Paper'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { browserHistory,Link } from 'react-router'; const styles={ headerStyle:{ color: '#999', textAlign: 'left' }, paperStyle:{ height: 'auto', width: 'auto', padding: '20px', marginRight: 'auto', marginLeft: 'auto', borderRadius: '5px', textAlign: "center", }, divStyle1:{ textAlign: 'center', }, divStyle2:{ textAlign: 'center', height: window.innerHeight+'px', backgroundColor: '#eee', }, signUpButtonStyle: { width: '300px', }, flatButtonStyle:{ padding: '10px', height: '50px', fontSize: '20px', }, buttonStyle:{ padding: '10px', width: '50%', backgroundColor:'#F57C00', borderRadius: '4px', }, buttonLabelStyle:{ color: '#fff', }, } class Register extends React.Component { constructor(props) { super(props); this.state = { name: '', dateOfBirth: {}, email: "", username: '', password: "", repassword: "", errorname: '', errordateOfBirth: "", erroremail:"", errorusername: '', errorpassword: "", errorrepassword: "", open: false, message: "", }; this.handleInputChange = this.handleInputChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleInputChange(event) { const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value }); } handleDateChange(event,date) { this.setState({ dateOfBirth: date }); } handleKeyPress(target){ if(target.charCode == 13) { this.handleSubmit(); } } handleSubmit(event) { var errorname = (this.state.name ==='')? "Required" : ""; var errordateOfBirth = (this.state.dateOfBirth ==='')? "Required" : ""; var erroremail = (this.state.email ==='')? "Required" : ""; var errorusername = (this.state.username ==='')? "Required" : ""; var errorpassword = (this.state.password ==='')? "Required" : ""; var errorrepassword = (this.state.repassword ==='')? "Required" : ""; errorrepassword = (errorpassword !== "Required" && errorpassword !== "Required" && this.state.repassword !== this.state.password)? "Password did not match" : ""; this.setState({errorname,errordateOfBirth,erroremail,errorusername,errorpassword,errorrepassword}); var x=errorname+errordateOfBirth+erroremail+errorusername+errorpassword+errorrepassword; if(x === "") { var that=this; axios.get('http://localhost:3000/credentials?username='+that.state.username) .then(function (response) { if(response.data.length === 0) { that.props.handleRegister(that.state); } else { errorusername = "Choose another username"; that.setState({errorusername}) } }) } } handleFocus(event) { const target = event.target; const name= "error"+target.name; this.setState({ [name]: "" }); } render() { return ( <MuiThemeProvider> <div className="row"> <div className="col-md-2"> </div> <div className="col-sm-12 col-md-4" style={styles.divStyle1}> <h2 style={styles.headerStyle}>Sign Up</h2> <TextField hintText="Sourav" name="name" type="text" value={this.state.name} onFocus={this.handleFocus.bind(this)} onKeyPress={this.handleKeyPress.bind(this)} onChange={this.handleInputChange} floatingLabelText="Name" errorText={this.state.errorname} fullWidth={true}/><br/> <DatePicker hintText="20-08-1994" name="dateOfBirth" mode="landscape" value={this.state.dateOfBirth} onFocus={this.handleFocus.bind(this)} onChange={this.handleDateChange.bind(this)} autoOk={true} floatingLabelText="Date Of Birth" errorText={this.state.errordateOfBirth} fullWidth={true} onKeyPress={this.handleKeyPress.bind(this)}/><br/> <TextField hintText="abc@abc.com" name="email" type="email" value={this.state.email} onFocus={this.handleFocus.bind(this)} onKeyPress={this.handleKeyPress.bind(this)} onChange={this.handleInputChange} floatingLabelText="Email" errorText={this.state.erroremail} fullWidth={true}/><br/> <TextField hintText="Sourav123" name="username" type="text" value={this.state.username} onFocus={this.handleFocus.bind(this)} onKeyPress={this.handleKeyPress.bind(this)} onChange={this.handleInputChange} floatingLabelText="Username" errorText={this.state.errorusername} fullWidth={true}/><br/> <TextField hintText="RTdsrsdEE335w" name="password" type="password" value={this.state.password} onFocus={this.handleFocus.bind(this)} onKeyPress={this.handleKeyPress.bind(this)} onChange={this.handleInputChange} floatingLabelText="Password" errorText={this.state.errorpassword} fullWidth={true}/><br/> <TextField hintText="RTdsrsdEE335w" name="repassword" type="password" value={this.state.repassword} onFocus={this.handleFocus.bind(this)} onKeyPress={this.handleKeyPress.bind(this)} onChange={this.handleInputChange} floatingLabelText="Re-Enter Password" errorText={this.state.errorrepassword} fullWidth={true}/><br/><br/> <RaisedButton label="Register" style={styles.buttonStyle} labelStyle={styles.buttonLabelStyle} backgroundColor='#F57C00' onClick={this.handleSubmit.bind(this)} fullWidth={true}/> <br/> <br/> <Link to='/Login'><FlatButton onTouchTap={this.props.onTouchTap} primary={true} style={styles.flatButtonStyle}><span>Already have an account!</span></FlatButton></Link> <Snackbar open={this.state.open} message={this.state.message} autoHideDuration={3000} /> </div> <div className="col-sm-12 col-md-6" style={styles.divStyle2}> <br/> <br/> <span>{'or'}</span> <Divider /> <RaisedButton label="Sign up with Facebook" onClick={this.handleSubmit} className="logInButtonStyle" style={styles.signUpButtonStyle}/><br/> <RaisedButton label="Sign up with Gmail" onClick={this.handleSubmit} className="logInButtonStyle" style={styles.signUpButtonStyle}/><br/> <RaisedButton icon={<FontIcon className="muidocs-icon-custom-github" />} label="Sign up with Github" onClick={this.handleSubmit} className="logInButtonStyle" style={styles.signUpButtonStyle}/><br/> <RaisedButton label="Sign up with Linked In" onClick={this.handleSubmit} className="logInButtonStyle" style={styles.signUpButtonStyle}/><br/> </div> </div> </MuiThemeProvider> ); } } export default Register;
src/svg-icons/content/content-copy.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentContentCopy = (props) => ( <SvgIcon {...props}> <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/> </SvgIcon> ); ContentContentCopy = pure(ContentContentCopy); ContentContentCopy.displayName = 'ContentContentCopy'; ContentContentCopy.muiName = 'SvgIcon'; export default ContentContentCopy;
src/components/Notification/a11yIconWarningSolid.js
wfp/ui
import React from 'react'; const a11yWarningIcon = (prefix, notificationType) => ( <svg className={`${prefix}--${notificationType}-notification__icon`} width="20" height="20" xmlns="http://www.w3.org/2000/svg"> <defs> <path d="M18.05 15.95L9.925.95a.625.625 0 0 0-1.1 0L.7 15.95a.625.625 0 0 0 0 .625.625.625 0 0 0 .55.3H17.5a.625.625 0 0 0 .55-.925z" id="a" /> <path d="M.55.006h1.406v5H.55v-5zm.7 8.119a.938.938 0 1 1 0-1.875.938.938 0 0 1 0 1.875z" id="b" /> </defs> <g fill="none" fillRule="evenodd"> <path d="M18.675 16.575l-8.125-15a.625.625 0 0 0-1.1 0l-8.125 15a.625.625 0 0 0 0 .625.625.625 0 0 0 .55.3h16.25a.625.625 0 0 0 .55-.925z" fill="#FDD13A" /> <g> <path d="M9.3 6.881h1.406v5H9.3v-5zM10 15a.938.938 0 1 1 0-1.875A.938.938 0 0 1 10 15z" fill="#171717" fillRule="nonzero" /> </g> <path d="M0 0h20v20H0z" /> </g> </svg> ); export default a11yWarningIcon;
ajax/libs/material-ui/5.0.0-alpha.4/useMediaQuery/useMediaQuery.js
cdnjs/cdnjs
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useMediaQuery; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var React = _interopRequireWildcard(require("react")); var _styles = require("@material-ui/styles"); function useMediaQuery(queryInput) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var theme = (0, _styles.useTheme)(); var props = (0, _styles.getThemeProps)({ theme: theme, name: 'MuiUseMediaQuery', props: {} }); if (process.env.NODE_ENV !== 'production') { if (typeof queryInput === 'function' && theme === null) { console.error(['Material-UI: The `query` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.'].join('\n')); } } var query = typeof queryInput === 'function' ? queryInput(theme) : queryInput; query = query.replace(/^@media( ?)/m, ''); // Wait for jsdom to support the match media feature. // All the browsers Material-UI support have this built-in. // This defensive check is here for simplicity. // Most of the time, the match media logic isn't central to people tests. var supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; var _props$options = (0, _extends2.default)({}, props, options), _props$options$defaul = _props$options.defaultMatches, defaultMatches = _props$options$defaul === void 0 ? false : _props$options$defaul, _props$options$matchM = _props$options.matchMedia, matchMedia = _props$options$matchM === void 0 ? supportMatchMedia ? window.matchMedia : null : _props$options$matchM, _props$options$noSsr = _props$options.noSsr, noSsr = _props$options$noSsr === void 0 ? false : _props$options$noSsr, _props$options$ssrMat = _props$options.ssrMatchMedia, ssrMatchMedia = _props$options$ssrMat === void 0 ? null : _props$options$ssrMat; var _React$useState = React.useState(function () { if (noSsr && supportMatchMedia) { return matchMedia(query).matches; } if (ssrMatchMedia) { return ssrMatchMedia(query).matches; } // Once the component is mounted, we rely on the // event listeners to return the correct matches value. return defaultMatches; }), match = _React$useState[0], setMatch = _React$useState[1]; React.useEffect(function () { var active = true; if (!supportMatchMedia) { return undefined; } var queryList = matchMedia(query); var updateMatch = function updateMatch() { // Workaround Safari wrong implementation of matchMedia // TODO can we remove it? // https://github.com/mui-org/material-ui/pull/17315#issuecomment-528286677 if (active) { setMatch(queryList.matches); } }; updateMatch(); queryList.addListener(updateMatch); return function () { active = false; queryList.removeListener(updateMatch); }; }, [query, matchMedia, supportMatchMedia]); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue({ query: query, match: match }); } return match; }
src/scripts/views/form/index.js
AatuPitkanen/teamboard-client-react
import page from 'page'; import React from 'react'; import Broadcaster from '../../components/broadcaster'; import FormData from '../../views/form/form-map'; import BroadcastAction from '../../actions/broadcast'; import localeMixin from '../../mixins/locale'; /** * */ export default React.createClass({ mixins: [ React.addons.LinkedStateMixin, localeMixin() ], propTypes: { formProfile: React.PropTypes.string.isRequired, boardID: React.PropTypes.string, accessCode: React.PropTypes.string }, getInitialState() { return FormData.stateVariables.reduce((state, variable) => { state[variable] = ''; return state; }, {}); }, checkPasswords(){ if(this.props.formProfile === 'registerForm' && this.state.passwordAgain.length > 7) { return this.state.passwordAgain !== this.state.passwordRegister ? <span className="fa fa-times mismatch">{this.locale('PASSWORDMISMATCH')}</span> : <span className="fa fa-check match">{this.locale('PASSWORDMATCH')}</span>; } }, renderFields(fields) { return fields.map((field, index) => { let controlattrs = { title: this.locale(field.title), pattern: field.pattern, required: field.required } return ( <section key={field.name} className="input"> <label htmlFor={field.name}> {this.locale(field.label)} </label> <input autoFocus={index === 0} name={field.name} type={field.type} {...controlattrs} valueLink={this.linkState(field.name)} /> </section> ); }); }, /** * Submit will execute in all cases other than when the passwords given in * registration do not match. */ submitPrimary(currentForm) { if(this.props.formProfile !== 'registerForm' || this.state.passwordAgain === this.state.passwordRegister) { return (event) => { if(this.props.formProfile === 'registerForm') { this.state.password = this.state.passwordRegister; } currentForm.submit(this.state); return event.preventDefault(); } } else { return (event) => { BroadcastAction.add({ type: 'Error', content: this.locale('PASSWORDMISMATCH') }); return event.preventDefault(); } } }, submitSecondary(currentForm) { return (event) => { if (this.props.formProfile !== 'guestLoginForm') { currentForm.secondary.submit(this.state, this.props.boardID, this.props.accessCode); } else { currentForm.secondary.submit(this.state, this.props.boardID, this.props.accessCode); } return event.preventDefault(); } }, submitGuest(currentForm, accessCode, boardID){ return (event) => { currentForm.submit(this.state, boardID, accessCode); return event.preventDefault(); } }, renderForm(formType) { let secondaryContent = !formType.secondary ? null : ( <section className="secondary"> <p>{this.locale(formType.secondary.description)}</p> <button className="btn-secondary" onClick={this.submitSecondary(formType, this.props.boardID, this.props.accessCode)}> {this.locale(formType.secondary.action)} </button> </section> ); let socialLogin = !formType.social ? null : ( <div> <section className="social"> <h2>{this.locale(formType.social.header)}</h2> <a className="provider" href={formType.social.facebookUrl}> <img className="provider" src={formType.social.facebookLogo} /> </a> <a className="provider" href={formType.social.googleUrl}> <img className="provider" src={formType.social.googleLogo} /> </a> </section> <p className="basic-login">{this.locale(formType.social.subHeader)}</p> </div> ); let primarySubmit = ( this.props.formProfile !== 'guestLoginForm' && this.props.formProfile !== 'userAccessForm' ) ? this.submitPrimary(formType) : this.submitGuest( formType, this.props.accessCode, this.props.boardID); return ( <div className="view view-form"> <Broadcaster /> <div className="content"> <form className="form" onSubmit={primarySubmit}> <div className="logo"> <img src="/dist/assets/img/logo.svg" /> <h1>Contriboard</h1> </div> {socialLogin} {this.renderFields(formType.fields)} {this.checkPasswords()} <input type="submit" className="btn-primary" value={this.locale(formType.action)} /> <article className="help">{this.locale(formType.help)}</article> <section className="secondary-content"> {secondaryContent} </section> </form> </div> </div> ); }, render() { return this.renderForm(FormData[this.props.formProfile]); } });
src/components/common/svg-icons/device/battery-charging-90.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging90 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z"/> </SvgIcon> ); DeviceBatteryCharging90 = pure(DeviceBatteryCharging90); DeviceBatteryCharging90.displayName = 'DeviceBatteryCharging90'; DeviceBatteryCharging90.muiName = 'SvgIcon'; export default DeviceBatteryCharging90;
src/svg-icons/file/cloud-off.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudOff = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4c-1.48 0-2.85.43-4.01 1.17l1.46 1.46C10.21 6.23 11.08 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3 0 1.13-.64 2.11-1.56 2.62l1.45 1.45C23.16 18.16 24 16.68 24 15c0-2.64-2.05-4.78-4.65-4.96zM3 5.27l2.75 2.74C2.56 8.15 0 10.77 0 14c0 3.31 2.69 6 6 6h11.73l2 2L21 20.73 4.27 4 3 5.27zM7.73 10l8 8H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h1.73z"/> </SvgIcon> ); FileCloudOff = pure(FileCloudOff); FileCloudOff.displayName = 'FileCloudOff'; FileCloudOff.muiName = 'SvgIcon'; export default FileCloudOff;
__tests__/index.ios.js
sotayamashita/wizardsLifeCounter
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
app/javascript/mastodon/features/ui/components/follow_requests_nav_link.js
cobodo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { fetchFollowRequests } from 'mastodon/actions/accounts'; import { connect } from 'react-redux'; import { NavLink, withRouter } from 'react-router-dom'; import IconWithBadge from 'mastodon/components/icon_with_badge'; import { List as ImmutableList } from 'immutable'; import { FormattedMessage } from 'react-intl'; const mapStateToProps = state => ({ count: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size, }); export default @withRouter @connect(mapStateToProps) class FollowRequestsNavLink extends React.Component { static propTypes = { dispatch: PropTypes.func.isRequired, count: PropTypes.number.isRequired, }; componentDidMount () { const { dispatch } = this.props; dispatch(fetchFollowRequests()); } render () { const { count } = this.props; if (count === 0) { return null; } return <NavLink className='column-link column-link--transparent' to='/follow_requests'><IconWithBadge className='column-link__icon' id='user-plus' count={count} /><FormattedMessage id='navigation_bar.follow_requests' defaultMessage='Follow requests' /></NavLink>; } }
react-native-life/ReactNativeLife/js/APIs/Animated/AnimatedExample.js
CaMnter/front-end-life
/** * @author CaMnter */ import React from 'react'; import { Animated, Easing, StyleSheet, Text, View } from 'react-native'; import RNTesterButton from '../../../RNTester/js/RNTesterButton'; const examples = { pagerTitle: 'Animated examples', pagerBlocks: [ { title: 'FadeInView', description: 'Uses a simple timing animation to ' + 'bring opacity from 0 to 1 when the component ' + 'mounts.', render() { class FadeInView extends React.Component { state: any; constructor(props) { super(props); this.state = { fadeAnim: new Animated.Value(0), }; } componentDidMount() { Animated.timing( this.state.fadeAnim, { toValue: 1, duration: 2000, }, ).start(); } render() { return ( <Animated.View style={{ opacity: this.state.fadeAnim, }}> {this.props.children} </Animated.View> ); } } class FadeInExample extends React.Component { state: any; constructor(props) { super(props); this.state = { show: true, }; } render() { return ( <View> <RNTesterButton onPress={() => { this.setState((state) => ( {show: !state.show} )); }}> Press to {this.state.show ? 'Hide' : 'Show'} </RNTesterButton> {this.state.show && <FadeInView> <View style={styles.content}> <Text>FadeInView</Text> </View> </FadeInView>} </View> ); } } return <FadeInExample />; }, }, { title: 'Transform Bounce', description: 'One `Animated.Value` is driven by a ' + 'spring with custom constants and mapped to an ' + 'ordered set of transforms. Each transform has ' + 'an interpolation to convert the value into the ' + 'right range and units.', render: function () { this.anim = this.anim || new Animated.Value(0); return ( <View> <RNTesterButton onPress={() => { Animated.spring(this.anim, { toValue: 0, velocity: 3, tension: -10, friction: 1, }).start(); }}> Press to Fling it! </RNTesterButton> <Animated.View style={[styles.content, { transform: [ // Array order matters { scale: this.anim.interpolate({ inputRange: [0, 1], outputRange: [1, 4], }) }, { translateX: this.anim.interpolate({ inputRange: [0, 1], outputRange: [0, 500], }) }, { rotate: this.anim.interpolate({ inputRange: [0, 1], outputRange: [ '0deg', '360deg' // 'deg' or 'rad' ], }) }, ] } ]}> <Text>Transforms!</Text> </Animated.View> </View> ); }, }, { title: 'Composite Animations with Easing', description: 'Sequence, parallel, delay, and ' + 'stagger with different easing functions.', render: function () { this.anims = this.anims || [1, 2, 3].map( () => new Animated.Value(0) ); return ( <View> <RNTesterButton onPress={() => { var timing = Animated.timing; Animated.sequence([ timing(this.anims[0], { toValue: 200, easing: Easing.linear, }), Animated.delay(400), timing(this.anims[0], { toValue: 0, easing: Easing.elastic(2), }), Animated.delay(400), Animated.stagger(200, this.anims.map((anim) => timing( anim, {toValue: 200} )).concat( this.anims.map((anim) => timing( anim, {toValue: 0} ))), ), Animated.delay(400), Animated.parallel([ Easing.inOut(Easing.quad), // Symmetric Easing.back(1.5), // Goes backwards first Easing.ease // Default bezier ].map((easing, ii) => ( timing(this.anims[ii], { toValue: 320, easing, duration: 3000, }) ))), Animated.delay(400), Animated.stagger(200, this.anims.map((anim) => timing(anim, { toValue: 0, easing: Easing.bounce, // Like a ball duration: 2000, })), ), ]).start(); }}> Press to Animate </RNTesterButton> {['Composite', 'Easing', 'Animations!'].map( (text, ii) => ( <Animated.View key={text} style={[styles.content, { left: this.anims[ii] }]}> <Text>{text}</Text> </Animated.View> ) )} </View> ); }, }, { title: 'Continuous Interactions', description: 'Gesture events, chaining, 2D ' + 'values, interrupting and transitioning ' + 'animations, etc.', render: () => ( <Text>Checkout the Gratuitous Animation App!</Text> ), } ] }; const styles = StyleSheet.create({ content: { backgroundColor: 'deepskyblue', borderWidth: 1, borderColor: 'dodgerblue', padding: 20, margin: 20, borderRadius: 10, alignItems: 'center', }, }); module.exports = {examples};
18-react-router-redux/src/components/repos.js
iproduct/course-node-express-react
import React from 'react'; import { PropTypes } from 'prop-types'; import Repo from './repo'; import { Route } from 'react-router-dom'; import { connect } from 'react-redux'; const Repos = (props) => { return ( <div> <h2>Repos</h2> <Route path="/repos/:userName/:repoName" component={Repo} /> </div> ); }; Repos.propTypes = { children: PropTypes.node } export default connect()(Repos);
html.js
pcm-ca/pcm-ca.github.io
import React from 'react' import Helmet from 'react-helmet' import { prefixLink } from 'gatsby-helpers' import { TypographyStyle, GoogleFont } from 'react-typography' import typography from './utils/typography' const BUILD_TIME = new Date().getTime() module.exports = React.createClass({ propTypes () { return { body: React.PropTypes.string, } }, render () { const head = Helmet.rewind() let css if (process.env.NODE_ENV === 'production') { css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} /> } return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png" /> <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png" /> <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png" /> <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png" /> <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png" /> <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png" /> <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png" /> <link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/manifest.json" /> <meta name="msapplication-TileColor" content="#ffffff" /> <meta name="msapplication-TileImage" content="/ms-icon-144x144.png" /> <meta name="theme-color" content="#ffffff" /> {head.title.toComponent()} {head.meta.toComponent()} <TypographyStyle typography={typography} /> <GoogleFont typography={typography} /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css" /> {css} </head> <body> <div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} /> <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} /> </body> </html> ) }, })
ajax/libs/core-js/2.0.0-alpha/library.js
sufuf3/cdnjs
/** * core-js 2.0.0-alpha * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(__e, __g, undefined){ 'use strict'; /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(33); __webpack_require__(42); __webpack_require__(44); __webpack_require__(46); __webpack_require__(48); __webpack_require__(50); __webpack_require__(51); __webpack_require__(52); __webpack_require__(53); __webpack_require__(54); __webpack_require__(55); __webpack_require__(56); __webpack_require__(57); __webpack_require__(58); __webpack_require__(59); __webpack_require__(60); __webpack_require__(61); __webpack_require__(62); __webpack_require__(64); __webpack_require__(65); __webpack_require__(66); __webpack_require__(67); __webpack_require__(68); __webpack_require__(69); __webpack_require__(70); __webpack_require__(72); __webpack_require__(73); __webpack_require__(74); __webpack_require__(76); __webpack_require__(77); __webpack_require__(78); __webpack_require__(80); __webpack_require__(81); __webpack_require__(82); __webpack_require__(83); __webpack_require__(84); __webpack_require__(85); __webpack_require__(86); __webpack_require__(87); __webpack_require__(88); __webpack_require__(89); __webpack_require__(90); __webpack_require__(91); __webpack_require__(92); __webpack_require__(94); __webpack_require__(96); __webpack_require__(100); __webpack_require__(101); __webpack_require__(103); __webpack_require__(104); __webpack_require__(108); __webpack_require__(110); __webpack_require__(111); __webpack_require__(112); __webpack_require__(113); __webpack_require__(114); __webpack_require__(115); __webpack_require__(116); __webpack_require__(117); __webpack_require__(118); __webpack_require__(119); __webpack_require__(120); __webpack_require__(121); __webpack_require__(122); __webpack_require__(128); __webpack_require__(129); __webpack_require__(132); __webpack_require__(134); __webpack_require__(136); __webpack_require__(138); __webpack_require__(139); __webpack_require__(140); __webpack_require__(147); __webpack_require__(150); __webpack_require__(151); __webpack_require__(153); __webpack_require__(154); __webpack_require__(155); __webpack_require__(156); __webpack_require__(157); __webpack_require__(158); __webpack_require__(159); __webpack_require__(160); __webpack_require__(161); __webpack_require__(162); __webpack_require__(163); __webpack_require__(164); __webpack_require__(166); __webpack_require__(167); __webpack_require__(168); __webpack_require__(169); __webpack_require__(170); __webpack_require__(171); __webpack_require__(173); __webpack_require__(174); __webpack_require__(175); __webpack_require__(176); __webpack_require__(177); __webpack_require__(179); __webpack_require__(180); __webpack_require__(182); __webpack_require__(183); __webpack_require__(184); __webpack_require__(185); __webpack_require__(186); __webpack_require__(187); __webpack_require__(190); __webpack_require__(125); __webpack_require__(192); __webpack_require__(191); __webpack_require__(193); __webpack_require__(194); __webpack_require__(195); __webpack_require__(196); __webpack_require__(197); __webpack_require__(199); __webpack_require__(200); __webpack_require__(201); __webpack_require__(203); module.exports = __webpack_require__(204); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , $export = __webpack_require__(3) , DESCRIPTORS = __webpack_require__(8) , createDesc = __webpack_require__(10) , html = __webpack_require__(11) , cel = __webpack_require__(12) , has = __webpack_require__(14) , cof = __webpack_require__(15) , invoke = __webpack_require__(16) , fails = __webpack_require__(9) , anObject = __webpack_require__(17) , aFunction = __webpack_require__(7) , isObject = __webpack_require__(13) , toObject = __webpack_require__(18) , toIObject = __webpack_require__(20) , toInteger = __webpack_require__(22) , toIndex = __webpack_require__(23) , toLength = __webpack_require__(24) , IObject = __webpack_require__(21) , IE_PROTO = __webpack_require__(25)('__proto__') , createArrayMethod = __webpack_require__(26) , arrayIndexOf = __webpack_require__(32)(false) , ObjectProto = Object.prototype , ArrayProto = Array.prototype , arraySlice = ArrayProto.slice , arrayJoin = ArrayProto.join , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , factories = {} , IE8_DOM_DEFINE; if(!DESCRIPTORS){ IE8_DOM_DEFINE = !fails(function(){ return defineProperty(cel('div'), 'a', {get: function(){ return 7; }}).a != 7; }); $.setDesc = function(O, P, Attributes){ if(IE8_DOM_DEFINE)try { return defineProperty(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)anObject(O)[P] = Attributes.value; return O; }; $.getDesc = function(O, P){ if(IE8_DOM_DEFINE)try { return getOwnDescriptor(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ anObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $export($export.S + $export.F * !DESCRIPTORS, 'Object', { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $.getDesc, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: $.setDesc, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' + 'toLocaleString,toString,valueOf').split(',') // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', 'prototype') , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = cel('iframe') , i = keysLen1 , gt = '>' , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict.prototype[keys1[i]]; return createDict(); }; var createGetKeys = function(names, length){ return function(object){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; }; var Empty = function(){}; $export($export.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: $.create = $.create || function(O, /*?*/Properties){ var result; if(O !== null){ Empty.prototype = anObject(O); result = new Empty(); Empty.prototype = null; // add "__proto__" for Object.getPrototypeOf shim result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false) }); var construct = function(F, len, args){ if(!(len in factories)){ for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $export($export.P, 'Function', { bind: function bind(that /*, args... */){ var fn = aFunction(this) , partArgs = arraySlice.call(arguments, 1); var bound = function(/* args... */){ var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); }; if(isObject(fn.prototype))bound.prototype = fn.prototype; return bound; } }); // fallback for not array-like ES3 strings and DOM objects $export($export.P + $export.F * fails(function(){ if(html)arraySlice.call(html); }), 'Array', { slice: function(begin, end){ var len = toLength(this.length) , klass = cof(this); end = end === undefined ? len : end; if(klass == 'Array')return arraySlice.call(this, begin, end); var start = toIndex(begin, len) , upTo = toIndex(end, len) , size = toLength(upTo - start) , cloned = Array(size) , i = 0; for(; i < size; i++)cloned[i] = klass == 'String' ? this.charAt(start + i) : this[start + i]; return cloned; } }); $export($export.P + $export.F * (IObject != Object), 'Array', { join: function join(separator){ return arrayJoin.call(IObject(this), separator === undefined ? ',' : separator); } }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $export($export.S, 'Array', {isArray: __webpack_require__(28)}); var createArrayReduce = function(isRight){ return function(callbackfn, memo){ aFunction(callbackfn); var O = IObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(arguments.length < 2)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; if(isRight ? index < 0 : length <= index){ throw TypeError('Reduce of empty array with no initial value'); } } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; }; }; var methodize = function($fn){ return function(arg1/*, arg2 = undefined */){ return $fn(this, arg1, arguments[1]); }; }; $export($export.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || methodize(createArrayMethod(0)), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: methodize(createArrayMethod(1)), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: methodize(createArrayMethod(2)), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: methodize(createArrayMethod(3)), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: methodize(createArrayMethod(4)), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: methodize(arrayIndexOf), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toIObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 20.3.3.1 / 15.9.4.4 Date.now() $export($export.S, 'Date', {now: function(){ return +new Date; }}); var lz = function(num){ return num > 9 ? num : '0' + num; }; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS / old WebKit has a broken implementations $export($export.P + $export.F * (fails(function(){ return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; }) || !fails(function(){ new Date(NaN).toISOString(); })), 'Date', { toISOString: function toISOString(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } }); /***/ }, /* 2 */ /***/ function(module, exports) { var $Object = Object; module.exports = { create: $Object.create, getProto: $Object.getPrototypeOf, isEnum: {}.propertyIsEnumerable, getDesc: $Object.getOwnPropertyDescriptor, setDesc: $Object.defineProperty, setDescs: $Object.defineProperties, getKeys: $Object.keys, getNames: $Object.getOwnPropertyNames, getSymbols: $Object.getOwnPropertySymbols, each: [].forEach }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(5) , ctx = __webpack_require__(6) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(param){ return this instanceof C ? new C(param) : C(param); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe module.exports = $export; /***/ }, /* 4 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 5 */ /***/ function(module, exports) { var core = module.exports = {version: '2.0.0-alpha'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(7); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 7 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(9)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 9 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 10 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(4).document && document.documentElement; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(13) , document = __webpack_require__(4).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 13 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 14 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 15 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 16 */ /***/ function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(13); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(19); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 19 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(21) , defined = __webpack_require__(19); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(15); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 22 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(22) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(22) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 25 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = __webpack_require__(6) , IObject = __webpack_require__(21) , toObject = __webpack_require__(18) , toLength = __webpack_require__(24) , asc = __webpack_require__(27); module.exports = function(TYPE, $create){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX , create = $create || asc; return function($this, callbackfn, that){ var O = toObject($this) , self = IObject(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var isObject = __webpack_require__(13) , isArray = __webpack_require__(28) , SPECIES = __webpack_require__(29)('species'); module.exports = function(original, length){ var C; if(isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; if(isObject(C)){ C = C[SPECIES]; if(C === null)C = undefined; } } return new (C === undefined ? Array : C)(length); }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(15); module.exports = Array.isArray || function(arg){ return cof(arg) == 'Array'; }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(30)('wks') , uid = __webpack_require__(25) , Symbol = __webpack_require__(4).Symbol , USE_SYMBOL = __webpack_require__(31); module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , $Symbol = global.Symbol , document = global.document || {} , GEBTN = 'getElementsByTagName'; module.exports = typeof $Symbol == 'function' && (document[GEBTN] === undefined || !__webpack_require__(9)(function(){ // Chromium 38-40 Symbol has a bug with some kinds of DOM collections var htc = document.createElement('x')[GEBTN]('y') , sym = $Symbol(); htc[sym] = 7; return htc[sym] !== 7; })); /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(20) , toLength = __webpack_require__(24) , toIndex = __webpack_require__(23); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var $ = __webpack_require__(2) , global = __webpack_require__(4) , has = __webpack_require__(14) , DESCRIPTORS = __webpack_require__(8) , $export = __webpack_require__(3) , redefine = __webpack_require__(34) , META = __webpack_require__(36).KEY , $fails = __webpack_require__(9) , shared = __webpack_require__(30) , setToStringTag = __webpack_require__(37) , uid = __webpack_require__(25) , wks = __webpack_require__(29) , keyOf = __webpack_require__(38) , $names = __webpack_require__(39) , enumKeys = __webpack_require__(40) , isArray = __webpack_require__(28) , anObject = __webpack_require__(17) , toIObject = __webpack_require__(20) , createDesc = __webpack_require__(10) , USE_NATIVE = __webpack_require__(31) , getDesc = $.getDesc , setDesc = $.setDesc , _create = $.create , getNames = $names.get , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , setter = false , HIDDEN = wks('_hidden') , isEnum = $.isEnum , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , ObjectProto = Object.prototype; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(setDesc({}, 'a', { get: function(){ return setDesc(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = getDesc(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; setDesc(it, key, D); if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc); } : setDesc; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol.prototype); sym._k = tag; DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); } }); return sym; }; var isSymbol = function(it){ return typeof it == 'symbol'; }; var $defineProperty = function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return setDesc(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key); return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toIObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = getNames(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var names = getNames(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); return result; }; var $stringify = function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , $$ = arguments , replacer, $replacer; while($$.length > i)args.push($$[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); }; var BUGGY_JSON = $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; }); // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(isSymbol(this))throw TypeError('Symbol is not a constructor'); return wrap(uid(arguments.length > 0 ? arguments[0] : undefined)); }; redefine($Symbol.prototype, 'toString', function toString(){ return this._k; }); isSymbol = function(it){ return it instanceof $Symbol; }; $.create = $create; $.isEnum = $propertyIsEnumerable; $.getDesc = $getOwnPropertyDescriptor; $.setDesc = $defineProperty; $.setDescs = $defineProperties; $.getNames = $names.get = $getOwnPropertyNames; $.getSymbols = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(41)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } } var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ return keyOf(SymbolRegistry, key); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.4 Symbol.iterator // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.13 Symbol.toStringTag // 19.4.2.14 Symbol.unscopables $.each.call(( 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + 'species,split,toPrimitive,toStringTag,unscopables' ).split(','), function(it){ var sym = wks(it); symbolStatics[it] = USE_NATIVE ? sym : wrap(sym); }); setter = true; $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', symbolStatics); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || BUGGY_JSON), 'JSON', {stringify: $stringify}); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(35); /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , createDesc = __webpack_require__(10); module.exports = __webpack_require__(8) ? function(object, key, value){ return $.setDesc(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var META = __webpack_require__(25)('meta') , isObject = __webpack_require__(13) , has = __webpack_require__(14) , setDesc = __webpack_require__(2).setDesc , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !__webpack_require__(9)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(2).setDesc , has = __webpack_require__(14) , TAG = __webpack_require__(29)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , toIObject = __webpack_require__(20); module.exports = function(object, el){ var O = toIObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(20) , getNames = __webpack_require__(2).getNames , toString = {}.toString; var windowNames = typeof window == 'object' && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return getNames(it); } catch(e){ return windowNames.slice(); } }; module.exports.get = function getOwnPropertyNames(it){ if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it); return getNames(toIObject(it)); }; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var $ = __webpack_require__(2); module.exports = function(it){ var keys = $.getKeys(it) , getSymbols = $.getSymbols; if(getSymbols){ var symbols = getSymbols(it) , isEnum = $.isEnum , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key); } return keys; }; /***/ }, /* 41 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(3); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(43)}); /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var $ = __webpack_require__(2) , toObject = __webpack_require__(18) , IObject = __webpack_require__(21); // should work with symbols and should have deterministic property order (V8 bug) module.exports = __webpack_require__(9)(function(){ var a = Object.assign , A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , $$ = arguments , $$len = $$.length , index = 1 , getKeys = $.getKeys , getSymbols = $.getSymbols , isEnum = $.isEnum; while($$len > index){ var S = IObject($$[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : Object.assign; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.10 Object.is(value1, value2) var $export = __webpack_require__(3); $export($export.S, 'Object', {is: __webpack_require__(45)}); /***/ }, /* 45 */ /***/ function(module, exports) { // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(3); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(47).set}); /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var getDesc = __webpack_require__(2).getDesc , isObject = __webpack_require__(13) , anObject = __webpack_require__(17); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(6)(Function.call, getDesc(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.5 Object.freeze(O) var isObject = __webpack_require__(13) , meta = __webpack_require__(36).onFreeze; __webpack_require__(49)('freeze', function($freeze){ return function freeze(it){ return $freeze && isObject(it) ? $freeze(meta(it)) : it; }; }); /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(3) , core = __webpack_require__(5) , fails = __webpack_require__(9); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.17 Object.seal(O) var isObject = __webpack_require__(13) , meta = __webpack_require__(36).onFreeze; __webpack_require__(49)('seal', function($seal){ return function seal(it){ return $seal && isObject(it) ? $seal(meta(it)) : it; }; }); /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.15 Object.preventExtensions(O) var isObject = __webpack_require__(13) , meta = __webpack_require__(36).onFreeze; __webpack_require__(49)('preventExtensions', function($preventExtensions){ return function preventExtensions(it){ return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; }; }); /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.12 Object.isFrozen(O) var isObject = __webpack_require__(13); __webpack_require__(49)('isFrozen', function($isFrozen){ return function isFrozen(it){ return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; }; }); /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.13 Object.isSealed(O) var isObject = __webpack_require__(13); __webpack_require__(49)('isSealed', function($isSealed){ return function isSealed(it){ return isObject(it) ? $isSealed ? $isSealed(it) : false : true; }; }); /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.11 Object.isExtensible(O) var isObject = __webpack_require__(13); __webpack_require__(49)('isExtensible', function($isExtensible){ return function isExtensible(it){ return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; }; }); /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(20); __webpack_require__(49)('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(18); __webpack_require__(49)('getPrototypeOf', function($getPrototypeOf){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(18); __webpack_require__(49)('keys', function($keys){ return function keys(it){ return $keys(toObject(it)); }; }); /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 Object.getOwnPropertyNames(O) __webpack_require__(49)('getOwnPropertyNames', function(){ return __webpack_require__(39).get; }); /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , isObject = __webpack_require__(13) , HAS_INSTANCE = __webpack_require__(29)('hasInstance') , FunctionProto = Function.prototype; // 19.2.3.6 Function.prototype[@@hasInstance](V) if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto, HAS_INSTANCE, {value: function(O){ if(typeof this != 'function' || !isObject(O))return false; if(!isObject(this.prototype))return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while(O = $.getProto(O))if(this.prototype === O)return true; return false; }}); /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.1 Number.EPSILON var $export = __webpack_require__(3); $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.2 Number.isFinite(number) var $export = __webpack_require__(3) , _isFinite = __webpack_require__(4).isFinite; $export($export.S, 'Number', { isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); } }); /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.3 Number.isInteger(number) var $export = __webpack_require__(3); $export($export.S, 'Number', {isInteger: __webpack_require__(63)}); /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.3 Number.isInteger(number) var isObject = __webpack_require__(13) , floor = Math.floor; module.exports = function isInteger(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.4 Number.isNaN(number) var $export = __webpack_require__(3); $export($export.S, 'Number', { isNaN: function isNaN(number){ return number != number; } }); /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.5 Number.isSafeInteger(number) var $export = __webpack_require__(3) , isInteger = __webpack_require__(63) , abs = Math.abs; $export($export.S, 'Number', { isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= 0x1fffffffffffff; } }); /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = __webpack_require__(3); $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = __webpack_require__(3); $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.12 Number.parseFloat(string) var $export = __webpack_require__(3); $export($export.S, 'Number', {parseFloat: parseFloat}); /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.13 Number.parseInt(string, radix) var $export = __webpack_require__(3); $export($export.S, 'Number', {parseInt: parseInt}); /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.3 Math.acosh(x) var $export = __webpack_require__(3) , log1p = __webpack_require__(71) , sqrt = Math.sqrt , $acosh = Math.acosh; // V8 bug https://code.google.com/p/v8/issues/detail?id=3509 $export($export.S + $export.F * !($acosh && Math.floor($acosh(Number.MAX_VALUE)) == 710), 'Math', { acosh: function acosh(x){ return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? Math.log(x) + Math.LN2 : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); } }); /***/ }, /* 71 */ /***/ function(module, exports) { // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.5 Math.asinh(x) var $export = __webpack_require__(3); function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); } $export($export.S, 'Math', {asinh: asinh}); /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.7 Math.atanh(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { atanh: function atanh(x){ return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; } }); /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.9 Math.cbrt(x) var $export = __webpack_require__(3) , sign = __webpack_require__(75); $export($export.S, 'Math', { cbrt: function cbrt(x){ return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); } }); /***/ }, /* 75 */ /***/ function(module, exports) { // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.11 Math.clz32(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { clz32: function clz32(x){ return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; } }); /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.12 Math.cosh(x) var $export = __webpack_require__(3) , exp = Math.exp; $export($export.S, 'Math', { cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; } }); /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.14 Math.expm1(x) var $export = __webpack_require__(3); $export($export.S, 'Math', {expm1: __webpack_require__(79)}); /***/ }, /* 79 */ /***/ function(module, exports) { // 20.2.2.14 Math.expm1(x) module.exports = Math.expm1 || function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; }; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.16 Math.fround(x) var $export = __webpack_require__(3) , sign = __webpack_require__(75) , pow = Math.pow , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); var roundTiesToEven = function(n){ return n + 1 / EPSILON - 1 / EPSILON; }; $export($export.S, 'Math', { fround: function fround(x){ var $abs = Math.abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; } }); /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = __webpack_require__(3) , abs = Math.abs; $export($export.S, 'Math', { hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , $$ = arguments , $$len = $$.length , larg = 0 , arg, div; while(i < $$len){ arg = abs($$[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * Math.sqrt(sum); } }); /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.18 Math.imul(x, y) var $export = __webpack_require__(3) , $imul = Math.imul; // some WebKit versions fails with big numbers, some has wrong arity $export($export.S + $export.F * __webpack_require__(9)(function(){ return $imul(0xffffffff, 5) != -5 || $imul.length != 2; }), 'Math', { imul: function imul(x, y){ var UINT16 = 0xffff , xn = +x , yn = +y , xl = UINT16 & xn , yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); } }); /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.21 Math.log10(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { log10: function log10(x){ return Math.log(x) / Math.LN10; } }); /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.20 Math.log1p(x) var $export = __webpack_require__(3); $export($export.S, 'Math', {log1p: __webpack_require__(71)}); /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.22 Math.log2(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { log2: function log2(x){ return Math.log(x) / Math.LN2; } }); /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.28 Math.sign(x) var $export = __webpack_require__(3); $export($export.S, 'Math', {sign: __webpack_require__(75)}); /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.30 Math.sinh(x) var $export = __webpack_require__(3) , expm1 = __webpack_require__(79) , exp = Math.exp; // V8 near Chromium 38 has a problem with very small numbers $export($export.S + $export.F * __webpack_require__(9)(function(){ return !Math.sinh(-2e-17) != -2e-17; }), 'Math', { sinh: function sinh(x){ return Math.abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); } }); /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.33 Math.tanh(x) var $export = __webpack_require__(3) , expm1 = __webpack_require__(79) , exp = Math.exp; $export($export.S, 'Math', { tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); } }); /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.34 Math.trunc(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { trunc: function trunc(it){ return (it > 0 ? Math.floor : Math.ceil)(it); } }); /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , toIndex = __webpack_require__(23) , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , $$ = arguments , $$len = $$.length , i = 0 , code; while($$len > i){ code = +$$[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , toIObject = __webpack_require__(20) , toLength = __webpack_require__(24); $export($export.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = toIObject(callSite.raw) , len = toLength(tpl.length) , $$ = arguments , $$len = $$.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < $$len)res.push(String($$[i])); } return res.join(''); } }); /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 21.1.3.25 String.prototype.trim() __webpack_require__(93)('trim', function($trim){ return function trim(){ return $trim(this, 3); }; }); /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , defined = __webpack_require__(19) , fails = __webpack_require__(9) , spaces = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF' , space = '[' + spaces + ']' , non = '\u200b\u0085' , ltrim = RegExp('^' + space + space + '*') , rtrim = RegExp(space + space + '*$'); var exporter = function(KEY, exec, ALIAS){ var exp = {}; var FORCE = fails(function(){ return !!spaces[KEY]() || non[KEY]() != non; }); var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; if(ALIAS)exp[ALIAS] = fn; $export($export.P + $export.F * FORCE, 'String', exp); }; // 1 -> String#trimLeft // 2 -> String#trimRight // 3 -> String#trim var trim = exporter.trim = function(string, TYPE){ string = String(defined(string)); if(TYPE & 1)string = string.replace(ltrim, ''); if(TYPE & 2)string = string.replace(rtrim, ''); return string; }; module.exports = exporter; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $at = __webpack_require__(95)(false); $export($export.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(22) , defined = __webpack_require__(19); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = __webpack_require__(3) , toLength = __webpack_require__(24) , context = __webpack_require__(97) , ENDS_WITH = 'endsWith' , $endsWith = ''[ENDS_WITH]; $export($export.P + $export.F * __webpack_require__(99)(ENDS_WITH), 'String', { endsWith: function endsWith(searchString /*, endPosition = @length */){ var that = context(this, searchString, ENDS_WITH) , $$ = arguments , endPosition = $$.length > 1 ? $$[1] : undefined , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) , search = String(searchString); return $endsWith ? $endsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } }); /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { // helper for String#{startsWith, endsWith, includes} var isRegExp = __webpack_require__(98) , defined = __webpack_require__(19); module.exports = function(that, searchString, NAME){ if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); return String(defined(that)); }; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { // 7.2.8 IsRegExp(argument) var isObject = __webpack_require__(13) , cof = __webpack_require__(15) , MATCH = __webpack_require__(29)('match'); module.exports = function(it){ var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { var MATCH = __webpack_require__(29)('match'); module.exports = function(KEY){ var re = /./; try { '/./'[KEY](re); } catch(e){ try { re[MATCH] = false; return !'/./'[KEY](re); } catch(f){ /* empty */ } } return true; }; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = __webpack_require__(3) , context = __webpack_require__(97) , INCLUDES = 'includes'; $export($export.P + $export.F * __webpack_require__(99)(INCLUDES), 'String', { includes: function includes(searchString /*, position = 0 */){ return !!~context(this, searchString, INCLUDES) .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3); $export($export.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: __webpack_require__(102) }); /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var toInteger = __webpack_require__(22) , defined = __webpack_require__(19); module.exports = function repeat(count){ var str = String(defined(this)) , res = '' , n = toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = __webpack_require__(3) , toLength = __webpack_require__(24) , context = __webpack_require__(97) , STARTS_WITH = 'startsWith' , $startsWith = ''[STARTS_WITH]; $export($export.P + $export.F * __webpack_require__(99)(STARTS_WITH), 'String', { startsWith: function startsWith(searchString /*, position = 0 */){ var that = context(this, searchString, STARTS_WITH) , $$ = arguments , index = toLength(Math.min($$.length > 1 ? $$[1] : undefined, that.length)) , search = String(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(95)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(105)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(41) , $export = __webpack_require__(3) , redefine = __webpack_require__(34) , hide = __webpack_require__(35) , has = __webpack_require__(14) , Iterators = __webpack_require__(106) , $iterCreate = __webpack_require__(107) , setToStringTag = __webpack_require__(37) , getProto = __webpack_require__(2).getProto , ITERATOR = __webpack_require__(29)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getProto($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 106 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , descriptor = __webpack_require__(10) , setToStringTag = __webpack_require__(37) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(35)(IteratorPrototype, __webpack_require__(29)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.2 String.prototype.anchor(name) __webpack_require__(109)('anchor', function(createHTML){ return function anchor(name){ return createHTML(this, 'a', 'name', name); } }); /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , fails = __webpack_require__(9) , defined = __webpack_require__(19) , quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value) var createHTML = function(string, tag, attribute, value) { var S = String(defined(string)) , p1 = '<' + tag; if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"'; return p1 + '>' + S + '</' + tag + '>'; }; module.exports = function(NAME, exec){ var O = {}; O[NAME] = exec(createHTML); $export($export.P + $export.F * fails(function(){ var test = ''[NAME]('"'); return test !== test.toLowerCase() || test.split('"').length > 3; }), 'String', O); }; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.3 String.prototype.big() __webpack_require__(109)('big', function(createHTML){ return function big(){ return createHTML(this, 'big', '', ''); } }); /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.4 String.prototype.blink() __webpack_require__(109)('blink', function(createHTML){ return function blink(){ return createHTML(this, 'blink', '', ''); } }); /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.5 String.prototype.bold() __webpack_require__(109)('bold', function(createHTML){ return function bold(){ return createHTML(this, 'b', '', ''); } }); /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.6 String.prototype.fixed() __webpack_require__(109)('fixed', function(createHTML){ return function fixed(){ return createHTML(this, 'tt', '', ''); } }); /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.7 String.prototype.fontcolor(color) __webpack_require__(109)('fontcolor', function(createHTML){ return function fontcolor(color){ return createHTML(this, 'font', 'color', color); } }); /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.8 String.prototype.fontsize(size) __webpack_require__(109)('fontsize', function(createHTML){ return function fontsize(size){ return createHTML(this, 'font', 'size', size); } }); /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.9 String.prototype.italics() __webpack_require__(109)('italics', function(createHTML){ return function italics(){ return createHTML(this, 'i', '', ''); } }); /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.10 String.prototype.link(url) __webpack_require__(109)('link', function(createHTML){ return function link(url){ return createHTML(this, 'a', 'href', url); } }); /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.11 String.prototype.small() __webpack_require__(109)('small', function(createHTML){ return function small(){ return createHTML(this, 'small', '', ''); } }); /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.12 String.prototype.strike() __webpack_require__(109)('strike', function(createHTML){ return function strike(){ return createHTML(this, 'strike', '', ''); } }); /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.13 String.prototype.sub() __webpack_require__(109)('sub', function(createHTML){ return function sub(){ return createHTML(this, 'sub', '', ''); } }); /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.14 String.prototype.sup() __webpack_require__(109)('sup', function(createHTML){ return function sup(){ return createHTML(this, 'sup', '', ''); } }); /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(6) , $export = __webpack_require__(3) , toObject = __webpack_require__(18) , call = __webpack_require__(123) , isArrayIter = __webpack_require__(124) , toLength = __webpack_require__(24) , getIterFn = __webpack_require__(125); $export($export.S + $export.F * !__webpack_require__(127)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , $$ = arguments , $$len = $$.length , mapfn = $$len > 1 ? $$[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value; } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ result[index] = mapping ? mapfn(O[index], index) : O[index]; } } result.length = index; return result; } }); /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(17); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(106) , ITERATOR = __webpack_require__(29)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(126) , ITERATOR = __webpack_require__(29)('iterator') , Iterators = __webpack_require__(106); module.exports = __webpack_require__(5).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(15) , TAG = __webpack_require__(29)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = (O = Object(it))[TAG]) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(29)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ safe = true; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3); // WebKit Array.of isn't generic $export($export.S + $export.F * __webpack_require__(9)(function(){ function F(){} return !(Array.of.call(F) instanceof F); }), 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , $$ = arguments , $$len = $$.length , result = new (typeof this == 'function' ? this : Array)($$len); while($$len > index)result[index] = $$[index++]; result.length = $$len; return result; } }); /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(130) , step = __webpack_require__(131) , Iterators = __webpack_require__(106) , toIObject = __webpack_require__(20); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(105)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 130 */ /***/ function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }, /* 131 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(133)('Array'); /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var core = __webpack_require__(5) , $ = __webpack_require__(2) , DESCRIPTORS = __webpack_require__(8) , SPECIES = __webpack_require__(29)('species'); module.exports = function(KEY){ var C = core[KEY]; if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = __webpack_require__(3); $export($export.P, 'Array', {copyWithin: __webpack_require__(135)}); __webpack_require__(130)('copyWithin'); /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = __webpack_require__(18) , toIndex = __webpack_require__(23) , toLength = __webpack_require__(24); module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ var O = toObject(this) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , $$ = arguments , end = $$.length > 2 ? $$[2] : undefined , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from += count - 1; to += count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = __webpack_require__(3); $export($export.P, 'Array', {fill: __webpack_require__(137)}); __webpack_require__(130)('fill'); /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = __webpack_require__(18) , toIndex = __webpack_require__(23) , toLength = __webpack_require__(24); module.exports = function fill(value /*, start = 0, end = @length */){ var O = toObject(this) , length = toLength(O.length) , $$ = arguments , $$len = $$.length , index = toIndex($$len > 1 ? $$[1] : undefined, length) , end = $$len > 2 ? $$[2] : undefined , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = __webpack_require__(3) , $find = __webpack_require__(26)(5) , KEY = 'find' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(130)(KEY); /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = __webpack_require__(3) , $find = __webpack_require__(26)(6) , KEY = 'findIndex' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(130)(KEY); /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , LIBRARY = __webpack_require__(41) , global = __webpack_require__(4) , ctx = __webpack_require__(6) , classof = __webpack_require__(126) , $export = __webpack_require__(3) , isObject = __webpack_require__(13) , anObject = __webpack_require__(17) , aFunction = __webpack_require__(7) , strictNew = __webpack_require__(141) , forOf = __webpack_require__(142) , setProto = __webpack_require__(47).set , same = __webpack_require__(45) , speciesConstructor = __webpack_require__(143) , asap = __webpack_require__(144) , PROMISE = 'Promise' , process = global.process , isNode = classof(process) == 'process' , P = global[PROMISE] , Wrapper; var testResolve = function(sub){ var test = new P(function(){}); if(sub)test.constructor = Object; return P.resolve(test) === test; }; var USE_NATIVE = function(){ var works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = P && P.resolve && testResolve(); setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); // actual Firefox has broken subclass support, test that if(!(P2.resolve(5).then(function(){}) instanceof P2)){ works = false; } // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 if(works && __webpack_require__(8)){ var thenableThenGotten = false; P.resolve($.setDesc({}, 'then', { get: function(){ thenableThenGotten = true; } })); works = thenableThenGotten; } } catch(e){ works = false; } return works; }(); // helpers var sameConstructor = function(a, b){ // library wrapper special case if(LIBRARY && a === P && b === Wrapper)return true; return same(a, b); }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var PromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve), this.reject = aFunction(reject) }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(record, isReject){ if(record.n)return; record.n = true; var chain = record.c; asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , result, then; try { if(handler){ if(!ok)record.h = true; result = handler === true ? value : handler(value); if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; record.n = false; if(isReject)setTimeout(function(){ var promise = record.p , handler, console; if(isUnhandled(promise)){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }, 1); }); }; var isUnhandled = function(promise){ var record = promise._d , chain = record.a || record.c , i = 0 , reaction; if(record.h)return false; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var $reject = function(value){ var record = this; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); notify(record, true); }; var $resolve = function(value){ var record = this , then; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(record.p === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ asap(function(){ var wrapper = {r: record, d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { record.v = value; record.s = 1; notify(record, false); } } catch(e){ $reject.call({r: record, d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ aFunction(executor); var record = this._d = { p: strictNew(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: undefined, // <- checked in isUnhandled reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false, // <- handled rejection n: false // <- notify }; try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; __webpack_require__(146)(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = new PromiseCapability(speciesConstructor(this, P)) , promise = reaction.promise , record = this._d; reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; record.c.push(reaction); if(record.a)record.a.push(reaction); if(record.s)notify(record, false); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P}); __webpack_require__(37)(P, PROMISE); __webpack_require__(133)(PROMISE); Wrapper = __webpack_require__(5)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = new PromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof P && sameConstructor(x.constructor, this))return x; var capability = new PromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(127)(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = new PromiseCapability(C) , resolve = capability.resolve , reject = capability.reject , values = []; var abrupt = perform(function(){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ var alreadyCalled = false; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = new PromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); /***/ }, /* 141 */ /***/ function(module, exports) { module.exports = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(6) , call = __webpack_require__(123) , isArrayIter = __webpack_require__(124) , anObject = __webpack_require__(17) , toLength = __webpack_require__(24) , getIterFn = __webpack_require__(125); module.exports = function(iterable, entries, fn, that){ var iterFn = getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ call(iterator, f, step.value, entries); } }; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(17) , aFunction = __webpack_require__(7) , SPECIES = __webpack_require__(29)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , macrotask = __webpack_require__(145).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = __webpack_require__(15)(process) == 'process' , head, last, notify; var flush = function(){ var parent, domain, fn; if(isNode && (parent = process.domain)){ process.domain = null; parent.exit(); } while(head){ domain = head.domain; fn = head.fn; if(domain)domain.enter(); fn(); // <- currently we use it only for Promise - try / catch not required if(domain)domain.exit(); head = head.next; } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = 1 , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = -toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ notify = function(){ Promise.resolve().then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } module.exports = function asap(fn){ var task = {fn: fn, next: undefined, domain: isNode && process.domain}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(6) , invoke = __webpack_require__(16) , html = __webpack_require__(11) , cel = __webpack_require__(12) , global = __webpack_require__(4) , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listner = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(__webpack_require__(15)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listner, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { var redefine = __webpack_require__(34); module.exports = function(target, src, safe){ for(var key in src)redefine(target, key, src[key], safe); return target; }; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(148); // 23.1 Map Objects __webpack_require__(149)('Map', function(get){ return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , hide = __webpack_require__(35) , redefineAll = __webpack_require__(146) , ctx = __webpack_require__(6) , strictNew = __webpack_require__(141) , defined = __webpack_require__(19) , forOf = __webpack_require__(142) , $iterDefine = __webpack_require__(105) , step = __webpack_require__(131) , setSpecies = __webpack_require__(133) , DESCRIPTORS = __webpack_require__(8) , fastKey = __webpack_require__(36).fastKey , SIZE = DESCRIPTORS ? '_s' : 'size'; var getEntry = function(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that._i[index]; // frozen object case for(entry = that._f; entry; entry = entry.n){ if(entry.k == key)return entry; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ strictNew(that, C, NAME); that._i = $.create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that._i[entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that._f == entry)that._f = next; if(that._l == entry)that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) , entry; while(entry = entry ? entry.n : this._f){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if(DESCRIPTORS)$.setDesc(C.prototype, 'size', { get: function(){ return defined(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that._f)that._f = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function(C, NAME, IS_MAP){ // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function(iterated, kind){ this._t = iterated; // target this._k = kind; // kind this._l = undefined; // previous }, function(){ var that = this , kind = that._k , entry = that._l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ // or finish the iteration that._t = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , global = __webpack_require__(4) , $export = __webpack_require__(3) , meta = __webpack_require__(36) , fails = __webpack_require__(9) , hide = __webpack_require__(35) , redefineAll = __webpack_require__(146) , forOf = __webpack_require__(142) , strictNew = __webpack_require__(141) , isObject = __webpack_require__(13) , setToStringTag = __webpack_require__(37) , DESCRIPTORS = __webpack_require__(8); module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { C = wrapper(function(target, iterable){ strictNew(target, C, NAME); target._c = new Base; if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target); }); $.each.call('add,clear,delete,forEach,get,has,set,keys,values,entries'.split(','),function(KEY){ var IS_ADDER = KEY == 'add' || KEY == 'set'; if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){ if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false; var result = this._c[KEY](a === 0 ? 0 : a, b); return IS_ADDER ? this : result; }); }); if('size' in proto)$.setDesc(C.prototype, 'size', { get: function(){ return this._c.size; } }); } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F, O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(148); // 23.2 Set Objects __webpack_require__(149)('Set', function(get){ return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var each = __webpack_require__(2).each , redefine = __webpack_require__(34) , meta = __webpack_require__(36) , assign = __webpack_require__(43) , weak = __webpack_require__(152) , isObject = __webpack_require__(13) , has = __webpack_require__(14) , getWeak = meta.getWeak , isExtensible = Object.isExtensible , uncaughtFrozenStore = weak.ufstore , tmp = {} , InternalMap; var wrapper = function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).get(key); return data ? data[this._i] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }; // 23.3 WeakMap Objects var $WeakMap = __webpack_require__(149)('WeakMap', wrapper, methods, weak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ InternalMap = weak.getConstructor(wrapper); assign(InternalMap.prototype, methods); meta.NEED = true; each.call(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; redefine(proto, key, function(a, b){ // store frozen objects on internal weakmap shim if(isObject(a) && !isExtensible(a)){ if(!this._f)this._f = new InternalMap; var result = this._f[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var redefineAll = __webpack_require__(146) , getWeak = __webpack_require__(36).getWeak , anObject = __webpack_require__(17) , isObject = __webpack_require__(13) , strictNew = __webpack_require__(141) , forOf = __webpack_require__(142) , createArrayMethod = __webpack_require__(26) , $has = __webpack_require__(14) , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new FrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ strictNew(that, C, NAME); that._i = id++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && $has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var weak = __webpack_require__(152); // 23.4 WeakSet Objects __webpack_require__(149)('WeakSet', function(get){ return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = __webpack_require__(3) , _apply = Function.apply; $export($export.S, 'Reflect', { apply: function apply(target, thisArgument, argumentsList){ return _apply.call(target, thisArgument, argumentsList); } }); /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $ = __webpack_require__(2) , $export = __webpack_require__(3) , aFunction = __webpack_require__(7) , anObject = __webpack_require__(17) , isObject = __webpack_require__(13) , bind = Function.bind || __webpack_require__(5).Function.prototype.bind; // MS Edge supports only 2 arguments // FF Nightly sets third argument as `new.target`, but does not create `this` from it $export($export.S + $export.F * __webpack_require__(9)(function(){ function F(){} return !(Reflect.construct(function(){}, [], F) instanceof F); }), 'Reflect', { construct: function construct(Target, args /*, newTarget*/){ aFunction(Target); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); if(Target == newTarget){ // w/o altered newTarget, optimization for 0-4 arguments if(args != undefined)switch(anObject(args).length){ case 0: return new Target; case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind.apply(Target, $args)); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var $ = __webpack_require__(2) , $export = __webpack_require__(3) , anObject = __webpack_require__(17); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false $export($export.S + $export.F * __webpack_require__(9)(function(){ Reflect.defineProperty($.setDesc({}, 1, {value: 1}), 1, {value: 2}); }), 'Reflect', { defineProperty: function defineProperty(target, propertyKey, attributes){ anObject(target); try { $.setDesc(target, propertyKey, attributes); return true; } catch(e){ return false; } } }); /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = __webpack_require__(3) , getDesc = __webpack_require__(2).getDesc , anObject = __webpack_require__(17); $export($export.S, 'Reflect', { deleteProperty: function deleteProperty(target, propertyKey){ var desc = getDesc(anObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; } }); /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = __webpack_require__(3) , anObject = __webpack_require__(17); var Enumerate = function(iterated){ this._t = anObject(iterated); // target this._i = 0; // next index var keys = this._k = [] // keys , key; for(key in iterated)keys.push(key); }; __webpack_require__(107)(Enumerate, 'Object', function(){ var that = this , keys = that._k , key; do { if(that._i >= keys.length)return {value: undefined, done: true}; } while(!((key = keys[that._i++]) in that._t)); return {value: key, done: false}; }); $export($export.S, 'Reflect', { enumerate: function enumerate(target){ return new Enumerate(target); } }); /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var $ = __webpack_require__(2) , has = __webpack_require__(14) , $export = __webpack_require__(3) , isObject = __webpack_require__(13) , anObject = __webpack_require__(17); function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc, proto; if(anObject(target) === receiver)return target[propertyKey]; if(desc = $.getDesc(target, propertyKey))return has(desc, 'value') ? desc.value : desc.get !== undefined ? desc.get.call(receiver) : undefined; if(isObject(proto = $.getProto(target)))return get(proto, propertyKey, receiver); } $export($export.S, 'Reflect', {get: get}); /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var $ = __webpack_require__(2) , $export = __webpack_require__(3) , anObject = __webpack_require__(17); $export($export.S, 'Reflect', { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return $.getDesc(anObject(target), propertyKey); } }); /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { // 26.1.8 Reflect.getPrototypeOf(target) var $export = __webpack_require__(3) , getProto = __webpack_require__(2).getProto , anObject = __webpack_require__(17); $export($export.S, 'Reflect', { getPrototypeOf: function getPrototypeOf(target){ return getProto(anObject(target)); } }); /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { // 26.1.9 Reflect.has(target, propertyKey) var $export = __webpack_require__(3); $export($export.S, 'Reflect', { has: function has(target, propertyKey){ return propertyKey in target; } }); /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { // 26.1.10 Reflect.isExtensible(target) var $export = __webpack_require__(3) , anObject = __webpack_require__(17) , $isExtensible = Object.isExtensible; $export($export.S, 'Reflect', { isExtensible: function isExtensible(target){ anObject(target); return $isExtensible ? $isExtensible(target) : true; } }); /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { // 26.1.11 Reflect.ownKeys(target) var $export = __webpack_require__(3); $export($export.S, 'Reflect', {ownKeys: __webpack_require__(165)}); /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { // all object keys, includes non-enumerable and symbols var $ = __webpack_require__(2) , anObject = __webpack_require__(17) , Reflect = __webpack_require__(4).Reflect; module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ var keys = $.getNames(anObject(it)) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { // 26.1.12 Reflect.preventExtensions(target) var $export = __webpack_require__(3) , anObject = __webpack_require__(17) , $preventExtensions = Object.preventExtensions; $export($export.S, 'Reflect', { preventExtensions: function preventExtensions(target){ anObject(target); try { if($preventExtensions)$preventExtensions(target); return true; } catch(e){ return false; } } }); /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var $ = __webpack_require__(2) , has = __webpack_require__(14) , $export = __webpack_require__(3) , createDesc = __webpack_require__(10) , anObject = __webpack_require__(17) , isObject = __webpack_require__(13); function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = $.getDesc(anObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = $.getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = createDesc(0); } if(has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = $.getDesc(receiver, propertyKey) || createDesc(0); existingDescriptor.value = V; $.setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } $export($export.S, 'Reflect', {set: set}); /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = __webpack_require__(3) , setProto = __webpack_require__(47); if(setProto)$export($export.S, 'Reflect', { setPrototypeOf: function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } } }); /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $includes = __webpack_require__(32)(true); $export($export.P, 'Array', { // https://github.com/domenic/Array.prototype.includes includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(130)('includes'); /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/mathiasbynens/String.prototype.at var $export = __webpack_require__(3) , $at = __webpack_require__(95)(true); $export($export.P, 'String', { at: function at(pos){ return $at(this, pos); } }); /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $pad = __webpack_require__(172); $export($export.P, 'String', { padStart: function padStart(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); } }); /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-string-pad-start-end var toLength = __webpack_require__(24) , repeat = __webpack_require__(102) , defined = __webpack_require__(19); module.exports = function(that, maxLength, fillString, left){ var S = String(defined(that)) , stringLength = S.length , fillStr = fillString === undefined ? ' ' : String(fillString) , intMaxLength = toLength(maxLength); if(intMaxLength <= stringLength)return S; if(fillStr == '')fillStr = ' '; var fillLen = intMaxLength - stringLength , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); return left ? stringFiller + S : S + stringFiller; }; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $pad = __webpack_require__(172); $export($export.P, 'String', { padEnd: function padEnd(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); } }); /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim __webpack_require__(93)('trimLeft', function($trim){ return function trimLeft(){ return $trim(this, 1); }; }, 'trimStart'); /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim __webpack_require__(93)('trimRight', function($trim){ return function trimRight(){ return $trim(this, 2); }; }, 'trimEnd'); /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/WebReflection/9353781 var $ = __webpack_require__(2) , $export = __webpack_require__(3) , ownKeys = __webpack_require__(165) , toIObject = __webpack_require__(20) , createDesc = __webpack_require__(10); $export($export.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = toIObject(object) , setDesc = $.setDesc , getDesc = $.getDesc , keys = ownKeys(O) , result = {} , i = 0 , key, D; while(keys.length > i){ D = getDesc(O, key = keys[i++]); if(key in result)setDesc(result, key, createDesc(0, D)); else result[key] = D; } return result; } }); /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $export = __webpack_require__(3) , $values = __webpack_require__(178)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , toIObject = __webpack_require__(20) , isEnum = $.isEnum; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $export = __webpack_require__(3) , $entries = __webpack_require__(178)(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(3); $export($export.P, 'Map', {toJSON: __webpack_require__(181)('Map')}); /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var forOf = __webpack_require__(142) , classof = __webpack_require__(126); module.exports = function(NAME){ return function toJSON(){ if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); var arr = []; forOf(this, false, arr.push, arr); return arr; }; }; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(3); $export($export.P, 'Set', {toJSON: __webpack_require__(181)('Set')}); /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/ljharb/proposal-global var $export = __webpack_require__(3); $export($export.S, 'System', {global: __webpack_require__(4)}); /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/ljharb/proposal-is-error var $export = __webpack_require__(3) , cof = __webpack_require__(15); $export($export.S, 'Error', { isError: function isError(it){ return cof(it) === 'Error'; } }); /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , $task = __webpack_require__(145); $export($export.G + $export.B, { setImmediate: $task.set, clearImmediate: $task.clear }); /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(129); var global = __webpack_require__(4) , hide = __webpack_require__(35) , Iterators = __webpack_require__(106) , TO_STRING_TAG = __webpack_require__(29)('toStringTag') , ArrayValues = Iterators.Array; __webpack_require__(2).each.call(( 'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' + 'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList' ).split(','), function(NAME){ var Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; }); /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { // ie9- setTimeout & setInterval additional parameters fix var global = __webpack_require__(4) , $export = __webpack_require__(3) , invoke = __webpack_require__(16) , partial = __webpack_require__(188) , navigator = global.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check var wrap = function(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), typeof fn == 'function' ? fn : Function(fn) ), time); } : set; }; $export($export.G + $export.B + $export.F * MSIE, { setTimeout: wrap(global.setTimeout), setInterval: wrap(global.setInterval) }); /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var path = __webpack_require__(189) , invoke = __webpack_require__(16) , aFunction = __webpack_require__(7); module.exports = function(/* ...pargs */){ var fn = aFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , $$ = arguments , $$len = $$.length , j = 0, k = 0, args; if(!holder && !$$len)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = $$[k++]; while($$len > k)args.push($$[k++]); return invoke(fn, args, that); }; }; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(5); /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , ctx = __webpack_require__(6) , $export = __webpack_require__(3) , createDesc = __webpack_require__(10) , assign = __webpack_require__(43) , keyOf = __webpack_require__(38) , aFunction = __webpack_require__(7) , forOf = __webpack_require__(142) , isIterable = __webpack_require__(191) , $iterCreate = __webpack_require__(107) , step = __webpack_require__(131) , isObject = __webpack_require__(13) , toIObject = __webpack_require__(20) , DESCRIPTORS = __webpack_require__(8) , has = __webpack_require__(14) , getKeys = $.getKeys; // 0 -> Dict.forEach // 1 -> Dict.map // 2 -> Dict.filter // 3 -> Dict.some // 4 -> Dict.every // 5 -> Dict.find // 6 -> Dict.findKey // 7 -> Dict.mapPairs var createDictMethod = function(TYPE){ var IS_MAP = TYPE == 1 , IS_EVERY = TYPE == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = toIObject(object) , result = IS_MAP || TYPE == 7 || TYPE == 2 ? new (typeof this == 'function' ? this : Dict) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(TYPE){ if(IS_MAP)result[key] = res; // map else if(res)switch(TYPE){ case 2: result[key] = val; break; // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(IS_EVERY)return false; // every } } return TYPE == 3 || IS_EVERY ? IS_EVERY : result; }; }; var findKey = createDictMethod(6); var createDictIter = function(kind){ return function(it){ return new DictIterator(it, kind); }; }; var DictIterator = function(iterated, kind){ this._t = toIObject(iterated); // target this._a = getKeys(iterated); // keys this._i = 0; // next index this._k = kind; // kind }; $iterCreate(DictIterator, 'Dict', function(){ var that = this , O = that._t , keys = that._a , kind = that._k , key; do { if(that._i >= keys.length){ that._t = undefined; return step(1); } } while(!has(O, key = keys[that._i++])); if(kind == 'keys' )return step(0, key); if(kind == 'values')return step(0, O[key]); return step(0, [key, O[key]]); }); function Dict(iterable){ var dict = $.create(null); if(iterable != undefined){ if(isIterable(iterable)){ forOf(iterable, true, function(key, value){ dict[key] = value; }); } else assign(dict, iterable); } return dict; } Dict.prototype = null; function reduce(object, mapfn, init){ aFunction(mapfn); var O = toIObject(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key; if(arguments.length < 3){ if(!length)throw TypeError('Reduce of empty object with no initial value'); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ memo = mapfn(memo, O[key], key, object); } return memo; } function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, function(it){ return it != it; })) !== undefined; } function get(object, key){ if(has(object, key))return object[key]; } function set(object, key, value){ if(DESCRIPTORS && key in Object)$.setDesc(object, key, createDesc(0, value)); else object[key] = value; return object; } function isDict(it){ return isObject(it) && $.getProto(it) === Dict.prototype; } $export($export.G + $export.F, {Dict: Dict}); $export($export.S, 'Dict', { keys: createDictIter('keys'), values: createDictIter('values'), entries: createDictIter('entries'), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs: createDictMethod(7), reduce: reduce, keyOf: keyOf, includes: includes, has: has, get: get, set: set, isDict: isDict }); /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(126) , ITERATOR = __webpack_require__(29)('iterator') , Iterators = __webpack_require__(106); module.exports = __webpack_require__(5).isIterable = function(it){ var O = Object(it); return O[ITERATOR] !== undefined || '@@iterator' in O || Iterators.hasOwnProperty(classof(O)); }; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(17) , get = __webpack_require__(125); module.exports = __webpack_require__(5).getIterator = function(it){ var iterFn = get(it); if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(5) , $export = __webpack_require__(3) , partial = __webpack_require__(188); // https://esdiscuss.org/topic/promise-returning-delay-function $export($export.G + $export.F, { delay: function delay(time){ return new (core.Promise || global.Promise)(function(resolve){ setTimeout(partial.call(resolve, true), time); }); } }); /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { var path = __webpack_require__(189) , $export = __webpack_require__(3); // Placeholder __webpack_require__(5)._ = path._ = path._ || {}; $export($export.P + $export.F, 'Function', {part: __webpack_require__(188)}); /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3); $export($export.S + $export.F, 'Object', {isObject: __webpack_require__(13)}); /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3); $export($export.S + $export.F, 'Object', {classof: __webpack_require__(126)}); /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , define = __webpack_require__(198); $export($export.S + $export.F, 'Object', {define: define}); /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , ownKeys = __webpack_require__(165) , toIObject = __webpack_require__(20); module.exports = function define(target, mixin){ var keys = ownKeys(toIObject(mixin)) , length = keys.length , i = 0, key; while(length > i)$.setDesc(target, key = keys[i++], $.getDesc(mixin, key)); return target; }; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , define = __webpack_require__(198) , create = __webpack_require__(2).create; $export($export.S + $export.F, 'Object', { make: function(proto, mixin){ return define(create(proto), mixin); } }); /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(105)(Number, 'Number', function(iterated){ this._l = +iterated; this._i = 0; }, function(){ var i = this._i++ , done = !(i < this._l); return {done: done, value: done ? undefined : i}; }); /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/benjamingr/RexExp.escape var $export = __webpack_require__(3) , $re = __webpack_require__(202)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }}); /***/ }, /* 202 */ /***/ function(module, exports) { module.exports = function(regExp, replace){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(it).replace(regExp, replacer); }; }; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3); var $re = __webpack_require__(202)(/[&<>"']/g, { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }); $export($export.P + $export.F, 'String', {escapeHTML: function escapeHTML(){ return $re(this); }}); /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3); var $re = __webpack_require__(202)(/&(?:amp|lt|gt|quot|apos);/g, { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'" }); $export($export.P + $export.F, 'String', {unescapeHTML: function unescapeHTML(){ return $re(this); }}); /***/ } /******/ ]); // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = __e; // RequireJS export else if(typeof define == 'function' && define.amd)define(function(){return __e}); // Export to global object else __g.core = __e; }(1, 1);
src/svg-icons/hardware/keyboard-hide.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardHide = (props) => ( <SvgIcon {...props}> <path d="M20 3H4c-1.1 0-1.99.9-1.99 2L2 15c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 3h2v2h-2V6zm0 3h2v2h-2V9zM8 6h2v2H8V6zm0 3h2v2H8V9zm-1 2H5V9h2v2zm0-3H5V6h2v2zm9 7H8v-2h8v2zm0-4h-2V9h2v2zm0-3h-2V6h2v2zm3 3h-2V9h2v2zm0-3h-2V6h2v2zm-7 15l4-4H8l4 4z"/> </SvgIcon> ); HardwareKeyboardHide = pure(HardwareKeyboardHide); HardwareKeyboardHide.displayName = 'HardwareKeyboardHide'; HardwareKeyboardHide.muiName = 'SvgIcon'; export default HardwareKeyboardHide;
client/src/components/ContentWrapper/index.js
steThera/react-mobx-koa
import React from 'react'; import './style.less'; class ContentWrapper extends React.Component { componentDidMount() { $.AdminLTE.layout.activate(); // eslint-disable-line no-undef } render() { return ( <div className="content-wrapper"> { React.Children.toArray(this.props.children) } </div> ); } } ContentWrapper.propTypes = { children: React.PropTypes.any.isRequired, }; export default ContentWrapper;
src/svg-icons/image/music-note.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMusicNote = (props) => ( <SvgIcon {...props}> <path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/> </SvgIcon> ); ImageMusicNote = pure(ImageMusicNote); ImageMusicNote.displayName = 'ImageMusicNote'; ImageMusicNote.muiName = 'SvgIcon'; export default ImageMusicNote;
src/ShowActivitySubHeader/index.js
DuckyTeam/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import LabelSmall from '../LabelSmall'; import Wrapper from '../Wrapper'; import classNames from 'classnames'; import styles from './styles.css'; function ShowActivitySubHeader(props) { return ( <div className={classNames(styles.wrapper, {[props.className]: props.className})}> <Wrapper size="side-bottom" > <LabelSmall icon={props.userLikes ? 'icon-favorite' : 'icon-favorite_border'} number={props.favNumber} /> <LabelSmall icon={props.userCommented ? 'icon-chat_bubble' : 'icon-chat_bubble_outline'} number={props.commentNumber} /> <LabelSmall icon={props.userBookmarked ? 'icon-turned_in' : 'icon_turned_in_not'} number={props.bookmarkNumber} /> <LabelSmall icon="icon-share" number={props.shareNumber} /> </Wrapper> </div> ); } ShowActivitySubHeader.propTypes = { bookmarkNumber: PropTypes.string, className: PropTypes.string, commentNumber: PropTypes.string, favNumber: PropTypes.string, shareNumber: PropTypes.string, userBookmarked: PropTypes.bool, userCommented: PropTypes.bool, userLikes: PropTypes.bool }; export default ShowActivitySubHeader;
app/javascript/mastodon/features/ui/components/onboarding_modal.js
kagucho/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ReactSwipeableViews from 'react-swipeable-views'; import classNames from 'classnames'; import Permalink from '../../../components/permalink'; import ComposeForm from '../../compose/components/compose_form'; import Search from '../../compose/components/search'; import NavigationBar from '../../compose/components/navigation_bar'; import ColumnHeader from './column_header'; import { List as ImmutableList } from 'immutable'; const noop = () => { }; const messages = defineMessages({ home_title: { id: 'column.home', defaultMessage: 'Home' }, notifications_title: { id: 'column.notifications', defaultMessage: 'Notifications' }, local_title: { id: 'column.community', defaultMessage: 'Local timeline' }, federated_title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const PageOne = ({ acct, domain }) => ( <div className='onboarding-modal__page onboarding-modal__page-one'> <div style={{ flex: '0 0 auto' }}> <div className='onboarding-modal__page-one__elephant-friend' /> </div> <div> <h1><FormattedMessage id='onboarding.page_one.welcome' defaultMessage='Welcome to Mastodon!' /></h1> <p><FormattedMessage id='onboarding.page_one.federation' defaultMessage='Mastodon is a network of independent servers joining up to make one larger social network. We call these servers instances.' /></p> <p><FormattedMessage id='onboarding.page_one.handle' defaultMessage='You are on {domain}, so your full handle is {handle}' values={{ domain, handle: <strong>{acct}@{domain}</strong> }} /></p> </div> </div> ); PageOne.propTypes = { acct: PropTypes.string.isRequired, domain: PropTypes.string.isRequired, }; const PageTwo = ({ me }) => ( <div className='onboarding-modal__page onboarding-modal__page-two'> <div className='figure non-interactive'> <div className='pseudo-drawer'> <NavigationBar account={me} /> </div> <ComposeForm text='Awoo! #introductions' suggestions={ImmutableList()} mentionedDomains={[]} spoiler={false} onChange={noop} onSubmit={noop} onPaste={noop} onPickEmoji={noop} onChangeSpoilerText={noop} onClearSuggestions={noop} onFetchSuggestions={noop} onSuggestionSelected={noop} showSearch /> </div> <p><FormattedMessage id='onboarding.page_two.compose' defaultMessage='Write posts from the compose column. You can upload images, change privacy settings, and add content warnings with the icons below.' /></p> </div> ); PageTwo.propTypes = { me: ImmutablePropTypes.map.isRequired, }; const PageThree = ({ me }) => ( <div className='onboarding-modal__page onboarding-modal__page-three'> <div className='figure non-interactive'> <Search value='' onChange={noop} onSubmit={noop} onClear={noop} onShow={noop} /> <div className='pseudo-drawer'> <NavigationBar account={me} /> </div> </div> <p><FormattedMessage id='onboarding.page_three.search' defaultMessage='Use the search bar to find people and look at hashtags, such as {illustration} and {introductions}. To look for a person who is not on this instance, use their full handle.' values={{ illustration: <Permalink to='/timelines/tag/illustration' href='/tags/illustration'>#illustration</Permalink>, introductions: <Permalink to='/timelines/tag/introductions' href='/tags/introductions'>#introductions</Permalink> }} /></p> <p><FormattedMessage id='onboarding.page_three.profile' defaultMessage='Edit your profile to change your avatar, bio, and display name. There, you will also find other preferences.' /></p> </div> ); PageThree.propTypes = { me: ImmutablePropTypes.map.isRequired, }; const PageFour = ({ domain, intl }) => ( <div className='onboarding-modal__page onboarding-modal__page-four'> <div className='onboarding-modal__page-four__columns'> <div className='row'> <div> <div className='figure non-interactive'><ColumnHeader icon='home' type={intl.formatMessage(messages.home_title)} /></div> <p><FormattedMessage id='onboarding.page_four.home' defaultMessage='The home timeline shows posts from people you follow.' /></p> </div> <div> <div className='figure non-interactive'><ColumnHeader icon='bell' type={intl.formatMessage(messages.notifications_title)} /></div> <p><FormattedMessage id='onboarding.page_four.notifications' defaultMessage='The notifications column shows when someone interacts with you.' /></p> </div> </div> <div className='row'> <div> <div className='figure non-interactive' style={{ marginBottom: 0 }}><ColumnHeader icon='users' type={intl.formatMessage(messages.local_title)} /></div> </div> <div> <div className='figure non-interactive' style={{ marginBottom: 0 }}><ColumnHeader icon='globe' type={intl.formatMessage(messages.federated_title)} /></div> </div> </div> <p><FormattedMessage id='onboarding.page_five.public_timelines' defaultMessage='The local timeline shows public posts from everyone on {domain}. The federated timeline shows public posts from everyone who people on {domain} follow. These are the Public Timelines, a great way to discover new people.' values={{ domain }} /></p> </div> </div> ); PageFour.propTypes = { domain: PropTypes.string.isRequired, intl: PropTypes.object.isRequired, }; const PageSix = ({ admin, domain }) => { let adminSection = ''; if (admin) { adminSection = ( <p> <FormattedMessage id='onboarding.page_six.admin' defaultMessage="Your instance's admin is {admin}." values={{ admin: <Permalink href={admin.get('url')} to={`/accounts/${admin.get('id')}`}>@{admin.get('acct')}</Permalink> }} /> <br /> <FormattedMessage id='onboarding.page_six.read_guidelines' defaultMessage="Please read {domain}'s {guidelines}!" values={{ domain, guidelines: <a href='/about/more' target='_blank'><FormattedMessage id='onboarding.page_six.guidelines' defaultMessage='community guidelines' /></a> }} /> </p> ); } return ( <div className='onboarding-modal__page onboarding-modal__page-six'> <h1><FormattedMessage id='onboarding.page_six.almost_done' defaultMessage='Almost done...' /></h1> {adminSection} <p><FormattedMessage id='onboarding.page_six.github' defaultMessage='Mastodon is free open-source software. You can report bugs, request features, or contribute to the code on {github}.' values={{ github: <a href='https://github.com/kagucho/mastodon' target='_blank' rel='noopener'>GitHub</a> }} /></p> <p><FormattedMessage id='onboarding.page_six.apps_available' defaultMessage='There are {apps} available for iOS, Android and other platforms.' values={{ apps: <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md' target='_blank' rel='noopener'><FormattedMessage id='onboarding.page_six.various_app' defaultMessage='mobile apps' /></a> }} /></p> <p><em><FormattedMessage id='onboarding.page_six.appetoot' defaultMessage='Bon Appetoot!' /></em></p> </div> ); }; PageSix.propTypes = { admin: ImmutablePropTypes.map, domain: PropTypes.string.isRequired, }; const mapStateToProps = state => ({ me: state.getIn(['accounts', state.getIn(['meta', 'me'])]), admin: state.getIn(['accounts', state.getIn(['meta', 'admin'])]), domain: state.getIn(['meta', 'domain']), }); @connect(mapStateToProps) @injectIntl export default class OnboardingModal extends React.PureComponent { static propTypes = { onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, me: ImmutablePropTypes.map.isRequired, domain: PropTypes.string.isRequired, admin: ImmutablePropTypes.map, }; state = { currentIndex: 0, }; componentWillMount() { const { me, admin, domain, intl } = this.props; this.pages = [ <PageOne acct={me.get('acct')} domain={domain} />, <PageTwo me={me} />, <PageThree me={me} />, <PageFour domain={domain} intl={intl} />, <PageSix admin={admin} domain={domain} />, ]; }; componentDidMount() { window.addEventListener('keyup', this.handleKeyUp); } componentWillUnmount() { window.addEventListener('keyup', this.handleKeyUp); } handleSkip = (e) => { e.preventDefault(); this.props.onClose(); } handleDot = (e) => { const i = Number(e.currentTarget.getAttribute('data-index')); e.preventDefault(); this.setState({ currentIndex: i }); } handlePrev = () => { this.setState(({ currentIndex }) => ({ currentIndex: Math.max(0, currentIndex - 1), })); } handleNext = () => { const { pages } = this; this.setState(({ currentIndex }) => ({ currentIndex: Math.min(currentIndex + 1, pages.length - 1), })); } handleSwipe = (index) => { this.setState({ currentIndex: index }); } handleKeyUp = ({ key }) => { switch (key) { case 'ArrowLeft': this.handlePrev(); break; case 'ArrowRight': this.handleNext(); break; } } handleClose = () => { this.props.onClose(); } render () { const { pages } = this; const { currentIndex } = this.state; const hasMore = currentIndex < pages.length - 1; const nextOrDoneBtn = hasMore ? ( <button onClick={this.handleNext} className='onboarding-modal__nav onboarding-modal__next' > <FormattedMessage id='onboarding.next' defaultMessage='Next' /> </button> ) : ( <button onClick={this.handleClose} className='onboarding-modal__nav onboarding-modal__done' > <FormattedMessage id='onboarding.done' defaultMessage='Done' /> </button> ); return ( <div className='modal-root__modal onboarding-modal'> <ReactSwipeableViews index={currentIndex} onChangeIndex={this.handleSwipe} className='onboarding-modal__pager'> {pages.map((page, i) => { const className = classNames('onboarding-modal__page__wrapper', { 'onboarding-modal__page__wrapper--active': i === currentIndex, }); return ( <div key={i} className={className}>{page}</div> ); })} </ReactSwipeableViews> <div className='onboarding-modal__paginator'> <div> <button onClick={this.handleSkip} className='onboarding-modal__nav onboarding-modal__skip' > <FormattedMessage id='onboarding.skip' defaultMessage='Skip' /> </button> </div> <div className='onboarding-modal__dots'> {pages.map((_, i) => { const className = classNames('onboarding-modal__dot', { active: i === currentIndex, }); return ( <div key={`dot-${i}`} role='button' tabIndex='0' data-index={i} onClick={this.handleDot} className={className} /> ); })} </div> <div> {nextOrDoneBtn} </div> </div> </div> ); } }
app/client/main.js
dshook/issue-viewer
import React from 'react'; import babel from 'babel/polyfill'; import { Router, Route, Link } from 'react-router'; import { history } from 'react-router/lib/HashHistory'; import Layout from './views/Layout.jsx'; import IssueList from './views/IssueList.jsx'; import Issue from './views/Issue.jsx'; // Finally we render a `Router` component with some `Route`s, it'll do all // the fancy routing stuff for us. React.render(( <Router history={history}> <Route component={Layout}> <Route path="/" component={IssueList}/> <Route path="issue/:repo/:number" component={Issue}/> </Route> </Router> ), document.getElementById('layout'));
demo/src/index.js
Psykar/react-filtered-multiselect
import 'bootstrap/dist/css/bootstrap.min.css' import 'bootstrap/dist/css/bootstrap-theme.min.css' import React from 'react' import {render} from 'react-dom' import FilteredMultiSelect from '../../src/index' import CULTURE_SHIPS from './ships.json' const BOOTSTRAP_CLASSES = { filter: 'form-control', select: 'form-control', button: 'btn btn btn-block btn-default', buttonActive: 'btn btn btn-block btn-primary' } var BasicSelection = React.createClass({ getInitialState() { return { selectedOptions: [] } }, handleClearSelection() { this.setState({selectedOptions: []}) }, handleDeselect(index) { var selectedOptions = this.state.selectedOptions.slice() selectedOptions.splice(index, 1) this.setState({selectedOptions}) }, handleSelectionChange(selectedOptions) { selectedOptions.sort((a, b) => a.id - b.id) this.setState({selectedOptions}) }, render() { var {selectedOptions} = this.state return <div className="row"> <div className="col-md-5"> <FilteredMultiSelect classNames={BOOTSTRAP_CLASSES} onChange={this.handleSelectionChange} options={CULTURE_SHIPS} selectedOptions={selectedOptions} textProp="name" valueProp="id" /> <p className="help-block">Press Enter when there's only one matching item to select it.</p> </div> <div className="col-md-5"> {selectedOptions.length === 0 && <p>(nothing selected yet)</p>} {selectedOptions.length > 0 && <ol> {selectedOptions.map((ship, i) => <li key={ship.id}> {`${ship.name} `} <span style={{cursor: 'pointer'}} onClick={this.handleDeselect.bind(null, i)}> &times; </span> </li>)} </ol>} {selectedOptions.length > 0 && <button style={{marginLeft: 20}} className="btn btn-default" onClick={this.handleClearSelection}> Clear Selection </button>} </div> </div> } }) var AddRemoveSelection = React.createClass({ getInitialState() { return { selectedOptions: [] } }, handleDeselect(deselectedOptions) { var selectedOptions = this.state.selectedOptions.slice() deselectedOptions.forEach(option => { selectedOptions.splice(selectedOptions.indexOf(option), 1) }) this.setState({selectedOptions}) }, handleSelect(selectedOptions) { selectedOptions.sort((a, b) => a.id - b.id) this.setState({selectedOptions}) }, render() { var {selectedOptions} = this.state return <div className="row"> <div className="col-md-5"> <FilteredMultiSelect buttonText="Add" classNames={BOOTSTRAP_CLASSES} onChange={this.handleSelect} options={CULTURE_SHIPS} selectedOptions={selectedOptions} textProp="name" valueProp="id" /> </div> <div className="col-md-5"> <FilteredMultiSelect buttonText="Remove" classNames={{ filter: 'form-control', select: 'form-control', button: 'btn btn btn-block btn-default', buttonActive: 'btn btn btn-block btn-danger' }} onChange={this.handleDeselect} options={selectedOptions} textProp="name" valueProp="id" /> </div> </div> } }) var App = React.createClass({ render() { return <div className="container"> <div className="row header"> <div className="col-md-12"> <h1><a href="https://github.com/insin/react-filtered-multiselect">React &lt;FilteredMultiSelect/&gt;</a></h1> <p className="lead">A reusable React component for making and adding to selections using a filtered multi-select.</p> </div> </div> <h2>Basic Selection</h2> <p>Select some ships from <a href="http://en.wikipedia.org/wiki/The_Culture">The Culture</a>.</p> <BasicSelection/> <h2>Add &amp; Remove</h2> <p>Move items from one <code>&lt;FilteredMultiSelect/&gt;</code> to another and back again.</p> <AddRemoveSelection/> </div> } }) var app = document.querySelector('#app') if (!app) { app = document.createElement('div') app.id = 'app' document.body.appendChild(app) } render(<App/>, app)
packages/mcs-lite-landing-web/src/components/SVG/SVGTooltip.js
MCS-Lite/mcs-lite
/** * svgtoreact * * @author Michael Hsu */ import React from 'react'; export default function SVGTooltip(props) { return ( <svg width={83} height={50} viewBox="0 0 83 50" {...props}> <g> <path d="M46.076 41l-4.517 6.677c-.307.454-.81.457-1.119 0l-4.517-6.677h-32.924c-1.103 0-1.997-.892-1.997-1.997v-36.005c0-1.103.898-1.997 1.997-1.997h76.005c1.103 0 1.997.892 1.997 1.997v36.005c0 1.103-.898 1.997-1.997 1.997h-32.927z" id="Combined-Shape" fill="#E6F5FB" /> <path d="M11 13v-2h60v2h-60zm0 6v-2h50v2h-50zm0 6v-2h40v2h-40zm0 6v-2h30v2h-30z" id="Combined-Shape" fill="#97D9F2" /> <path d="M42.386 48.237c-.704 1.041-2.07 1.043-2.775 0l-4.22-6.237h-32.394c-1.656 0-2.997-1.34-2.997-2.997v-36.005c0-1.654 1.345-2.997 2.997-2.997h76.005c1.656 0 2.997 1.34 2.997 2.997v36.005c0 1.654-1.345 2.997-2.997 2.997h-32.396l-4.22 6.237zm3.158-8.237h33.458c.549 0 .997-.448.997-.997v-36.005c0-.552-.445-.997-.997-.997h-76.005c-.549 0-.997.448-.997.997v36.005c0 .552.445.997.997.997h33.455l4.546 6.719 4.546-6.719z" fill="#00A1DE" /> </g> </svg> ); }
src/components/NotFound/NotFound.react.js
uday96/chat.susi.ai
import React, { Component } from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import { Link } from 'react-router-dom'; import './NotFound.css'; import LogoImg from '../../images/susi-logo.svg'; import UserPreferencesStore from '../../stores/UserPreferencesStore'; import Login from '../Auth/Login/Login.react'; import SignUp from '../Auth/SignUp/SignUp.react'; import Dialog from 'material-ui/Dialog'; import ForgotPassword from '../Auth/ForgotPassword/ForgotPassword.react'; import Close from 'material-ui/svg-icons/navigation/close'; import Footer from '../Footer/Footer.react'; export default class NotFound extends Component { constructor(props) { super(props); this.state = { open: false, loginOpen: false, openForgotPassword: false } } // Open Sign Up Dialog handleOpen = () => { this.setState({ open: true }); }; // Close all dialog boxes handleClose = () => { this.setState({ open: false, loginOpen: false, openForgotPassword: false }); }; // Open Login Dialog handleLoginOpen = () => { this.setState({ loginOpen: true, open: false, openForgotPassword:false }) } // Close Login Dialog handleLoginClose = () => { this.setState({ loginOpen: false, }) } // Close Login Dialog and open Forgot Password dialog handleForgotPassword = () => { this.setState({ openForgotPassword: true, loginOpen: false }); } render() { document.body.style.setProperty('background-image', 'none'); const closingStyle ={ position: 'absolute', zIndex: 1200, fill: '#444', width: '26px', height: '26px', right: '10px', top: '10px', cursor:'pointer' } const closingStyleLogin = { position: 'absolute', zIndex: 1200, fill: '#444', width: '26px', height: '26px', right: '10px', top: '10px', cursor: 'pointer' }; const bodyStyle = { 'padding': 0, textAlign: 'center' } return ( <div> <div className='container-fluid not-found-banner'> <h2 > <a className='susilogo' > <img src={LogoImg} to={'/'} alt='Page Not Found' /> </a> </h2> <h1>404</h1> <h2>Page not found</h2> <div className='button-wrapper'> <Link to={'/'} className='actionButton'> <RaisedButton className='notfound-button' label='Chat With SUSI' backgroundColor={ UserPreferencesStore.getTheme() ? '#4285f4' : '#19314B'} labelColor='#fff' /> </Link> <br /> <RaisedButton className='notfound-button' label='SignUp to SUSI' onTouchTap={this.handleOpen} backgroundColor={ UserPreferencesStore.getTheme() ? '#4285f4' : '#19314B'} labelColor='#fff' /> <br /> <RaisedButton className='notfound-button' label='SignIn to SUSI' onTouchTap={this.handleLoginOpen} backgroundColor={ UserPreferencesStore.getTheme() ? '#4285f4' : '#19314B'} labelColor='#fff' /> </div> </div> <Footer /> {/* Login */} <Dialog className='dialogStyle' modal={true} open={this.state.loginOpen} autoScrollBodyContent={true} bodyStyle={bodyStyle} contentStyle={{ width: '35%', minWidth: '300px' }} onRequestClose={this.handleClose}> <Login {...this.props} handleForgotPassword={this.handleForgotPassword}/> <Close style={closingStyleLogin} onTouchTap={this.handleClose} /> </Dialog> {/* SignUp */} <Dialog className='dialogStyle' modal={true} open={this.state.open} autoScrollBodyContent={true} bodyStyle={bodyStyle} contentStyle={{ width: '35%', minWidth: '300px' }} onRequestClose={this.handleClose}> <SignUp {...this.props} onRequestClose={this.handleClose} onLoginSignUp={this.handleLoginOpen}/> <Close style={closingStyle} onTouchTap={this.handleClose} /> </Dialog> <Dialog className='dialogStyle' modal={false} open={this.state.openForgotPassword} autoScrollBodyContent={true} contentStyle={{width: '35%',minWidth: '300px'}} onRequestClose={this.handleClose}> <ForgotPassword {...this.props} showForgotPassword={this.showForgotPassword}/> <Close style={closingStyle} onTouchTap={this.handleClose}/> </Dialog> </div> ); }; }
src/App.js
Neil-G/Volume-Calculator
import React, { Component } from 'react'; import Tooltip from 'rc-tooltip'; export class App extends Component { constructor(props) { super(props); this.state = cleanForm(); } render() { const { decimals, area, roof, paved, grass, roofCoef, pavedCoef, grassCoef, porousAsphault, porousAsphaultCoef, undevelopedArea, undevelopedAreaCoef, borough, i } = this.state; const Cw = round( (roof*roofCoef + paved*pavedCoef + grass*grassCoef + porousAsphault*porousAsphaultCoef + undevelopedArea*undevelopedAreaCoef)/area, decimals ); const Qall = round( area*1000 * boroughs[borough] / 43560, decimals ); const developedFlow = round( area*1000*Cw*i / 43560, decimals ); const Qo = round( Qall/(round(area*0.0229568, decimals)*Cw), decimals ); const tVariable = round(Math.pow( 12600/Qo, 0.5)*0.5 - 15, decimals); const VVariable = round( ( 8400*tVariable/(tVariable + 15) - 40*tVariable*Qo )*round(area*0.0229568, decimals)*Cw, decimals); const tConstant = round(Math.pow( 8400/Qo, 0.5)*0.5 - 15, decimals ); const VConstant = round( ( 8400*tConstant/(tConstant + 15) - 60*tConstant*Qo )*round(area*0.0229568, decimals)*Cw, decimals); console.log(this.state) return ( <div className="container"> <h1 style={{textAlign: "center", background: "black", color: "white", padding: "15px"}} >Detention Facility Volume Calculator</h1> <hr/> {/* Warnings */} <h3 style={{textAlign: "center", marginBottom: "30px", background: "#EF6C00", color: "white"}}> Instructions </h3> <div className="row" style={{textAlign: "center"}}> <p style={{background: "#6db2df", padding: "5px 10px", color: "white", border: "5px double black"}} className="six columns u-full-width offset-by-three"> Boxes with this color heading can be changed directly </p> </div> <div className="row" style={{textAlign: "center"}}> <p style={{background: "gray", padding: "5px 10px", color: "white", border: "5px double black"}} className="six columns u-full-width offset-by-three"> Boxes with this color heading are calculations and cannot be changed directly </p> </div> <div className="row" style={{textAlign: "center"}}> <p style={{background: "tomato", padding: "5px 10px", color: "white", border: "5px double black"}} className="six columns u-full-width offset-by-three"> please input areas in 1,000 sq.ft. units <br/> <b>example:</b> 93,200 sq.ft. = 93.2 </p> </div> {/* INPUTS */} <h3 style={{textAlign: "center", marginBottom: "30px", background: "#EF6C00", color: "white"}}> Inputs </h3> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Decimals </span> <input type="number" className="three columns" value={decimals} onChange={ e => this.setState({ decimals: e.target.value })} /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Area <span style={{ fontSize: "0.7em"}}> (1000 sq.ft.)</span></span> <input type="number" className="five columns center-text" value={area} onChange={ e => this.setState({ area: e.target.value }) } /> <span className="two columns u-full-width" style={label}> acres </span> <input type="number" className="three columns center-text" value={round(area*0.0229568, decimals)} disabled={true} /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Roof <span style={{ fontSize: "0.7em"}}> (1000 sq.ft.)</span></span> <input type="number" className="five columns center-text" value={roof} onChange={ e => this.setState({ roof: e.target.value }) } /> <span className="two columns u-full-width" style={activeLabel}> runoff coef </span> <input type="number" className="three columns center-text" value={roofCoef} onChange={ e => this.setState({ roofCoef: e.target.value }) } /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Paved <span style={{ fontSize: "0.7em"}}> (1000 sq.ft.)</span></span> <input type="number" className="five columns center-text" value={paved} onChange={ e => this.setState({ paved: e.target.value }) } /> <span className="two columns u-full-width" style={activeLabel}> runoff coef </span> <input type="number" className="three columns center-text" value={pavedCoef} onChange={ e => this.setState({ pavedCoef: e.target.value }) } /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Porous Asphault <span style={{ fontSize: "0.7em"}}> (1000 sq.ft.)</span></span> <input type="number" className="five columns center-text" value={porousAsphault} onChange={ e => this.setState({ porousAsphault: e.target.value }) } /> <span className="two columns u-full-width" style={activeLabel}> runoff coef </span> <input type="number" className="three columns center-text" value={porousAsphaultCoef} onChange={ e => this.setState({ porousAsphaultCoef: e.target.value }) } /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Undeveloped <span style={{ fontSize: "0.7em"}}> (1000 sq.ft.)</span></span> <input type="number" className="five columns center-text" value={undevelopedArea} onChange={ e => this.setState({ undevelopedArea: e.target.value }) } /> <span className="two columns u-full-width" style={activeLabel}> runoff coef </span> <input type="number" className="three columns center-text" value={undevelopedAreaCoef} onChange={ e => this.setState({ undevelopedAreaCoef: e.target.value }) } /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Grass <span style={{ fontSize: "0.7em"}}> (1000 sq.ft.)</span></span> <input type="number" className="five columns center-text" value={grass} onChange={ e => this.setState({ grass: e.target.value }) } /> <span className="two columns u-full-width" style={activeLabel}> runoff coef </span> <input type="number" className="three columns center-text" value={grassCoef} onChange={ e => this.setState({ grassCoef: e.target.value }) } /> </div> <div className="row"> <span className="two columns u-full-width" style={activeLabel}> Borough </span> <select className="five columns u-full-width center-text" value={borough} onChange={ e => this.setState({ borough: e.target.value }) }> <option value={undefined}> please choose a borough </option> <option value="brooklyn"> Brooklyn </option> <option value="queens"> Queens </option> <option value="bronxPre"> Bronx-pre 1964 </option> <option value="bronxPost"> Bronx-post 1964 </option> </select> <span className="two columns u-full-width" style={label}> coefficient </span> <input type="text" className="three columns center-text" value={boroughs[borough]} /> </div> <hr/> {/* OUTPUTS */} <h3 style={{textAlign: "center", marginBottom: "30px", background: "#EF6C00", color: "white"}}> Outputs </h3> <div className="row" style={{textAlign: "center"}}> <span className="two columns u-full-width offset-by-three" style={label}> Cw </span> <input type="number" className="four columns" disabled={true} value={Cw}/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> ( {String(roof)}*{String(roofCoef)} + {String(paved)}*{String(pavedCoef)} + {String(porousAsphault)}*{String(porousAsphaultCoef)} + {String(undevelopedArea)}*{String(undevelopedAreaCoef)} + {String(grass)}*{String(grassCoef)}) / {String(area)} = {Cw} </span> </div> <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> Qall <span style={{fontSize: "0.6em"}}> (cfs) </span></span> <input type="number" className="four columns" disabled={true} value={Qall}/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> {area} * {1000} * {boroughs[borough]} / {43560} = {Qall} </span> </div> <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> Developed Flow <span style={{fontSize: "0.6em"}}> (cfs) </span></span> <input type="number" className="four columns" disabled={true} value={developedFlow}/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> {area} * {1000} * {Cw} * {i} / 43560 = {developedFlow} </span> </div> { developedFlow > Qall ? <div className="row"> <p style={{background: "tomato", padding: "5px 10px", color: "white", borderRadius: "2px"}} className="six columns u-full-width offset-by-three"> Developed Flow ({developedFlow}<span style={{fontSize: "0.6em"}}> cfs </span>) > Qall ({Qall}<span style={{fontSize: "0.6em"}}> cfs </span>) - Flow must be restricted </p> </div>: null } <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> Qo </span> <input type="number" className="four columns" disabled={true} value={Qo}/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> {Qall} / ({round(area*0.0229568, decimals)}*{Cw}) = {Qo} </span> </div> {/* Variable Outflow */} <div className="row"> <p className="twelve columns u-full-width offset-by-three"> Outflow will be controlled by an orifice and will <b>vary</b> with the depth of storage: </p> </div> <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> t (min.) </span> <input type="number" className="four columns" disabled={true} value={ tVariable }/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> (0.5)*(12600/{Qo})^.5) - 15 = { tVariable } </span> </div> <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> V (ft^3) </span> <input type="number" className="four columns" disabled={true} value={ VVariable }/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> [ 8400 * {tVariable} / ({tVariable} + 15) - 40 * {tVariable}*{Qo} )] * {round(area*0.0229568, decimals)} * {Cw} = { VVariable } </span> </div> {/* Constant Outflow */} <div className="row"> <p className="twelve columns u-full-width offset-by-three"> Outflow will be <b>constant</b> and will not vary with the depth of storage: </p> </div> <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> t (min.) </span> <input type="number" className="four columns" disabled={true} value={ tConstant }/> </div> <div className="row"> <span className="twelve columns u-full-width offset-by-three" style={{marginBottom: "15px"}}> (0.5)*(8400/{Qo})^.5) - 15 = { tConstant } </span> </div> <div className="row"> <span className="two columns u-full-width offset-by-three" style={label}> V (ft^3) </span> <input type="number" className="four columns" disabled={true} value={ VConstant }/> </div> <div className="row" > <span className="twelve columns u-full-width offset-by-three"> [ 8400 * {tConstant} / ({tConstant} + 15) - 60 * {tConstant}*{Qo} )] * {round(area*0.0229568, decimals)} * {Cw} = { VConstant } </span> </div> </div> ); } } const label = { background: "gray" , color: "white" , textAlign: "center" , height: "38px" // , borderRadius: "2px" , padding: "3px" , boxSizing: "border-box" } const activeLabel = { background: "#6db2df" , color: "white" , textAlign: "center" , height: "38px" // , borderRadius: "2px" , padding: "3px" , boxSizing: "border-box" } function cleanForm() { return { area: 0 , roof: 0 , roofCoef: 1 , paved: 0 , pavedCoef: 0.85 , porousAsphault: 0 , porousAsphaultCoef: 0.75 , undevelopedArea: 0 , undevelopedAreaCoef: 0.3 , grass: 0 , grassCoef: 0.2 , borough: undefined , i: 5.95 , round: 3 , decimals: 3 } } const boroughs = { brooklyn: 0.5*5 , queens: 0.5*4.8 , bronxPre: 0.44*4 , bronxPost: 0.75*4 } function round(number, decimals) { const factor = Math.pow(10, decimals) return Math.round(number*factor)/factor; }
src/components/RightSideBar.js
caesai/medialeaks
import React from 'react'; import rightsidebanner from '../img/rightsidebanner.jpg'; import sidebarbanner from '../img/sidebarbanner.jpg'; export default class RightSideBar extends React.Component { constructor(props) { super(props); } componentDidMount(){ } render() { return( <div className="sidebar_right"> {this.props.banner ? <img src={sidebarbanner} alt="" /> : ''} <div className="didgest"> <span className="h3">Самое читаемое</span> <div className="didgest_news"> <div className="didgest_image"></div> <div className="didgest_caption"> <a href="#"> <p>Тираннозавр, зомби и взрывающаяся голова. Какие эмодзи ждут нас в будущем и как общаться ими уже сейчас</p> </a> <div className="didgest_credential"> <p className="didgest_date">13 июля 2017 г.</p> <p className="didgest_category">Видео</p> </div> </div> </div> <div className="didgest_news"> <div className="didgest_image"></div> <div className="didgest_caption"> <a href="#"> <p>«Улетаю с этой планеты». Паук так съел сверчка, что всем нам теперь хочется смотреть себе под ноги</p> </a> <div className="didgest_credential"> <p className="didgest_date">13 июля 2017 г.</p> <p className="didgest_category">Видео</p> </div> </div> </div> {this.props.banner ? <img src={rightsidebanner} className="rightsidebanner" alt="" /> : ''} <div className="history-ofaday"> <span className="h3">История дня</span> <div className="history-ofaday_caption"> <a href="#"> <p>Когда включили «Деспасито». Как песня музыкантов из Пуэрто-Рико стала хитом этого лета и превратилась в мем</p> </a> <div className="didgest_credential"> <p className="didgest_date">13 июля 2017 г.</p> <p className="didgest_category">Видео</p> </div> </div> </div> </div> </div> ) } }
Filter.js
baosen/horribletime
import React from 'react'; import { InputGroup, FormControl, Glyphicon } from 'react-bootstrap'; import { margin } from './Show.css' let callbacks = []; // callbacks containing functions to call on filter change. // Register a callback to signal changes to the filter input. export function register(cb) { callbacks.push(cb); } // Signal elements that user wants to filter shows. function signal(val) { for (let callback of callbacks) callback(val); } // Filter anime shows displaying those within the filter. export default class Filter extends React.Component { constructor() { super(); } // Filter shows. filter(keypressEvent) { signal(keypressEvent.target.value); } render() { return ( <div> <InputGroup className={ margin }> <InputGroup.Addon><Glyphicon glyph="filter" /></InputGroup.Addon> <FormControl type="text" onChange={ this.filter } placeholder="Type in the name of the anime show you are searching for here." /> </InputGroup> </div> ) } };
node_modules/react-icons/md/devices-other.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdDevicesOther = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m35 30v-13.4h-6.6v13.4h6.6z m1.6-16.6c0.9 0 1.8 0.7 1.8 1.6v16.6c0 0.9-0.9 1.8-1.8 1.8h-10c-0.8 0-1.6-0.9-1.6-1.8v-16.6c0-0.9 0.8-1.6 1.6-1.6h10z m-18.2 15.7c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m3.2-9.1v3c1.1 0.9 1.8 2.2 1.8 3.6s-0.7 2.9-1.8 3.8v3h-6.6v-3c-1-0.9-1.6-2.3-1.6-3.8s0.6-2.7 1.6-3.6v-3h6.6z m-16.6-10v20h6.6v3.4h-6.6c-1.8 0-3.4-1.6-3.4-3.4v-20c0-1.8 1.6-3.4 3.4-3.4h30v3.4h-30z"/></g> </Icon> ) export default MdDevicesOther
.eslintrc.js
skystebnicki/chamel
module.exports = { env: { browser: true, es6: true, }, extends: ['eslint:recommended', 'plugin:react/recommended', 'prettier'], parser: 'babel-eslint', plugins: ['prettier', 'react'], rules: { 'prettier/prettier': 'error', }, };
example/main.js
ubergrape/react-visibility-sensor
'use strict'; var React = require('react'); var ReactDOM = require('react-dom') var VisibilitySensor = require('../'); var Example = React.createClass({ getInitialState: function () { return { msg: '' }; }, onChange: function (isVisible) { this.setState({ msg: 'Element is now ' + (isVisible ? 'visible' : 'hidden') }); }, render: function () { var self = this; return ( <div> <p className='msg'>{this.state.msg}</p> <div className='before'></div> <VisibilitySensor containment={this.props.containment} onChange={this.onChange}> <div className='sensor' /> </VisibilitySensor> <div className='after'></div> </div> ); } }); ReactDOM.render(React.createElement(Example), document.getElementById('example')); var container = document.getElementById('example-container'); var elem = container.querySelector('.inner'); container.scrollTop = 320; container.scrollLeft = 320; ReactDOM.render(React.createElement(Example, { containment: container }), elem);
ajax/libs/elfinder/2.1.14/js/i18n/elfinder.nl.min.js
joeyparrish/cdnjs
elFinder&&elFinder.prototype&&"object"==typeof elFinder.prototype.i18&&(elFinder.prototype.i18.nl={translator:"Barry vd. Heuvel &lt;barry@fruitcakestudio.nl&gt;",language:"Nederlands",direction:"ltr",dateFormat:"d-m-Y H:i",fancyDateFormat:"$1 H:i",messages:{error:"Fout",errUnknown:"Onbekend fout.",errUnknownCmd:"Onbekend commando.",errJqui:"Ongeldige jQuery UI configuratie. Selectable, draggable en droppable componenten moeten aanwezig zijn.",errNode:"Voor elFinder moet een DOM Element gemaakt worden.",errURL:"Ongeldige elFinder configuratie! URL optie is niet ingesteld.",errAccess:"Toegang geweigerd.",errConnect:"Kan geen verbinding met de backend maken.",errAbort:"Verbinding afgebroken.",errTimeout:"Verbinding time-out.",errNotFound:"Backend niet gevonden.",errResponse:"Ongeldige reactie van de backend.",errConf:"Ongeldige backend configuratie.",errJSON:"PHP JSON module niet geïnstalleerd.",errNoVolumes:"Leesbaar volume is niet beschikbaar.",errCmdParams:'Ongeldige parameters voor commando "$1".',errDataNotJSON:"Data is niet JSON.",errDataEmpty:"Data is leeg.",errCmdReq:"Backend verzoek heeft een commando naam nodig.",errOpen:'Kan "$1" niet openen.',errNotFolder:"Object is geen map.",errNotFile:"Object is geen bestand.",errRead:'Kan "$1" niet lezen.',errWrite:'Kan niet schrijven in "$1".',errPerm:"Toegang geweigerd.",errLocked:'"$1" is vergrendeld en kan niet hernoemd, verplaats of verwijderd worden.',errExists:'Bestand "$1" bestaat al.',errInvName:"Ongeldige bestandsnaam.",errFolderNotFound:"Map niet gevonden.",errFileNotFound:"Bestand niet gevonden.",errTrgFolderNotFound:'Doelmap"$1" niet gevonden.',errPopup:"De browser heeft voorkomen dat de pop-up is geopend. Pas de browser instellingen aan om de popup te kunnen openen.",errMkdir:'Kan map "$1" niet aanmaken.',errMkfile:'Kan bestand "$1" niet aanmaken.',errRename:'Kan "$1" niet hernoemen.',errCopyFrom:'Bestanden kopiëren van "$1" is niet toegestaan.',errCopyTo:'Bestanden kopiëren naar "$1" is niet toegestaan.',errMkOutLink:"Kan geen link maken buiten de hoofdmap.",errUpload:"Upload fout.",errUploadFile:'Kan "$1" niet uploaden.',errUploadNoFiles:"Geen bestanden gevonden om te uploaden.",errUploadTotalSize:"Data overschrijdt de maximale grootte.",errUploadFileSize:"Bestand overschrijdt de maximale grootte.",errUploadMime:"Bestandstype niet toegestaan.",errUploadTransfer:'"$1" overdrachtsfout.',errUploadTemp:"Kan geen tijdelijk bestand voor de upload maken.",errNotReplace:'Object "$1" bestaat al op deze locatie en kan niet vervangen worden door een ander type object.',errReplace:'Kan "$1" niet vervangen.',errSave:'Kan "$1" niet opslaan.',errCopy:'Kan "$1" niet kopiëren.',errMove:'Kan "$1" niet verplaatsen.',errCopyInItself:'Kan "$1" niet in zichzelf kopiëren.',errRm:'Kan "$1" niet verwijderen.',errRmSrc:"Kan bronbestanden niet verwijderen.",errExtract:'Kan de bestanden van "$1" niet uitpakken.',errArchive:"Kan het archief niet maken.",errArcType:"Archief type is niet ondersteund.",errNoArchive:"Bestand is geen archief of geen ondersteund archief type.",errCmdNoSupport:"Backend ondersteund dit commando niet.",errReplByChild:'De map "$1" kan niet vervangen worden door een item uit die map.',errArcSymlinks:"Om veiligheidsredenen kan een bestand met symlinks of bestanden met niet toegestane namen niet worden uitgepakt .",errArcMaxSize:"Archief overschrijdt de maximale bestandsgrootte.",errResize:'Kan het formaat van "$1" niet wijzigen.',errResizeDegree:"Ongeldig aantal graden om te draaien.",errResizeRotate:"Afbeelding kan niet gedraaid worden.",errResizeSize:"Ongeldig afbeelding formaat.",errResizeNoChange:"Afbeelding formaat is niet veranderd.",errUsupportType:"Bestandstype wordt niet ondersteund.",errNotUTF8Content:'Bestand "$1" is niet in UTF-8 and kan niet aangepast worden.',errNetMount:'Kan "$1" niet mounten.',errNetMountNoDriver:"Niet ondersteund protocol.",errNetMountFailed:"Mount mislukt.",errNetMountHostReq:"Host is verplicht.",errSessionExpires:"Uw sessie is verlopen vanwege inactiviteit.",errCreatingTempDir:'Kan de tijdelijke map niet aanmaken: "$1" ',errFtpDownloadFile:'Kan het bestand niet downloaden vanaf FTP: "$1"',errFtpUploadFile:'Kan het bestand niet uploaden naar FTP: "$1"',errFtpMkdir:'Kan het externe map niet aanmaken op de FTP-server: "$1"',errArchiveExec:'Er is een fout opgetreden bij het archivering van de bestanden: "$1" ',errExtractExec:'Er is een fout opgetreden bij het uitpakken van de bestanden: "$1" ',errNetUnMount:"Kan niet unmounten",errConvUTF8:"Kan niet converteren naar UTF-8",errFolderUpload:"Probeer Google Chrome, als je de map wil uploaden.",cmdarchive:"Maak archief",cmdback:"Vorige",cmdcopy:"Kopieer",cmdcut:"Knip",cmddownload:"Download",cmdduplicate:"Dupliceer",cmdedit:"Pas bestand aan",cmdextract:"Bestanden uit archief uitpakken",cmdforward:"Volgende",cmdgetfile:"Kies bestanden",cmdhelp:"Over deze software",cmdhome:"Home",cmdinfo:"Bekijk info",cmdmkdir:"Nieuwe map",cmdmkfile:"Nieuw tekstbestand",cmdopen:"Open",cmdpaste:"Plak",cmdquicklook:"Voorbeeld",cmdreload:"Vernieuwen",cmdrename:"Naam wijzigen",cmdrm:"Verwijder",cmdsearch:"Zoek bestanden",cmdup:"Ga een map hoger",cmdupload:"Upload bestanden",cmdview:"Bekijk",cmdresize:"Formaat wijzigen",cmdsort:"Sorteren",cmdnetmount:"Mount netwerk volume",cmdnetunmount:"Unmount",cmdplaces:"Naar Plaatsen",cmdchmod:"Wijzig modus",btnClose:"Sluit",btnSave:"Opslaan",btnRm:"Verwijder",btnApply:"Toepassen",btnCancel:"Annuleren",btnNo:"Nee",btnYes:"Ja",btnMount:"Mount",btnApprove:"Ga naar $1 & keur goed",btnUnmount:"Unmount",btnConv:"Converteer",btnCwd:"Hier",btnVolume:"Volume",btnAll:"Alles",btnMime:"MIME Type",btnFileName:"Bestandsnaam",btnSaveClose:"Opslaan & Sluiten",btnBackup:"Back-up",ntfopen:"Bezig met openen van map",ntffile:"Bezig met openen bestand",ntfreload:"Herladen map inhoud",ntfmkdir:"Bezig met map maken",ntfmkfile:"Bezig met Bestanden maken",ntfrm:"Verwijderen bestanden",ntfcopy:"Kopieer bestanden",ntfmove:"Verplaats bestanden",ntfprepare:"Voorbereiden kopiëren",ntfrename:"Hernoem bestanden",ntfupload:"Bestanden uploaden actief",ntfdownload:"Bestanden downloaden actief",ntfsave:"Bestanden opslaan",ntfarchive:"Archief aan het maken",ntfextract:"Bestanden uitpakken actief",ntfsearch:"Zoeken naar bestanden",ntfresize:"Formaat wijzigen van afbeeldingen",ntfsmth:"Iets aan het doen",ntfloadimg:"Laden van plaatje",ntfnetmount:"Mounten van netwerk volume",ntfnetunmount:"Unmounten van netwerk volume",ntfdim:"Opvragen afbeeldingen dimensies",ntfreaddir:"Map informatie lezen",ntfurl:"URL van link ophalen",ntfchmod:"Bestandsmodus wijzigen",ntfpreupload:"Upload bestandsnaam verifiëren",dateUnknown:"onbekend",Today:"Vandaag",Yesterday:"Gisteren",msJan:"Jan",msFeb:"Feb",msMar:"Mar",msApr:"Apr",msMay:"Mei",msJun:"Jun",msJul:"Jul",msAug:"Aug",msSep:"Sep",msOct:"Okt",msNov:"Nov",msDec:"Dec",January:"Januari",February:"Februari",March:"Maart",April:"April",May:"Mei",June:"Juni",July:"Juli",August:"Augustus",September:"September",October:"Oktober",November:"November",December:"December",Sunday:"Zondag",Monday:"Maandag",Tuesday:"Dinsdag",Wednesday:"Woensdag",Thursday:"Donderdag",Friday:"Vrijdag",Saturday:"Zaterdag",Sun:"Zo",Mon:"Ma",Tue:"Di",Wed:"Wo",Thu:"Do",Fri:"Vr",Sat:"Za",sortname:"op naam",sortkind:"op type",sortsize:"op grootte",sortdate:"op datum",sortFoldersFirst:"Mappen eerst","untitled file.txt":"NieuwBestand.txt","untitled folder":"NieuweMap",Archive:"NieuwArchief",confirmReq:"Bevestiging nodig",confirmRm:"Weet u zeker dat u deze bestanden wil verwijderen?<br/>Deze actie kan niet ongedaan gemaakt worden!",confirmRepl:"Oud bestand vervangen door het nieuwe bestand?",confirmConvUTF8:"Niet in UTF-8<br/>Converteren naar UTF-8?<br/>De inhoud wordt UTF-8 door op te slaan na de conversie.",confirmNotSave:"Het is aangepast.<br/>Wijzigingen gaan verloren als je niet opslaat.",apllyAll:"Toepassen op alles",name:"Naam",size:"Grootte",perms:"Rechten",modify:"Aangepast",kind:"Type",read:"lees",write:"schrijf",noaccess:"geen toegang",and:"en",unknown:"onbekend",selectall:"Selecteer alle bestanden",selectfiles:"Selecteer bestand(en)",selectffile:"Selecteer eerste bestand",selectlfile:"Selecteer laatste bestand",viewlist:"Lijst weergave",viewicons:"Icoon weergave",places:"Plaatsen",calc:"Bereken",path:"Pad",aliasfor:"Alias voor",locked:"Vergrendeld",dim:"Dimensies",files:"Bestanden",folders:"Mappen",items:"Items",yes:"ja",no:"nee",link:"Link",searcresult:"Zoek resultaten",selected:"geselecteerde items",about:"Over",shortcuts:"Snelkoppelingen",help:"Help",webfm:"Web bestandsmanager",ver:"Versie",protocolver:"protocol versie",homepage:"Project home",docs:"Documentatie",github:"Fork ons op Github",twitter:"Volg ons op twitter",facebook:"Wordt lid op facebook",team:"Team",chiefdev:"Hoofd ontwikkelaar",developer:"ontwikkelaar",contributor:"bijdrager",maintainer:"onderhouder",translator:"vertaler",icons:"Iconen",dontforget:"En vergeet je handdoek niet!",shortcutsof:"Snelkoppelingen uitgeschakeld",dropFiles:"Sleep hier uw bestanden heen",or:"of",selectForUpload:"Selecteer bestanden om te uploaden",moveFiles:"Verplaats bestanden",copyFiles:"Kopieer bestanden",rmFromPlaces:"Verwijder uit Plaatsen",aspectRatio:"Aspect ratio",scale:"Schaal",width:"Breedte",height:"Hoogte",resize:"Verkleinen",crop:"Bijsnijden",rotate:"Draaien","rotate-cw":"Draai 90 graden rechtsom","rotate-ccw":"Draai 90 graden linksom",degree:"°",netMountDialogTitle:"Mount netwerk volume",protocol:"Protocol",host:"Host",port:"Poort",user:"Gebruikersnaams",pass:"Wachtwoord",confirmUnmount:"Weet u zeker dat u $1 wil unmounten?",dropFilesBrowser:"Sleep of plak bestanden vanuit de browser",dropPasteFiles:"Sleep of plak bestanden hier",encoding:"Encodering",locale:"Locale",searchTarget:"Doel: $1",searchMime:"Zoek op invoer MIME Type",owner:"Eigenaar",group:"Groep",other:"Overig",execute:"Uitvoeren",perm:"Rechten",mode:"Modus",kindUnknown:"Onbekend",kindFolder:"Map",kindAlias:"Alias",kindAliasBroken:"Kapot alias",kindApp:"Applicatie",kindPostscript:"Postscript document",kindMsOffice:"Microsoft Office document",kindMsWord:"Microsoft Word document",kindMsExcel:"Microsoft Excel document",kindMsPP:"Microsoft Powerpoint presentation",kindOO:"Open Office document",kindAppFlash:"Flash applicatie",kindPDF:"Portable Document Format (PDF)",kindTorrent:"Bittorrent bestand",kind7z:"7z archief",kindTAR:"TAR archief",kindGZIP:"GZIP archief",kindBZIP:"BZIP archief",kindXZ:"XZ archief",kindZIP:"ZIP archief",kindRAR:"RAR archief",kindJAR:"Java JAR bestand",kindTTF:"True Type font",kindOTF:"Open Type font",kindRPM:"RPM package",kindText:"Tekst bestand",kindTextPlain:"Tekst",kindPHP:"PHP bronbestand",kindCSS:"Cascading style sheet",kindHTML:"HTML document",kindJS:"Javascript bronbestand",kindRTF:"Rich Text Format",kindC:"C bronbestand",kindCHeader:"C header bronbestand",kindCPP:"C++ bronbestand",kindCPPHeader:"C++ header bronbestand",kindShell:"Unix shell script",kindPython:"Python bronbestand",kindJava:"Java bronbestand",kindRuby:"Ruby bronbestand",kindPerl:"Perl bronbestand",kindSQL:"SQL bronbestand",kindXML:"XML document",kindAWK:"AWK bronbestand",kindCSV:"Komma gescheiden waardes",kindDOCBOOK:"Docbook XML document",kindMarkdown:"Markdown tekst",kindImage:"Afbeelding",kindBMP:"BMP afbeelding",kindJPEG:"JPEG afbeelding",kindGIF:"GIF afbeelding",kindPNG:"PNG afbeelding",kindTIFF:"TIFF afbeelding",kindTGA:"TGA afbeelding",kindPSD:"Adobe Photoshop afbeelding",kindXBITMAP:"X bitmap afbeelding",kindPXM:"Pixelmator afbeelding",kindAudio:"Audio media",kindAudioMPEG:"MPEG audio",kindAudioMPEG4:"MPEG-4 audio",kindAudioMIDI:"MIDI audio",kindAudioOGG:"Ogg Vorbis audio",kindAudioWAV:"WAV audio",AudioPlaylist:"MP3 playlist",kindVideo:"Video media",kindVideoDV:"DV video",kindVideoMPEG:"MPEG video",kindVideoMPEG4:"MPEG-4 video",kindVideoAVI:"AVI video",kindVideoMOV:"Quick Time video",kindVideoWM:"Windows Media video",kindVideoFlash:"Flash video",kindVideoMKV:"Matroska video",kindVideoOGG:"Ogg video"}}); //# sourceMappingURL=elfinder.nl.min.js.map
src/_examples/App.js
beestripes/react-highcharts-wrapper
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; import routes from './routesMap'; const App = () => { return ( <div className="App"> <Router> <div> <sidebar> <a href="https://react-highcharts-wrapper.firebaseapp.com/">{`< Back to home`}</a> <h1><a href="https://github.com/beestripes/react-highcharts-wrapper">React Highcharts Wrapper</a></h1> <h2>Prove that:</h2> <ul> {routes.map((r, idx) => ( // hard load each route <li key={idx}><a href={r.path}>{r.title}</a></li> ))} </ul> </sidebar> <main> <Switch> <Redirect from="/" to={routes[0].path} exact /> {routes.map((r, idx) => ( <Route key={idx} path={r.path} exact={r.exact} component={() => <r.main title={r.title} />} /> ))} </Switch> </main> </div> </Router> </div> ); }; export default App;
ajax/libs/reactable/0.9.6/reactable.min.js
jonathantneal/cdnjs
"use strict";(function(a,b){if(typeof define==="function"&&define.amd){define(["react"],b)}else{if(typeof exports==="object"){module.exports=b(require("react"))}else{a.Reactable=b(a.React)}}}(this,function(b){var e={};if(!Array.prototype.map){Array.prototype.map=function(y,x){var r,q,s;if(this==null){throw new TypeError(" this is null or not defined")}var u=Object(this);var v=u.length>>>0;if(typeof y!=="function"){throw new TypeError(y+" is not a function")}if(arguments.length>1){r=x}q=new Array(v);s=0;while(s<v){var t,w;if(s in u){t=u[s];w=y.call(r,t,s,u);q[s]=w}s++}return q}}if(!Array.prototype.indexOf){Array.prototype.indexOf=function(r){var q=this.length>>>0;var s=Number(arguments[1])||0;s=(s<0)?Math.ceil(s):Math.floor(s);if(s<0){s+=q}for(;s<q;s++){if(s in this&&this[s]===r){return s}}return -1}}if(!Array.prototype.find){Object.defineProperty(Array.prototype,"find",{enumerable:false,configurable:true,writable:true,value:function(q){if(this==null){throw new TypeError("Array.prototype.find called on null or undefined")}if(typeof q!=="function"){throw new TypeError("predicate must be a function")}var v=Object(this);var t=v.length>>>0;var r=arguments[1];var u;for(var s=0;s<t;s++){if(s in v){u=v[s];if(q.call(r,u,s,v)){return u}}}return undefined}})}if(!Array.isArray){Array.isArray=function(q){return Object.prototype.toString.call(q)==="[object Array]"}}if(!Object.assign){Object.defineProperty(Object,"assign",{enumerable:false,configurable:true,writable:true,value:function(x,q){if(x===undefined||x===null){throw new TypeError("Cannot convert first argument to object")}var z=Object(x);for(var r=1;r<arguments.length;r++){var u=arguments[r];if(u===undefined||u===null){continue}var s=Object.keys(Object(u));for(var t=0,w=s.length;t<w;t++){var y=s[t];var v=Object.getOwnPropertyDescriptor(u,y);if(v!==undefined&&v.enumerable){z[y]=u[y]}}}return z}})}function l(q){this.content=q}l.prototype.toString=function(){return this.content};function n(q){return q!==null&&typeof(q)!=="undefined"&&typeof(q.toString==="function")}function h(q){return q!==null&&typeof(q)==="object"&&typeof(q.props)!=="undefined"}b.Children.children=function(q){return b.Children.map(q,function(r){return r})||[]};e.unsafe=function(q){return new l(q)};e.Sort={Numeric:function(s,q){var t=parseFloat(s.toString().replace(",",""));var r=parseFloat(q.toString().replace(",",""));if(isNaN(t)&&isNaN(r)){t=s;r=q}else{if(isNaN(t)){return 1}if(isNaN(r)){return -1}}if(t<r){return -1}if(t>r){return 1}return 0},Currency:function(r,q){if(r[0]==="$"){r=r.substring(1)}if(q[0]==="$"){q=q.substring(1)}return e.Sort.Numeric(r,q)},Date:function(s,q){var t=Date.parse(s);var r=Date.parse(q);if(isNaN(t)||isNaN(r)){return e.Sort.Numeric(s,q)}if(t>r){return 1}if(r>t){return -1}return 0},CaseInsensitive:function(s,q){var t=s.toLowerCase();var r=q.toLowerCase();if(t>r){return 1}if(r>t){return -1}return 0}};var g=e.Td=b.createClass({displayName:"Td",handleClick:function(q){if(typeof this.props.handleClick!=="undefined"){return this.props.handleClick(q,this)}},render:function(){var s={"data-column":this.props.column.key,className:this.props.className,onClick:this.handleClick};for(var q in this.props.column){if(q!=="key"&&q!=="name"){s[q]=this.props.column[q]}}var r=this.props.data;if(typeof(this.props.children)!=="undefined"){if(h(this.props.children)){r=this.props.children}else{if(typeof(this.props.data)==="undefined"&&n(this.props.children)){r=this.props.children.toString()}}if(this.props.children instanceof l){s.dangerouslySetInnerHTML={__html:this.props.children.toString()}}else{s.children=r}}return b.DOM.td(s)}});var m=e.Tr=b.createClass({displayName:"Tr",statics:{childNode:g,dataType:"object"},render:function(){var q=d(b.Children.children(this.props.children));if(this.props.data&&this.props.columns&&typeof this.props.columns.map==="function"){if(typeof(q.concat)==="undefined"){console.log(q)}q=q.concat(this.props.columns.map(function(u,s){if(this.props.data.hasOwnProperty(u.key)){var v=this.props.data[u.key];var t={};if(typeof(v)!=="undefined"&&v!==null&&v.__reactableMeta===true){t=v.props;v=v.value}return g(Object.assign({column:u,key:u.key},t),v)}else{return g({column:u,key:u.key})}}.bind(this)))}var r=o(this.props);return b.DOM.tr(r,q)}});var f=e.Thead=b.createClass({displayName:"Thead",getColumns:function(){return b.Children.map(this.props.children,function(q){if(typeof q.props.children==="string"){return q.props.children}else{throw new TypeError("<th> must have a string child")}})},handleClickTh:function(q){this.props.onSort(q.key)},render:function(){var u=[];for(var r=0;r<this.props.columns.length;r++){var t=this.props.columns[r];var q="";if(this.props.sortableColumns[t.key]){q+="reactable-header-sortable "}if(this.props.sort.column===t.key){q+="reactable-header-sort";if(this.props.sort.direction===1){q+="-asc"}else{q+="-desc"}}u.push(c({className:q,key:r,onClick:this.handleClickTh.bind(this,t)},t.label))}var s=o(this.props);return b.DOM.thead(s,(this.props.filtering===true?k({colSpan:this.props.columns.length,onFilter:this.props.onFilter,value:this.props.currentFilter}):""),b.DOM.tr({className:"reactable-column-header"},u))}});var c=e.Th=b.createClass({displayName:"Th",render:function(){if(this.props.children instanceof l){return this.transferPropsTo(b.DOM.th({dangerouslySetInnerHTML:{__html:this.props.children.toString()}}))}else{return this.transferPropsTo(b.DOM.th(null,this.props.children))}}});var p=b.createClass({displayName:"FiltererInput",onChange:function(){this.props.onFilter(this.getDOMNode().value)},render:function(){return(b.DOM.input({type:"text",className:"reactable-filter-input",value:this.props.value,onKeyUp:this.onChange,onChange:this.onChange}))}});var k=b.createClass({displayName:"Filterer",render:function(){if(typeof this.props.colSpan==="undefined"){throw new TypeError("Must pass a colSpan argument to Filterer")}return(b.DOM.tr({className:"reactable-filterer"},b.DOM.td({colSpan:this.props.colSpan},p({onFilter:this.props.onFilter,value:this.props.value}))))}});var a=b.createClass({displayName:"Paginator",render:function(){if(typeof this.props.colSpan==="undefined"){throw new TypeError("Must pass a colSpan argument to Paginator")}if(typeof this.props.numPages==="undefined"){throw new TypeError("Must pass a non-zero numPages argument to Paginator")}if(typeof this.props.currentPage==="undefined"){throw new TypeError("Must pass a currentPage argument to Paginator")}var s=[];for(var q=0;q<this.props.numPages;q++){var t=q;var r="reactable-page-button";if(this.props.currentPage===q){r+=" reactable-current-page"}s.push(b.DOM.a({className:r,key:q,onClick:(function(u){return function(){this.props.onPageChange(u)}.bind(this)}.bind(this))(q)},q+1))}return(b.DOM.tbody({className:"reactable-pagination"},b.DOM.tr(null,b.DOM.td({colSpan:this.props.colSpan},s))))}});var j=e.Table=b.createClass({displayName:"Table",translateColumnsArray:function(q){return q.map(function(t,s){if(typeof(t)==="string"){return{key:t,label:t}}else{if(typeof(t.sortable)!=="undefined"){var r=t.sortable===true?"default":t.sortable;this._sortable[t.key]=r}return t}}.bind(this))},parseChildData:function(q){var r=[];if(typeof(q.children)!=="undefined"){b.Children.forEach(q.children,function(t){var s=t.props.data||{};b.Children.forEach(t.props.children,function(u){if(true){if(typeof(u.props.column)!=="undefined"){var v;if(typeof(u.props.data)!=="undefined"){v=u.props.data}else{if(typeof(u.props.children)!=="undefined"){v=u.props.children}else{console.warn("exports.Td specified without a `data` property or children, ignoring");return}}s[u.props.column]={value:v,props:o(u.props),__reactableMeta:true}}else{console.warn("exports.Td specified without a `column` property, ignoring")}}});r.push({data:s,props:o(t.props),__reactableMeta:true})}.bind(this))}return r},initialize:function(q){this.data=q.data||[];this.data=this.data.concat(this.parseChildData(q));this.initializeSorts(q)},initializeSorts:function(){this._sortable={};for(var s in this.props.sortable){var t=this.props.sortable[s];var r,q;if(t instanceof Object){if(typeof(t.column)!=="undefined"){r=t.column}else{console.warn("Sortable column specified without column name");return}if(typeof(t.sortFunction)==="function"){q=t.sortFunction}else{q="default"}}else{r=t;q="default"}this._sortable[r]=q}},getDefaultProps:function(){var q={sortBy:false,defaultSort:false,itemsPerPage:0};return q},getInitialState:function(){var q={currentPage:0,currentSort:{column:null,direction:1},filter:""};if(this.props.sortBy!==false||this.props.defaultSort!==false){var r=this.props.sortBy||this.props.defaultSort;q.currentSort=this.getCurrentSort(r)}return q},getCurrentSort:function(r){if(r instanceof Object){var q,s;if(typeof(r.column)!=="undefined"){q=r.column}else{console.warn("Default column specified without column name");return}if(typeof(r.direction)!=="undefined"){if(r.direction===1||r.direction==="asc"){s=1}else{if(r.direction===-1||r.direction==="desc"){s=-1}else{console.warn("Invalid default sort specified. Defaulting to ascending");s=1}}}else{s=1}}else{q=r;s=1}return{column:q,direction:s}},updateCurrentSort:function(q){if(q!==false&&q.column!==this.state.currentSort.column&&q.direction!==this.state.currentSort.direction){this.setState({currentSort:this.getCurrentSort(q)})}},componentWillMount:function(){this.initialize(this.props);this.sortByCurrentSort()},componentWillReceiveProps:function(q){this.initialize(q);this.updateCurrentSort(q.sortBy);this.sortByCurrentSort()},onPageChange:function(q){this.setState({currentPage:q})},filterBy:function(q){this.setState({filter:q})},applyFilter:function(t,s){var t=t.toLowerCase();var u=[];for(var r=0;r<s.length;r++){var v=s[r].props.data;for(var q=0;q<this.props.filterable.length;q++){var w=this.props.filterable[q];if(typeof(v[w])!=="undefined"&&v[w].toString().toLowerCase().indexOf(t)>-1){u.push(s[r]);break}}}return u},sortByCurrentSort:function(){var q=this.state.currentSort;if(q.column===null){return}this.data.sort(function(u,s){var t=u[q.column];t=n(t)?t.toString():"";var r=s[q.column];r=n(r)?r.toString():"";if(typeof(this._sortable[q.column])==="undefined"||this._sortable[q.column]==="default"){if(t<r){return -1*q.direction}if(t>r){return 1*q.direction}return 0}else{if(q.direction===1){return this._sortable[q.column](t,r)}else{return this._sortable[q.column](r,t)}}}.bind(this))},onSort:function(r){if(typeof(this._sortable[r])==="undefined"){return}var q=this.state.currentSort;if(q.column===r){q.direction*=-1}else{q.column=r;q.direction=1}this.setState({currentSort:q});this.sortByCurrentSort()},render:function(){var r=[];var u;var y=false;if(this.props.children&&this.props.children.length>0&&this.props.children[0].type.ConvenienceConstructor===f){u=this.props.children[0].getColumns()}else{u=this.props.columns||[]}if(u.length>0){y=true;u=this.translateColumnsArray(u)}if(this.data&&typeof this.data.map==="function"){r=r.concat(this.data.map(function(H,D){var G=H;var F={};if(H.__reactableMeta===true){G=H.data;F=H.props}for(var C in G){if(G.hasOwnProperty(C)){if(y===false){var E={key:C,label:C};if(u.find(function(I){return I.key===E.key})===undefined){u.push(E)}}}}return(m(Object.assign({columns:u,key:D,data:G},F)))}.bind(this)))}if(this.props.sortable===true){for(var v=0;v<u.length;v++){this._sortable[u[v].key]="default"}}var B=false;if(this.props.filterable&&Array.isArray(this.props.filterable)&&this.props.filterable.length>0){B=true}var q=r;if(this.state.filter!==""){q=this.applyFilter(this.state.filter,q)}var s=0;var z=false;var t;var w=this.state.currentPage;var A=q;if(this.props.itemsPerPage>0){s=this.props.itemsPerPage;t=Math.ceil(q.length/s);if(w>t-1){w=t-1}z=true;A=q.slice(w*s,(w+1)*s)}var x=o(this.props);return b.DOM.table(Object.assign({},x),[(u&&u.length>0?f({columns:u,filtering:B,onFilter:this.filterBy,currentFilter:this.state.filter,sort:this.state.currentSort,sortableColumns:this._sortable,onSort:this.onSort,key:"thead"}):null),b.DOM.tbody({className:"reactable-data",key:"tbody"},A),(z===true?a({colSpan:u.length,numPages:t,currentPage:w,onPageChange:this.onPageChange,key:"paginator"}):null)])}});function d(s){var r=[];for(var q in s){r[q]=s}return r}function o(q){q=q||{};var s={};for(var r in q){if(!(r in i)){s[r]=q[r]}}return s}var i={columns:true,sortable:true,filterable:true,sortBy:true,defaultSort:true,itemsPerPage:true,childNode:true,data:true};return e}));
docs/src/pages/demos/selection-controls/Switches.js
cherniavskii/material-ui
import React from 'react'; import Switch from 'material-ui/Switch'; class Switches extends React.Component { state = { checkedA: true, checkedB: true, }; handleChange = name => event => { this.setState({ [name]: event.target.checked }); }; render() { return ( <div> <Switch checked={this.state.checkedA} onChange={this.handleChange('checkedA')} value="checkedA" /> <Switch checked={this.state.checkedB} onChange={this.handleChange('checkedB')} value="checkedB" color="primary" /> <Switch value="checkedC" /> <Switch disabled value="checkedD" /> <Switch disabled checked value="checkedE" /> <Switch defaultChecked value="checkedF" color="default" /> </div> ); } } export default Switches;
packages/flow-upgrade/src/upgrades/0.53.0/ReactUtilityTypes/__tests__/codemod-test.js
MichaelDeBoey/flow
/** * @format */ 'use strict'; const path = require('path'); const fs = require('fs'); const cp = require('child_process'); const jscodeshiftFlowParser = require('jscodeshift/parser/flow'); const jscodeshift = require('jscodeshift').withParser(jscodeshiftFlowParser); const transform = require('../codemod'); const JSCODESHIFT_BIN = path.resolve( __dirname, '../../node_modules/.bin/jscodeshift', ); const FIXTURES_DIR = path.join(__dirname, './fixtures'); const HEADERS = [ // No React. [], // Default import. [`import React from 'react';`], // Default import with named imports. [`import React, {PropTypes} from 'react';`], // Default import, custom name. [`import CustomName from 'react';`], // Namespace import. [`import * as React from 'react';`], // Namespace import, custom name. [`import * as CustomName from 'react';`], // Require. [`const React = require('react');`], // Require second name. [`const React = require('React');`], // Require, custom name. [`const CustomName = require('react');`], // Require, destructured. [`const {PropTypes} = require('react');`], // Require, destructured and not destructured 1. [`const React = require('react');`, `const {PropTypes} = require('react');`], // Require, destructured and not destructured 2. [`const {PropTypes} = require('react');`, `const React = require('react');`], // Destructured `Element`. [`const React = require('react');`, `const {Element} = React;`], // Named import `Element`. [`const React = require('react');`, `import type {Element} from 'react';`], ]; fs.readdirSync(FIXTURES_DIR).forEach(fixture => { test(fixture, () => { const file = path.join(FIXTURES_DIR, fixture); const source = fs.readFileSync(file, 'utf8'); HEADERS.forEach(header => { const root = jscodeshift(`${header.join('\n')}\n\n${source}`); const skipped = !transform(jscodeshift, root); expect(skipped ? null : root.toSource()).toMatchSnapshot(); }); }); });
src/components/App/App.js
dstirling/MyApp
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; import './App.less'; import React from 'react'; import invariant from 'react/lib/invariant'; import NavigationMixin from './NavigationMixin'; import AppStore from '../../stores/AppStore'; import Navbar from '../Navbar'; import ContentPage from '../ContentPage'; import NotFoundPage from '../NotFoundPage'; export default React.createClass({ mixins: [NavigationMixin], propTypes: { path: React.PropTypes.string.isRequired, onSetTitle: React.PropTypes.func.isRequired, onSetMeta: React.PropTypes.func.isRequired, onPageNotFound: React.PropTypes.func.isRequired }, render() { var page = AppStore.getPage(this.props.path); invariant(page !== undefined, 'Failed to load page content.'); this.props.onSetTitle(page.title); if (page.type === 'notfound') { this.props.onPageNotFound(); return React.createElement(NotFoundPage, page); } return ( <div className="App"> <Navbar /> { this.props.path === '/' ? <div className="jumbotron"> <div className="container text-center"> <h1>React</h1> <p>Complex web apps made easy</p> </div> </div> : <div className="container"> <h2>{page.title}</h2> </div> } <ContentPage className="container" {...page} /> <div className="navbar-footer"> <div className="container"> <p className="text-muted"> <span>© KriaSoft</span> <span><a href="/">Home</a></span> <span><a href="/privacy">Privacy</a></span> </p> </div> </div> </div> ); } });