path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
docs/src/sections/FormSection.js
Sipree/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function FormSection() { return ( <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="forms">Forms</Anchor> <small>Input, ButtonInput, FormControls</small> </h1> <p>The <code>{'<Input>'}</code> component renders an input in Bootstrap wrappers. Supports label, help, text input add-ons, validation and use as wrapper. Use <code>getValue()</code> or <code>getChecked()</code> to get the current state. The helper method <code>getInputDOMNode()</code> returns the internal input element. If you don't want the <code>form-group</code> class applied apply the prop named <code>standalone</code>.</p> <ReactPlayground codeText={Samples.Input} /> <h3><Anchor id="input-types">Types</Anchor></h3> <p>Supports <code>select</code>, <code>textarea</code>, as well as standard HTML input types. <code>getValue()</code> returns an array for multiple select.</p> <ReactPlayground codeText={Samples.InputTypes} /> <h3><Anchor id="forms-controls-static">FormControls.Static</Anchor></h3> <p>Static text can be added to your form controls through the use of the <code>FormControls.Static</code> component.</p> <ReactPlayground codeText={Samples.StaticText} /> <h3><Anchor id="button-input-types">Button Input Types</Anchor></h3> <p>Form buttons are encapsulated by <code>ButtonInput</code>. Pass in <code>type="reset"</code> or <code>type="submit"</code> to suit your needs. Styling is the same as <code>Button</code>.</p> <ReactPlayground codeText={Samples.ButtonInput} /> <h3><Anchor id="input-addons">Add-ons</Anchor></h3> <p>Use <code>addonBefore</code> and <code>addonAfter</code> for normal addons, <code>buttonBefore</code> and <code>buttonAfter</code> for button addons. Exotic configurations may require some css on your side.</p> <ReactPlayground codeText={Samples.InputAddons} /> <h3><Anchor id="input-sizes">Sizes</Anchor></h3> <p>Use <code>bsSize</code> to change the size of inputs. It also works with addons and most other options.</p> <ReactPlayground codeText={Samples.InputSizes} /> <h3><Anchor id="input-validation">Validation</Anchor></h3> <p>Set <code>bsStyle</code> to one of <code>success</code>, <code>warning</code> or <code>error</code>. Add <code>hasFeedback</code> to show glyphicon. Glyphicon may need additional styling if there is an add-on or no label.</p> <ReactPlayground codeText={Samples.InputValidation} /> <h3><Anchor id="input-horizontal">Horizontal forms</Anchor></h3> <p>Use <code>labelClassName</code> and <code>wrapperClassName</code> properties to add col classes manually. <code>checkbox</code> and <code>radio</code> types need special treatment because label wraps input.</p> <ReactPlayground codeText={Samples.InputHorizontal} /> <h3><Anchor id="input-wrapper">Use as a wrapper</Anchor></h3> <p>If <code>type</code> is not set, child element(s) will be rendered instead of an input element. <code>getValue()</code> will not work when used this way.</p> <ReactPlayground codeText={Samples.InputWrapper} /> <h3><Anchor id="input-props">Props</Anchor></h3> <PropTable component="InputBase"/> </div> ); }
examples/demos/rendering.js
Incubity/react-big-calendar
import React from 'react'; import BigCalendar from 'react-big-calendar'; import events from '../events'; function Event({ event }) { return ( <span> <strong> {event.title} </strong> { event.desc && (': ' + event.desc)} </span> ) } function EventAgenda({ event }) { return <span> <em style={{ color: 'magenta'}}>{event.title}</em> <p>{ event.desc }</p> </span> } let Rendering = React.createClass({ render(){ return ( <div {...this.props}> <BigCalendar events={events} defaultDate={new Date(2015, 3, 1)} defaultView='agenda' components={{ event: Event, agenda: { event: EventAgenda } }} /> </div> ) } }) export default Rendering;
node_modules/npm-run-all/node_modules/babel-runtime/helpers/jsx.js
chszard/chszard.github.io
"use strict"; exports.__esModule = true; var _for = require("../core-js/symbol/for"); var _for2 = _interopRequireDefault(_for); var _symbol = require("../core-js/symbol"); var _symbol2 = _interopRequireDefault(_symbol); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { var REACT_ELEMENT_TYPE = typeof _symbol2.default === "function" && _for2.default && (0, _for2.default)("react.element") || 0xeac7; return function createRawReactElement(type, props, key, children) { var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = {}; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }; }();
tests/client/disco/containers/TestDiscoPane.js
squarewave/addons-frontend
import React from 'react'; import { Simulate, renderIntoDocument } from 'react-addons-test-utils'; import { findDOMNode } from 'react-dom'; import { loadEntities } from 'core/actions'; import { ADDON_TYPE_EXTENSION, GLOBAL_EVENTS, INSTALL_STATE, } from 'core/constants'; import * as InfoDialog from 'core/containers/InfoDialog'; import { discoResults } from 'disco/actions'; import * as discoApi from 'disco/api'; import createStore from 'disco/store'; import { NAVIGATION_CATEGORY, VIDEO_CATEGORY, } from 'disco/constants'; import * as helpers from 'disco/containers/DiscoPane'; import { getFakeI18nInst, MockedSubComponent } from 'tests/client/helpers'; // Use DiscoPane that isn't wrapped in asyncConnect. const { DiscoPaneBase } = helpers; describe('AddonPage', () => { function render(props) { // Stub InfoDialog since it uses the store and is irrelevant. sinon.stub(InfoDialog, 'default', () => <p>InfoDialog</p>); const store = createStore({ addons: { foo: { type: ADDON_TYPE_EXTENSION } }, discoResults: [{ addon: 'foo' }], }); const results = [{ addon: 'foo', type: ADDON_TYPE_EXTENSION }]; const i18n = getFakeI18nInst(); // We need the providers for i18n and since InstallButton will pull data from the store. return findDOMNode(renderIntoDocument( <DiscoPaneBase store={store} i18n={i18n} results={results} {...props} AddonComponent={MockedSubComponent} /> )); } describe('video', () => { it('is small by default', () => { const root = render(); assert.notOk(root.querySelector('.show-video')); }); it('gets bigger and smaller when clicked', () => { const root = render(); Simulate.click(root.querySelector('.play-video')); assert.ok(root.querySelector('.show-video')); Simulate.click(root.querySelector('.close-video a')); assert.notOk(root.querySelector('.show-video')); }); it('tracks video being played', () => { const fakeTracking = { sendEvent: sinon.stub(), }; const root = render({ _tracking: fakeTracking }); Simulate.click(root.querySelector('.play-video')); assert.ok(fakeTracking.sendEvent.calledWith({ category: VIDEO_CATEGORY, action: 'play', })); }); it('tracks video being closed', () => { const fakeTracking = { sendEvent: sinon.stub(), }; const root = render({ _tracking: fakeTracking }); Simulate.click(root.querySelector('.close-video a')); assert.ok(fakeTracking.sendEvent.calledWith({ category: VIDEO_CATEGORY, action: 'close', })); }); }); describe('loadDataIfNeeded', () => { it('does nothing if there are loaded results', () => { const store = { getState() { return { addons: { foo: {} }, discoResults: [{ addon: 'foo' }] }; }, }; const getAddons = sinon.stub(discoApi, 'getDiscoveryAddons'); return helpers.loadDataIfNeeded({ store }) .then(() => assert.notOk(getAddons.called)); }); it('loads the addons if there are none', () => { const api = { the: 'config' }; const dispatch = sinon.spy(); const store = { dispatch, getState() { return { addons: {}, api, discoResults: [] }; }, }; const entities = { addons: { foo: { slug: 'foo', }, }, discoResults: { foo: { addon: 'foo', }, }, }; const result = { results: ['foo'] }; const getAddons = sinon.stub(discoApi, 'getDiscoveryAddons') .returns(Promise.resolve({ entities, result })); return helpers.loadDataIfNeeded({ store }) .then(() => { assert.ok(getAddons.calledWith({ api })); assert.ok(dispatch.calledWith(loadEntities(entities))); assert.ok(dispatch.calledWith(discoResults([{ addon: 'foo' }]))); }); }); }); describe('mapStateToProps', () => { it('only sets results', () => { const props = helpers.mapStateToProps({ discoResults: [], }); assert.sameMembers(Object.keys(props), ['results']); }); it('sets the results', () => { const props = helpers.mapStateToProps({ addons: { one: { slug: 'one' }, two: { slug: 'two' } }, discoResults: [{ addon: 'two' }], infoDialog: {}, }); assert.deepEqual(props.results, [{ slug: 'two', addon: 'two' }]); }); }); describe('mapDispatchToProps', () => { it('calls dispatch when handleGlobalEvent is called with data', () => { const dispatch = sinon.spy(); const { handleGlobalEvent } = helpers.mapDispatchToProps(dispatch); const payload = { id: 'whatever' }; handleGlobalEvent(payload); assert.ok(dispatch.calledWith({ type: INSTALL_STATE, payload })); }); it('is empty when there is no navigator', () => { const configStub = { get: sinon.stub().returns(true), }; assert.deepEqual( helpers.mapDispatchToProps(sinon.spy(), { _config: configStub }), {}); }); }); describe('componentDidMount', () => { it('sets events', () => { const fakeMozAddonManager = { addEventListener: sinon.stub(), }; render({ mozAddonManager: fakeMozAddonManager }); assert.equal(fakeMozAddonManager.addEventListener.callCount, GLOBAL_EVENTS.length); }); }); describe('See more add-ons link', () => { it('tracks see more addons link being clicked', () => { const fakeTracking = { sendEvent: sinon.stub(), }; const root = render({ _tracking: fakeTracking }); Simulate.click(root.querySelector('.amo-link a')); assert.ok(fakeTracking.sendEvent.calledWith({ category: NAVIGATION_CATEGORY, action: 'click', label: 'See More Add-ons', })); }); }); });
src/components/DatePicker/DatePicker-story.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { action, decorateAction } from '@storybook/addon-actions'; import { withKnobs, boolean, select, text } from '@storybook/addon-knobs'; import DatePicker from '../DatePicker'; import DatePickerInput from '../DatePickerInput'; import DatePickerSkeleton from '../DatePicker/DatePicker.Skeleton'; import WithState from '../../tools/withState'; // Datepickers last argument contains an instance of flatpickr // and will cause action logger to enter an infinite loop. Just don't log that argument const datePickerOnChangeActions = decorateAction([ args => args.slice(0, args.length - 2), ]); const patterns = { 'Short (d{1,2}/d{4})': 'd{1,2}/d{4}', 'Regular (d{1,2}/d{1,2}/d{4})': 'd{1,2}/d{1,2}/d{4}', }; const props = { datePicker: () => ({ id: 'date-picker', light: boolean('Light variant (light in <DatePicker>)', false), onChange: datePickerOnChangeActions('onPickerChange'), }), datePickerInput: () => ({ id: 'date-picker-input-id', className: 'some-class', labelText: text( 'Label text (labelText in <DatePickerInput>)', 'Date Picker label' ), pattern: select( 'The date format (pattern in <DatePickerInput>)', patterns, 'd{1,2}/d{4}' ), placeholder: text( 'Placeholder text (placeholder in <DatePickerInput>)', 'mm/dd/yyyy' ), disabled: boolean('Disabled (disabled in <DatePickerInput>)', false), invalid: boolean( 'Show form validation UI (invalid in <DatePickerInput>)', false ), invalidText: text( 'Form validation UI content (invalidText in <DatePickerInput>)', 'A valid value is required' ), iconDescription: text( 'Icon description (iconDescription in <DatePickerInput>)', 'Icon description' ), onClick: action('onClick'), onChange: action('onInputChange'), }), }; storiesOf('DatePicker', module) .addDecorator(withKnobs) .add( 'simple', () => ( <DatePicker {...props.datePicker()} short={boolean('Use shorter width (short in <DatePicker>)', false)} datePickerType="simple"> <DatePickerInput {...props.datePickerInput()} /> </DatePicker> ), { info: { text: 'A simple Date Picker consists of an input field and no calendar.', }, } ) .add( 'single with calendar', () => ( <DatePicker {...props.datePicker()} datePickerType="single" dateFormat={text( 'The date format (dateFormat in <DatePicker>)', 'm/d/Y' )}> <DatePickerInput {...props.datePickerInput()} /> </DatePicker> ), { info: { text: ` A single Date Picker consists of an input field and a calendar. `, }, } ) .add( 'range with calendar', () => { const datePickerInputProps = props.datePickerInput(); return ( <DatePicker {...props.datePicker()} datePickerType="range" dateFormat={text( 'The date format (dateFormat in <DatePicker>)', 'm/d/Y' )}> <DatePickerInput {...datePickerInputProps} id="date-picker-input-id-start" /> <DatePickerInput {...datePickerInputProps} id="date-picker-input-id-end" /> </DatePicker> ); }, { info: { text: ` A range Date Picker consists of two input fields and a calendar. `, }, } ) .add( 'range with calendar and min/max dates', () => { const datePickerInputProps = props.datePickerInput(); return ( <DatePicker {...props.datePicker()} minDate="1/10/2020" maxDate="1/20/2020" datePickerType="range" dateFormat="m/d/Y"> <DatePickerInput {...datePickerInputProps} id="date-picker-input-id" /> <DatePickerInput {...datePickerInputProps} id="date-picker-input-id-2" /> </DatePicker> ); }, { info: { text: ` A range Date Picker consists of two input fields and a calendar, and optionally, the minDate and maxDate fields. `, }, } ) .add( 'fully controlled', () => ( <WithState initialState={{ date: '' }}> {({ state, setState }) => ( <> <DatePicker datePickerType="single" dateFormat="m/d/Y" value={state.date} onChange={eventOrDates => { const value = eventOrDates.target ? eventOrDates.target.value : eventOrDates[0]; setState({ date: value }); }}> <DatePickerInput {...props.datePickerInput()} id="date-picker-input-id" /> </DatePicker> <button onClick={() => setState({ date: '01/01/2011' })}> Click me to set to 01/01/2011 </button> </> )} </WithState> ), { info: { text: ` If your application needs to control the value of the date picker and be notified of any changes. `, }, } ) .add('skeleton', () => <DatePickerSkeleton range />, { info: { text: ` Placeholder skeleton state to use when content is loading. `, }, });
sourcestats/webpack/components/App.js
Fizzadar/SourceServerStats
// Source Server Stats // File: sourcestats/webpack/components/app.js // Desc: app container import React from 'react'; import { Link } from 'react-router'; export class AppContainer extends React.Component { render() { return (<div> <div id="header"> <h1><a href="/"> <i className="icon icon-steam"></i> </a></h1> <ul className="nav"> <li><Link to={'/servers'} activeClassName='active'>Servers</Link></li> <li><Link to={'/maps'} activeClassName='active'>Maps</Link></li> <li><Link to={'/games'} activeClassName='active'>Games</Link></li> <li><Link to={'/global'} activeClassName='active'>Global</Link></li> </ul> <ul className="nav right"> <li> An experiment by <a href="http://pointlessramblings.com">Fizzadar</a> - <a href="https://github.com/Fizzadar/SourceServerStats">GitHub</a> </li> </ul> </div> <div>{this.props.children}</div> </div>); } }
ajax/libs/material-ui/5.0.0-beta.2/legacy/Radio/Radio.js
cdnjs/cdnjs
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import { refType } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import { alpha } from '@material-ui/system'; import SwitchBase from '../internal/SwitchBase'; import useThemeProps from '../styles/useThemeProps'; import RadioButtonIcon from './RadioButtonIcon'; import capitalize from '../utils/capitalize'; import createChainedFunction from '../utils/createChainedFunction'; import useRadioGroup from '../RadioGroup/useRadioGroup'; import radioClasses, { getRadioUtilityClass } from './radioClasses'; import styled, { rootShouldForwardProp } from '../styles/styled'; import { jsx as _jsx } from "react/jsx-runtime"; var useUtilityClasses = function useUtilityClasses(styleProps) { var classes = styleProps.classes, color = styleProps.color; var slots = { root: ['root', "color".concat(capitalize(color))] }; return _extends({}, classes, composeClasses(slots, getRadioUtilityClass, classes)); }; var RadioRoot = styled(SwitchBase, { shouldForwardProp: function shouldForwardProp(prop) { return rootShouldForwardProp(prop) || prop === 'classes'; }, name: 'MuiRadio', slot: 'Root', overridesResolver: function overridesResolver(props, styles) { var styleProps = props.styleProps; return [styles.root, styles["color".concat(capitalize(styleProps.color))]]; } })(function (_ref) { var theme = _ref.theme, styleProps = _ref.styleProps; return _extends({ color: theme.palette.text.secondary, '&:hover': { backgroundColor: alpha(styleProps.color === 'default' ? theme.palette.action.active : theme.palette[styleProps.color].main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, styleProps.color !== 'default' && _defineProperty({}, "&.".concat(radioClasses.checked), { color: theme.palette[styleProps.color].main }), _defineProperty({}, "&.".concat(radioClasses.disabled), { color: theme.palette.action.disabled })); }); var defaultCheckedIcon = /*#__PURE__*/_jsx(RadioButtonIcon, { checked: true }); var defaultIcon = /*#__PURE__*/_jsx(RadioButtonIcon, {}); var Radio = /*#__PURE__*/React.forwardRef(function Radio(inProps, ref) { var props = useThemeProps({ props: inProps, name: 'MuiRadio' }); var checkedProp = props.checked, _props$color = props.color, color = _props$color === void 0 ? 'primary' : _props$color, nameProp = props.name, onChangeProp = props.onChange, _props$size = props.size, size = _props$size === void 0 ? 'medium' : _props$size, other = _objectWithoutProperties(props, ["checked", "color", "name", "onChange", "size"]); var styleProps = _extends({}, props, { color: color, size: size }); var classes = useUtilityClasses(styleProps); var radioGroup = useRadioGroup(); var checked = checkedProp; var onChange = createChainedFunction(onChangeProp, radioGroup && radioGroup.onChange); var name = nameProp; if (radioGroup) { if (typeof checked === 'undefined') { checked = radioGroup.value === props.value; } if (typeof name === 'undefined') { name = radioGroup.name; } } return /*#__PURE__*/_jsx(RadioRoot, _extends({ type: "radio", icon: /*#__PURE__*/React.cloneElement(defaultIcon, { fontSize: size === 'small' ? 'small' : 'medium' }), checkedIcon: /*#__PURE__*/React.cloneElement(defaultCheckedIcon, { fontSize: size === 'small' ? 'small' : 'medium' }), styleProps: styleProps, classes: classes, name: name, checked: checked, onChange: onChange, ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Radio.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, the component is checked. */ checked: PropTypes.bool, /** * The icon to display when the component is checked. */ checkedIcon: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ color: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]), /** * If `true`, the component is disabled. */ disabled: PropTypes.bool, /** * If `true`, the ripple effect is disabled. */ disableRipple: PropTypes.bool, /** * The icon to display when the component is unchecked. */ icon: PropTypes.node, /** * The id of the `input` element. */ id: PropTypes.string, /** * [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, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the state is changed. * * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: PropTypes.func, /** * If `true`, the `input` element is required. */ required: PropTypes.bool, /** * The size of the component. * `small` is equivalent to the dense radio styling. * @default 'medium' */ size: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]), /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The value of the component. The DOM API casts this to a string. */ value: PropTypes.any } : void 0; export default Radio;
ajax/libs/extjs/4.2.1/src/button/Manager.js
thejameskyle/cdnjs
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * @private */ Ext.define('Ext.button.Manager', { singleton: true, alternateClassName: 'Ext.ButtonToggleManager', groups: {}, pressedButton: null, buttonSelector: '.' + Ext.baseCSSPrefix + 'btn', init: function() { var me = this; if (!me.initialized) { Ext.getDoc().on({ keydown: me.onDocumentKeyDown, mouseup: me.onDocumentMouseUp, scope: me }); me.initialized = true; } }, // Buttons must react to SPACE and ENTER to trigger the click handler. // Now that they are `<a>` elements, we use a keydown listener. onDocumentKeyDown: function(e) { var k = e.getKey(), btn; // SPACE and ENTER trigger a click if (k === e.SPACE || k === e.ENTER) { // Look for a Button's encapsulating element btn = e.getTarget(this.buttonSelector); // If found, fire the Button's onClick if (btn) { Ext.getCmp(btn.id).onClick(e); } } }, // Called by buton instances. // Track the button which was mousedowned upon so that the next *document* mouseup can be delivered to it // in case mouse is moved outside of button element. onButtonMousedown: function(button, e) { var pressed = this.pressedButton; if (pressed) { pressed.onMouseUp(e); } this.pressedButton = button; }, onDocumentMouseUp: function(e) { var pressed = this.pressedButton; if (pressed) { pressed.onMouseUp(e); this.pressedButton = null; } }, toggleGroup: function(btn, state) { if (state) { var g = this.groups[btn.toggleGroup], length = g.length, i; for (i = 0; i < length; i++) { if (g[i] !== btn) { g[i].toggle(false); } } } }, register: function(btn) { var me = this, groups = this.groups, group = groups[btn.toggleGroup]; me.init(); if (!btn.toggleGroup) { return; } if (!group) { group = groups[btn.toggleGroup] = []; } group.push(btn); btn.on('toggle', me.toggleGroup, me); }, unregister: function(btn) { if (!btn.toggleGroup) { return; } var me = this, group = me.groups[btn.toggleGroup]; if (group) { Ext.Array.remove(group, btn); btn.un('toggle', me.toggleGroup, me); } }, // Gets the pressed button in the passed group or null // @param {String} group // @return {Ext.button.Button} getPressed: function(group) { var g = this.groups[group], i = 0, len; if (g) { for (len = g.length; i < len; i++) { if (g[i].pressed === true) { return g[i]; } } } return null; } });
ajax/libs/F2/1.3.1/f2.no-bootstrap.min.js
toddmotto/cdnjs
/*! F2 - v1.3.1 - 10-15-2013 - See below for copyright and license */ (function(exports){if(!exports.F2||exports.F2_TESTING_MODE){/*! 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. */ "object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(e){return 10>e?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,o,i,a,s=gap,c=t[e];switch(c&&"object"==typeof c&&"function"==typeof c.toJSON&&(c=c.toJSON(e)),"function"==typeof rep&&(c=rep.call(t,e,c)),typeof c){case"string":return quote(c);case"number":return isFinite(c)?c+"":"null";case"boolean":case"null":return c+"";case"object":if(!c)return"null";if(gap+=indent,a=[],"[object Array]"===Object.prototype.toString.apply(c)){for(i=c.length,n=0;i>n;n+=1)a[n]=str(n,c)||"null";return o=0===a.length?"[]":gap?"[\n"+gap+a.join(",\n"+gap)+"\n"+s+"]":"["+a.join(",")+"]",gap=s,o}if(rep&&"object"==typeof rep)for(i=rep.length,n=0;i>n;n+=1)"string"==typeof rep[n]&&(r=rep[n],o=str(r,c),o&&a.push(quote(r)+(gap?": ":":")+o));else for(r in c)Object.prototype.hasOwnProperty.call(c,r)&&(o=str(r,c),o&&a.push(quote(r)+(gap?": ":":")+o));return o=0===a.length?"{}":gap?"{\n"+gap+a.join(",\n"+gap)+"\n"+s+"}":"{"+a.join(",")+"}",gap=s,o}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){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(){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={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;"function"!=typeof JSON.stringify&&(JSON.stringify=function(e,t,n){var r;if(gap="",indent="","number"==typeof n)for(r=0;n>r;r+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw Error("JSON.stringify");return str("",{"":e})}),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(e,t){var n,r,o=e[t];if(o&&"object"==typeof o)for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(r=walk(o,n),void 0!==r?o[n]=r:delete o[n]);return reviver.call(e,t,o)}var j;if(text+="",cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\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,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;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(e,t){function n(e){var t=ht[e]={};return Y.each(e.split(tt),function(e,n){t[n]=!0}),t}function r(e,n,r){if(r===t&&1===e.nodeType){var o="data-"+n.replace(mt,"-$1").toLowerCase();if(r=e.getAttribute(o),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:gt.test(r)?Y.parseJSON(r):r}catch(i){}Y.data(e,n,r)}else r=t}return r}function o(e){var t;for(t in e)if(("data"!==t||!Y.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function i(){return!1}function a(){return!0}function s(e){return!e||!e.parentNode||11===e.parentNode.nodeType}function c(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function l(e,t,n){if(t=t||0,Y.isFunction(t))return Y.grep(e,function(e,r){var o=!!t.call(e,r,e);return o===n});if(t.nodeType)return Y.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=Y.grep(e,function(e){return 1===e.nodeType});if(Pt.test(t))return Y.filter(t,r,!n);t=Y.filter(t,r)}return Y.grep(e,function(e){return Y.inArray(e,t)>=0===n})}function u(e){var t=Dt.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function p(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function f(e,t){if(1===t.nodeType&&Y.hasData(e)){var n,r,o,i=Y._data(e),a=Y._data(t,i),s=i.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,o=s[n].length;o>r;r++)Y.event.add(t,n,s[n][r])}a.data&&(a.data=Y.extend({},a.data))}}function d(e,t){var n;1===t.nodeType&&(t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),Y.support.html5Clone&&e.innerHTML&&!Y.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Xt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.selected=e.defaultSelected:"input"===n||"textarea"===n?t.defaultValue=e.defaultValue:"script"===n&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(Y.expando))}function h(e){return e.getElementsByTagName!==t?e.getElementsByTagName("*"):e.querySelectorAll!==t?e.querySelectorAll("*"):[]}function g(e){Xt.test(e.type)&&(e.defaultChecked=e.checked)}function m(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,o=vn.length;o--;)if(t=vn[o]+n,t in e)return t;return r}function y(e,t){return e=t||e,"none"===Y.css(e,"display")||!Y.contains(e.ownerDocument,e)}function v(e,t){for(var n,r,o=[],i=0,a=e.length;a>i;i++)n=e[i],n.style&&(o[i]=Y._data(n,"olddisplay"),t?(o[i]||"none"!==n.style.display||(n.style.display=""),""===n.style.display&&y(n)&&(o[i]=Y._data(n,"olddisplay",x(n.nodeName)))):(r=nn(n,"display"),o[i]||"none"===r||Y._data(n,"olddisplay",r)));for(i=0;a>i;i++)n=e[i],n.style&&(t&&"none"!==n.style.display&&""!==n.style.display||(n.style.display=t?o[i]||"":"none"));return e}function b(e,t,n){var r=pn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function _(e,t,n,r){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,i=0;4>o;o+=2)"margin"===n&&(i+=Y.css(e,n+yn[o],!0)),r?("content"===n&&(i-=parseFloat(nn(e,"padding"+yn[o]))||0),"margin"!==n&&(i-=parseFloat(nn(e,"border"+yn[o]+"Width"))||0)):(i+=parseFloat(nn(e,"padding"+yn[o]))||0,"padding"!==n&&(i+=parseFloat(nn(e,"border"+yn[o]+"Width"))||0));return i}function C(e,t,n){var r="width"===t?e.offsetWidth:e.offsetHeight,o=!0,i=Y.support.boxSizing&&"border-box"===Y.css(e,"boxSizing");if(0>=r||null==r){if(r=nn(e,t),(0>r||null==r)&&(r=e.style[t]),fn.test(r))return r;o=i&&(Y.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+_(e,t,n||(i?"border":"content"),o)+"px"}function x(e){if(hn[e])return hn[e];var t=Y("<"+e+">").appendTo(Q.body),n=t.css("display");return t.remove(),("none"===n||""===n)&&(rn=Q.body.appendChild(rn||Y.extend(Q.createElement("iframe"),{frameBorder:0,width:0,height:0})),on&&rn.createElement||(on=(rn.contentWindow||rn.contentDocument).document,on.write("<!doctype html><html><body>"),on.close()),t=on.body.appendChild(on.createElement(e)),n=nn(t,"display"),Q.body.removeChild(rn)),hn[e]=n,n}function w(e,t,n,r){var o;if(Y.isArray(t))Y.each(t,function(t,o){n||Cn.test(e)?r(e,o):w(e+"["+("object"==typeof o?t:"")+"]",o,n,r)});else if(n||"object"!==Y.type(t))r(e,t);else for(o in t)w(e+"["+o+"]",t[o],n,r)}function A(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,o,i,a=t.toLowerCase().split(tt),s=0,c=a.length;if(Y.isFunction(n))for(;c>s;s++)r=a[s],i=/^\+/.test(r),i&&(r=r.substr(1)||"*"),o=e[r]=e[r]||[],o[i?"unshift":"push"](n)}}function F(e,n,r,o,i,a){i=i||n.dataTypes[0],a=a||{},a[i]=!0;for(var s,c=e[i],l=0,u=c?c.length:0,p=e===Hn;u>l&&(p||!s);l++)s=c[l](n,r,o),"string"==typeof s&&(!p||a[s]?s=t:(n.dataTypes.unshift(s),s=F(e,n,r,o,s,a)));return!p&&s||a["*"]||(s=F(e,n,r,o,"*",a)),s}function k(e,n){var r,o,i=Y.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((i[r]?e:o||(o={}))[r]=n[r]);o&&Y.extend(!0,e,o)}function T(e,n,r){var o,i,a,s,c=e.contents,l=e.dataTypes,u=e.responseFields;for(i in u)i in r&&(n[u[i]]=r[i]);for(;"*"===l[0];)l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("content-type"));if(o)for(i in c)if(c[i]&&c[i].test(o)){l.unshift(i);break}if(l[0]in r)a=l[0];else{for(i in r){if(!l[0]||e.converters[i+" "+l[0]]){a=i;break}s||(s=i)}a=a||s}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function E(e,t){var n,r,o,i,a=e.dataTypes.slice(),s=a[0],c={},l=0;if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),a[1])for(n in e.converters)c[n.toLowerCase()]=e.converters[n];for(;o=a[++l];)if("*"!==o){if("*"!==s&&s!==o){if(n=c[s+" "+o]||c["* "+o],!n)for(r in c)if(i=r.split(" "),i[1]===o&&(n=c[s+" "+i[0]]||c["* "+i[0]])){n===!0?n=c[r]:c[r]!==!0&&(o=i[0],a.splice(l--,0,o));break}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(u){return{state:"parsererror",error:n?u:"No conversion from "+s+" to "+o}}}s=o}return{state:"success",data:t}}function N(){try{return new e.XMLHttpRequest}catch(t){}}function S(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function R(){return setTimeout(function(){Vn=t},0),Vn=Y.now()}function j(e,t){Y.each(t,function(t,n){for(var r=(er[t]||[]).concat(er["*"]),o=0,i=r.length;i>o;o++)if(r[o].call(e,t,n))return})}function O(e,t,n){var r,o=0,i=Zn.length,a=Y.Deferred().always(function(){delete s.elem}),s=function(){for(var t=Vn||R(),n=Math.max(0,c.startTime+c.duration-t),r=n/c.duration||0,o=1-r,i=0,s=c.tweens.length;s>i;i++)c.tweens[i].run(o);return a.notifyWith(e,[c,o,n]),1>o&&s?n:(a.resolveWith(e,[c]),!1)},c=a.promise({elem:e,props:Y.extend({},t),opts:Y.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Vn||R(),duration:n.duration,tweens:[],createTween:function(t,n){var r=Y.Tween(e,c.opts,t,n,c.opts.specialEasing[t]||c.opts.easing);return c.tweens.push(r),r},stop:function(t){for(var n=0,r=t?c.tweens.length:0;r>n;n++)c.tweens[n].run(1);return t?a.resolveWith(e,[c,t]):a.rejectWith(e,[c,t]),this}}),l=c.props;for(I(l,c.opts.specialEasing);i>o;o++)if(r=Zn[o].call(c,e,l,c.opts))return r;return j(c,l),Y.isFunction(c.opts.start)&&c.opts.start.call(e,c),Y.fx.timer(Y.extend(s,{anim:c,queue:c.opts.queue,elem:e})),c.progress(c.opts.progress).done(c.opts.done,c.opts.complete).fail(c.opts.fail).always(c.opts.always)}function I(e,t){var n,r,o,i,a;for(n in e)if(r=Y.camelCase(n),o=t[r],i=e[n],Y.isArray(i)&&(o=i[1],i=e[n]=i[0]),n!==r&&(e[r]=i,delete e[n]),a=Y.cssHooks[r],a&&"expand"in a){i=a.expand(i),delete e[r];for(n in i)n in e||(e[n]=i[n],t[n]=o)}else t[r]=o}function M(e,t,n){var r,o,i,a,s,c,l,u,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&y(e);n.queue||(u=Y._queueHooks(e,"fx"),null==u.unqueued&&(u.unqueued=0,p=u.empty.fire,u.empty.fire=function(){u.unqueued||p()}),u.unqueued++,f.always(function(){f.always(function(){u.unqueued--,Y.queue(e,"fx").length||u.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===Y.css(e,"display")&&"none"===Y.css(e,"float")&&(Y.support.inlineBlockNeedsLayout&&"inline"!==x(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",Y.support.shrinkWrapBlocks||f.done(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Kn.exec(i)){if(delete t[r],c=c||"toggle"===i,i===(m?"hide":"show"))continue;g.push(r)}if(a=g.length){s=Y._data(e,"fxshow")||Y._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),c&&(s.hidden=!m),m?Y(e).show():f.done(function(){Y(e).hide()}),f.done(function(){var t;Y.removeData(e,"fxshow",!0);for(t in h)Y.style(e,t,h[t])});for(r=0;a>r;r++)o=g[r],l=f.createTween(o,m?s[o]:0),h[o]=s[o]||Y.style(e,o),o in s||(s[o]=l.start,m&&(l.end=l.start,l.start="width"===o||"height"===o?1:0))}}function P(e,t,n,r,o){return new P.prototype.init(e,t,n,r,o)}function H(e,t){var n,r={height:e},o=0;for(t=t?1:0;4>o;o+=2-t)n=yn[o],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function L(e){return Y.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var D,U,Q=e.document,B=e.location,q=e.navigator,W=e.jQuery,$=e.$,z=Array.prototype.push,J=Array.prototype.slice,V=Array.prototype.indexOf,X=Object.prototype.toString,K=Object.prototype.hasOwnProperty,G=String.prototype.trim,Y=function(e,t){return new Y.fn.init(e,t,D)},Z=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,et=/\S/,tt=/\s+/,nt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,rt=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,ot=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,it=/^[\],:{}\s]*$/,at=/(?:^|:|,)(?:\s*\[)+/g,st=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,ct=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,lt=/^-ms-/,ut=/-([\da-z])/gi,pt=function(e,t){return(t+"").toUpperCase()},ft=function(){Q.addEventListener?(Q.removeEventListener("DOMContentLoaded",ft,!1),Y.ready()):"complete"===Q.readyState&&(Q.detachEvent("onreadystatechange",ft),Y.ready())},dt={};Y.fn=Y.prototype={constructor:Y,init:function(e,n,r){var o,i,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if("string"==typeof e){if(o="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:rt.exec(e),!o||!o[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(o[1])return n=n instanceof Y?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:Q,e=Y.parseHTML(o[1],a,!0),ot.test(o[1])&&Y.isPlainObject(n)&&this.attr.call(e,n,!0),Y.merge(this,e);if(i=Q.getElementById(o[2]),i&&i.parentNode){if(i.id!==o[2])return r.find(e);this.length=1,this[0]=i}return this.context=Q,this.selector=e,this}return Y.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),Y.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return J.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=Y.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,"find"===t?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return Y.each(this,e,t)},ready:function(e){return Y.ready.promise().done(e),this},eq:function(e){return e=+e,-1===e?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(J.apply(this,arguments),"slice",J.call(arguments).join(","))},map:function(e){return this.pushStack(Y.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:z,sort:[].sort,splice:[].splice},Y.fn.init.prototype=Y.fn,Y.extend=Y.fn.extend=function(){var e,n,r,o,i,a,s=arguments[0]||{},c=1,l=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[1]||{},c=2),"object"==typeof s||Y.isFunction(s)||(s={}),l===c&&(s=this,--c);l>c;c++)if(null!=(e=arguments[c]))for(n in e)r=s[n],o=e[n],s!==o&&(u&&o&&(Y.isPlainObject(o)||(i=Y.isArray(o)))?(i?(i=!1,a=r&&Y.isArray(r)?r:[]):a=r&&Y.isPlainObject(r)?r:{},s[n]=Y.extend(u,a,o)):o!==t&&(s[n]=o));return s},Y.extend({noConflict:function(t){return e.$===Y&&(e.$=$),t&&e.jQuery===Y&&(e.jQuery=W),Y},isReady:!1,readyWait:1,holdReady:function(e){e?Y.readyWait++:Y.ready(!0)},ready:function(e){if(e===!0?!--Y.readyWait:!Y.isReady){if(!Q.body)return setTimeout(Y.ready,1);Y.isReady=!0,e!==!0&&--Y.readyWait>0||(U.resolveWith(Q,[Y]),Y.fn.trigger&&Y(Q).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===Y.type(e)},isArray:Array.isArray||function(e){return"array"===Y.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+"":dt[X.call(e)]||"object"},isPlainObject:function(e){if(!e||"object"!==Y.type(e)||e.nodeType||Y.isWindow(e))return!1;try{if(e.constructor&&!K.call(e,"constructor")&&!K.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||K.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){var r;return e&&"string"==typeof e?("boolean"==typeof t&&(n=t,t=0),t=t||Q,(r=ot.exec(e))?[t.createElement(r[1])]:(r=Y.buildFragment([e],t,n?null:[]),Y.merge([],(r.cacheable?Y.clone(r.fragment):r.fragment).childNodes))):null},parseJSON:function(n){return n&&"string"==typeof n?(n=Y.trim(n),e.JSON&&e.JSON.parse?e.JSON.parse(n):it.test(n.replace(st,"@").replace(ct,"]").replace(at,""))?Function("return "+n)():(Y.error("Invalid JSON: "+n),t)):null},parseXML:function(n){var r,o;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(o=new DOMParser,r=o.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(i){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||Y.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&et.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(lt,"ms-").replace(ut,pt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var o,i=0,a=e.length,s=a===t||Y.isFunction(e);if(r)if(s){for(o in e)if(n.apply(e[o],r)===!1)break}else for(;a>i&&n.apply(e[i++],r)!==!1;);else if(s){for(o in e)if(n.call(e[o],o,e[o])===!1)break}else for(;a>i&&n.call(e[i],i,e[i++])!==!1;);return e},trim:G&&!G.call(" ")?function(e){return null==e?"":G.call(e)}:function(e){return null==e?"":(e+"").replace(nt,"")},makeArray:function(e,t){var n,r=t||[];return null!=e&&(n=Y.type(e),null==e.length||"string"===n||"function"===n||"regexp"===n||Y.isWindow(e)?z.call(r,e):Y.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(V)return V.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,o=e.length,i=0;if("number"==typeof r)for(;r>i;i++)e[o++]=n[i];else for(;n[i]!==t;)e[o++]=n[i++];return e.length=o,e},grep:function(e,t,n){var r,o=[],i=0,a=e.length;for(n=!!n;a>i;i++)r=!!t(e[i],i),n!==r&&o.push(e[i]);return o},map:function(e,n,r){var o,i,a=[],s=0,c=e.length,l=e instanceof Y||c!==t&&"number"==typeof c&&(c>0&&e[0]&&e[c-1]||0===c||Y.isArray(e));if(l)for(;c>s;s++)o=n(e[s],s,r),null!=o&&(a[a.length]=o);else for(i in e)o=n(e[i],i,r),null!=o&&(a[a.length]=o);return a.concat.apply([],a)},guid:1,proxy:function(e,n){var r,o,i;return"string"==typeof n&&(r=e[n],n=e,e=r),Y.isFunction(e)?(o=J.call(arguments,2),i=function(){return e.apply(n,o.concat(J.call(arguments)))},i.guid=e.guid=e.guid||Y.guid++,i):t},access:function(e,n,r,o,i,a,s){var c,l=null==r,u=0,p=e.length;if(r&&"object"==typeof r){for(u in r)Y.access(e,n,u,r[u],1,a,o);i=1}else if(o!==t){if(c=s===t&&Y.isFunction(o),l&&(c?(c=n,n=function(e,t,n){return c.call(Y(e),n)}):(n.call(e,o),n=null)),n)for(;p>u;u++)n(e[u],r,c?o.call(e[u],u,n(e[u],r)):o,s);i=1}return i?e:l?n.call(e):p?n(e[0],r):a},now:function(){return(new Date).getTime()}}),Y.ready.promise=function(t){if(!U)if(U=Y.Deferred(),"complete"===Q.readyState)setTimeout(Y.ready,1);else if(Q.addEventListener)Q.addEventListener("DOMContentLoaded",ft,!1),e.addEventListener("load",Y.ready,!1);else{Q.attachEvent("onreadystatechange",ft),e.attachEvent("onload",Y.ready);var n=!1;try{n=null==e.frameElement&&Q.documentElement}catch(r){}n&&n.doScroll&&function o(){if(!Y.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}Y.ready()}}()}return U.promise(t)},Y.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){dt["[object "+t+"]"]=t.toLowerCase()}),D=Y(Q);var ht={};Y.Callbacks=function(e){e="string"==typeof e?ht[e]||n(e):Y.extend({},e);var r,o,i,a,s,c,l=[],u=!e.once&&[],p=function(t){for(r=e.memory&&t,o=!0,c=a||0,a=0,s=l.length,i=!0;l&&s>c;c++)if(l[c].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}i=!1,l&&(u?u.length&&p(u.shift()):r?l=[]:f.disable())},f={add:function(){if(l){var t=l.length;(function n(t){Y.each(t,function(t,r){var o=Y.type(r);"function"===o?e.unique&&f.has(r)||l.push(r):r&&r.length&&"string"!==o&&n(r)})})(arguments),i?s=l.length:r&&(a=t,p(r))}return this},remove:function(){return l&&Y.each(arguments,function(e,t){for(var n;(n=Y.inArray(t,l,n))>-1;)l.splice(n,1),i&&(s>=n&&s--,c>=n&&c--)}),this},has:function(e){return Y.inArray(e,l)>-1},empty:function(){return l=[],this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||f.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!l||o&&!u||(i?u.push(t):p(t)),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},Y.extend({Deferred:function(e){var t=[["resolve","done",Y.Callbacks("once memory"),"resolved"],["reject","fail",Y.Callbacks("once memory"),"rejected"],["notify","progress",Y.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return o.done(arguments).fail(arguments),this},then:function(){var e=arguments;return Y.Deferred(function(n){Y.each(t,function(t,r){var i=r[0],a=e[t];o[r[1]](Y.isFunction(a)?function(){var e=a.apply(this,arguments);e&&Y.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[i+"With"](this===o?n:this,[e])}:n[i])}),e=null}).promise()},promise:function(e){return null!=e?Y.extend(e,r):r}},o={};return r.pipe=r.then,Y.each(t,function(e,i){var a=i[2],s=i[3];r[i[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),o[i[0]]=a.fire,o[i[0]+"With"]=a.fireWith}),r.promise(o),e&&e.call(o,o),o},when:function(e){var t,n,r,o=0,i=J.call(arguments),a=i.length,s=1!==a||e&&Y.isFunction(e.promise)?a:0,c=1===s?e:Y.Deferred(),l=function(e,n,r){return function(o){n[e]=this,r[e]=arguments.length>1?J.call(arguments):o,r===t?c.notifyWith(n,r):--s||c.resolveWith(n,r)}};if(a>1)for(t=Array(a),n=Array(a),r=Array(a);a>o;o++)i[o]&&Y.isFunction(i[o].promise)?i[o].promise().done(l(o,r,i)).fail(c.reject).progress(l(o,n,t)):--s;return s||c.resolveWith(r,i),c.promise()}}),Y.support=function(){var n,r,o,i,a,s,c,l,u,p,f,d=Q.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=d.getElementsByTagName("*"),o=d.getElementsByTagName("a")[0],!r||!o||!r.length)return{};i=Q.createElement("select"),a=i.appendChild(Q.createElement("option")),s=d.getElementsByTagName("input")[0],o.style.cssText="top:1px;float:left;opacity:.5",n={leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(o.getAttribute("style")),hrefNormalized:"/a"===o.getAttribute("href"),opacity:/^0.5/.test(o.style.opacity),cssFloat:!!o.style.cssFloat,checkOn:"on"===s.value,optSelected:a.selected,getSetAttribute:"t"!==d.className,enctype:!!Q.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==Q.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===Q.compatMode,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},s.checked=!0,n.noCloneChecked=s.cloneNode(!0).checked,i.disabled=!0,n.optDisabled=!a.disabled;try{delete d.test}catch(h){n.deleteExpando=!1}if(!d.addEventListener&&d.attachEvent&&d.fireEvent&&(d.attachEvent("onclick",f=function(){n.noCloneEvent=!1}),d.cloneNode(!0).fireEvent("onclick"),d.detachEvent("onclick",f)),s=Q.createElement("input"),s.value="t",s.setAttribute("type","radio"),n.radioValue="t"===s.value,s.setAttribute("checked","checked"),s.setAttribute("name","t"),d.appendChild(s),c=Q.createDocumentFragment(),c.appendChild(d.lastChild),n.checkClone=c.cloneNode(!0).cloneNode(!0).lastChild.checked,n.appendChecked=s.checked,c.removeChild(s),c.appendChild(d),d.attachEvent)for(u in{submit:!0,change:!0,focusin:!0})l="on"+u,p=l in d,p||(d.setAttribute(l,"return;"),p="function"==typeof d[l]),n[u+"Bubbles"]=p;return Y(function(){var r,o,i,a,s="padding:0;margin:0;border:0;display:block;overflow:hidden;",c=Q.getElementsByTagName("body")[0];c&&(r=Q.createElement("div"),r.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",c.insertBefore(r,c.firstChild),o=Q.createElement("div"),r.appendChild(o),o.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=o.getElementsByTagName("td"),i[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===i[0].offsetHeight,i[0].style.display="",i[1].style.display="none",n.reliableHiddenOffsets=p&&0===i[0].offsetHeight,o.innerHTML="",o.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%;",n.boxSizing=4===o.offsetWidth,n.doesNotIncludeMarginInBodyOffset=1!==c.offsetTop,e.getComputedStyle&&(n.pixelPosition="1%"!==(e.getComputedStyle(o,null)||{}).top,n.boxSizingReliable="4px"===(e.getComputedStyle(o,null)||{width:"4px"}).width,a=Q.createElement("div"),a.style.cssText=o.style.cssText=s,a.style.marginRight=a.style.width="0",o.style.width="1px",o.appendChild(a),n.reliableMarginRight=!parseFloat((e.getComputedStyle(a,null)||{}).marginRight)),o.style.zoom!==t&&(o.innerHTML="",o.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",n.inlineBlockNeedsLayout=3===o.offsetWidth,o.style.display="block",o.style.overflow="visible",o.innerHTML="<div></div>",o.firstChild.style.width="5px",n.shrinkWrapBlocks=3!==o.offsetWidth,r.style.zoom=1),c.removeChild(r),r=o=i=a=null)}),c.removeChild(d),r=o=i=a=s=c=d=null,n}();var gt=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,mt=/([A-Z])/g;Y.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(Y.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?Y.cache[e[Y.expando]]:e[Y.expando],!!e&&!o(e)},data:function(e,n,r,o){if(Y.acceptData(e)){var i,a,s=Y.expando,c="string"==typeof n,l=e.nodeType,u=l?Y.cache:e,p=l?e[s]:e[s]&&s;if(p&&u[p]&&(o||u[p].data)||!c||r!==t)return p||(l?e[s]=p=Y.deletedIds.pop()||Y.guid++:p=s),u[p]||(u[p]={},l||(u[p].toJSON=Y.noop)),("object"==typeof n||"function"==typeof n)&&(o?u[p]=Y.extend(u[p],n):u[p].data=Y.extend(u[p].data,n)),i=u[p],o||(i.data||(i.data={}),i=i.data),r!==t&&(i[Y.camelCase(n)]=r),c?(a=i[n],null==a&&(a=i[Y.camelCase(n)])):a=i,a}},removeData:function(e,t,n){if(Y.acceptData(e)){var r,i,a,s=e.nodeType,c=s?Y.cache:e,l=s?e[Y.expando]:Y.expando;if(c[l]){if(t&&(r=n?c[l]:c[l].data)){Y.isArray(t)||(t in r?t=[t]:(t=Y.camelCase(t),t=t in r?[t]:t.split(" ")));for(i=0,a=t.length;a>i;i++)delete r[t[i]];if(!(n?o:Y.isEmptyObject)(r))return}(n||(delete c[l].data,o(c[l])))&&(s?Y.cleanData([e],!0):Y.support.deleteExpando||c!=c.window?delete c[l]:c[l]=null)}}},_data:function(e,t,n){return Y.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&Y.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),Y.fn.extend({data:function(e,n){var o,i,a,s,c,l=this[0],u=0,p=null;if(e===t){if(this.length&&(p=Y.data(l),1===l.nodeType&&!Y._data(l,"parsedAttrs"))){for(a=l.attributes,c=a.length;c>u;u++)s=a[u].name,s.indexOf("data-")||(s=Y.camelCase(s.substring(5)),r(l,s,p[s]));Y._data(l,"parsedAttrs",!0)}return p}return"object"==typeof e?this.each(function(){Y.data(this,e)}):(o=e.split(".",2),o[1]=o[1]?"."+o[1]:"",i=o[1]+"!",Y.access(this,function(n){return n===t?(p=this.triggerHandler("getData"+i,[o[0]]),p===t&&l&&(p=Y.data(l,e),p=r(l,e,p)),p===t&&o[1]?this.data(o[0]):p):(o[1]=n,this.each(function(){var t=Y(this);t.triggerHandler("setData"+i,o),Y.data(this,e,n),t.triggerHandler("changeData"+i,o)}),t)},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){Y.removeData(this,e)})}}),Y.extend({queue:function(e,n,r){var o;return e?(n=(n||"fx")+"queue",o=Y._data(e,n),r&&(!o||Y.isArray(r)?o=Y._data(e,n,Y.makeArray(r)):o.push(r)),o||[]):t},dequeue:function(e,t){t=t||"fx";var n=Y.queue(e,t),r=n.length,o=n.shift(),i=Y._queueHooks(e,t),a=function(){Y.dequeue(e,t)};"inprogress"===o&&(o=n.shift(),r--),o&&("fx"===t&&n.unshift("inprogress"),delete i.stop,o.call(e,a,i)),!r&&i&&i.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y._data(e,n)||Y._data(e,n,{empty:Y.Callbacks("once memory").add(function(){Y.removeData(e,t+"queue",!0),Y.removeData(e,n,!0)})})}}),Y.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?Y.queue(this[0],e):n===t?this:this.each(function(){var t=Y.queue(this,e,n);Y._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&Y.dequeue(this,e)})},dequeue:function(e){return this.each(function(){Y.dequeue(this,e)})},delay:function(e,t){return e=Y.fx?Y.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,o=1,i=Y.Deferred(),a=this,s=this.length,c=function(){--o||i.resolveWith(a,[a])};for("string"!=typeof e&&(n=e,e=t),e=e||"fx";s--;)r=Y._data(a[s],e+"queueHooks"),r&&r.empty&&(o++,r.empty.add(c));return c(),i.promise(n)}});var yt,vt,bt,_t=/[\t\r\n]/g,Ct=/\r/g,xt=/^(?:button|input)$/i,wt=/^(?:button|input|object|select|textarea)$/i,At=/^a(?:rea|)$/i,Ft=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,kt=Y.support.getSetAttribute;Y.fn.extend({attr:function(e,t){return Y.access(this,Y.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){Y.removeAttr(this,e)})},prop:function(e,t){return Y.access(this,Y.prop,e,t,arguments.length>1)},removeProp:function(e){return e=Y.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,o,i,a,s;if(Y.isFunction(e))return this.each(function(t){Y(this).addClass(e.call(this,t,this.className))});if(e&&"string"==typeof e)for(t=e.split(tt),n=0,r=this.length;r>n;n++)if(o=this[n],1===o.nodeType)if(o.className||1!==t.length){for(i=" "+o.className+" ",a=0,s=t.length;s>a;a++)0>i.indexOf(" "+t[a]+" ")&&(i+=t[a]+" ");o.className=Y.trim(i)}else o.className=e;return this},removeClass:function(e){var n,r,o,i,a,s,c;if(Y.isFunction(e))return this.each(function(t){Y(this).removeClass(e.call(this,t,this.className))});if(e&&"string"==typeof e||e===t)for(n=(e||"").split(tt),s=0,c=this.length;c>s;s++)if(o=this[s],1===o.nodeType&&o.className){for(r=(" "+o.className+" ").replace(_t," "),i=0,a=n.length;a>i;i++)for(;r.indexOf(" "+n[i]+" ")>=0;)r=r.replace(" "+n[i]+" "," ");o.className=e?Y.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return Y.isFunction(e)?this.each(function(n){Y(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var o,i=0,a=Y(this),s=t,c=e.split(tt);o=c[i++];)s=r?s:!a.hasClass(o),a[s?"addClass":"removeClass"](o);else("undefined"===n||"boolean"===n)&&(this.className&&Y._data(this,"__className__",this.className),this.className=this.className||e===!1?"":Y._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(_t," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,o,i=this[0];{if(arguments.length)return o=Y.isFunction(e),this.each(function(r){var i,a=Y(this);1===this.nodeType&&(i=o?e.call(this,r,a.val()):e,null==i?i="":"number"==typeof i?i+="":Y.isArray(i)&&(i=Y.map(i,function(e){return null==e?"":e+""})),n=Y.valHooks[this.type]||Y.valHooks[this.nodeName.toLowerCase()],n&&"set"in n&&n.set(this,i,"value")!==t||(this.value=i))});if(i)return n=Y.valHooks[i.type]||Y.valHooks[i.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(i,"value"))!==t?r:(r=i.value,"string"==typeof r?r.replace(Ct,""):null==r?"":r)}}}),Y.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){for(var t,n,r=e.options,o=e.selectedIndex,i="select-one"===e.type||0>o,a=i?null:[],s=i?o+1:r.length,c=0>o?s:i?o:0;s>c;c++)if(n=r[c],!(!n.selected&&c!==o||(Y.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&Y.nodeName(n.parentNode,"optgroup"))){if(t=Y(n).val(),i)return t;a.push(t)}return a},set:function(e,t){var n=Y.makeArray(t);return Y(e).find("option").each(function(){this.selected=Y.inArray(Y(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,o){var i,a,s,c=e.nodeType;if(e&&3!==c&&8!==c&&2!==c)return o&&Y.isFunction(Y.fn[n])?Y(e)[n](r):e.getAttribute===t?Y.prop(e,n,r):(s=1!==c||!Y.isXMLDoc(e),s&&(n=n.toLowerCase(),a=Y.attrHooks[n]||(Ft.test(n)?vt:yt)),r!==t?null===r?(Y.removeAttr(e,n),t):a&&"set"in a&&s&&(i=a.set(e,r,n))!==t?i:(e.setAttribute(n,r+""),r):a&&"get"in a&&s&&null!==(i=a.get(e,n))?i:(i=e.getAttribute(n),null===i?t:i))},removeAttr:function(e,t){var n,r,o,i,a=0;if(t&&1===e.nodeType)for(r=t.split(tt);r.length>a;a++)o=r[a],o&&(n=Y.propFix[o]||o,i=Ft.test(o),i||Y.attr(e,o,""),e.removeAttribute(kt?o:n),i&&n in e&&(e[n]=!1))},attrHooks:{type:{set:function(e,t){if(xt.test(e.nodeName)&&e.parentNode)Y.error("type property can't be changed");else if(!Y.support.radioValue&&"radio"===t&&Y.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return yt&&Y.nodeName(e,"button")?yt.get(e,t):t in e?e.value:null},set:function(e,n,r){return yt&&Y.nodeName(e,"button")?yt.set(e,n,r):(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 o,i,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!Y.isXMLDoc(e),a&&(n=Y.propFix[n]||n,i=Y.propHooks[n]),r!==t?i&&"set"in i&&(o=i.set(e,r,n))!==t?o:e[n]=r:i&&"get"in i&&null!==(o=i.get(e,n))?o:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):wt.test(e.nodeName)||At.test(e.nodeName)&&e.href?0:t}}}}),vt={get:function(e,n){var r,o=Y.prop(e,n);return o===!0||"boolean"!=typeof o&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?Y.removeAttr(e,n):(r=Y.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},kt||(bt={name:!0,id:!0,coords:!0},yt=Y.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(bt[n]?""!==r.value:r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=Q.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},Y.each(["width","height"],function(e,n){Y.attrHooks[n]=Y.extend(Y.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})}),Y.attrHooks.contenteditable={get:yt.get,set:function(e,t,n){""===t&&(t="false"),yt.set(e,t,n) }}),Y.support.hrefNormalized||Y.each(["href","src","width","height"],function(e,n){Y.attrHooks[n]=Y.extend(Y.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null===r?t:r}})}),Y.support.style||(Y.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),Y.support.optSelected||(Y.propHooks.selected=Y.extend(Y.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),Y.support.enctype||(Y.propFix.enctype="encoding"),Y.support.checkOn||Y.each(["radio","checkbox"],function(){Y.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),Y.each(["radio","checkbox"],function(){Y.valHooks[this]=Y.extend(Y.valHooks[this],{set:function(e,n){return Y.isArray(n)?e.checked=Y.inArray(Y(e).val(),n)>=0:t}})});var Tt=/^(?:textarea|input|select)$/i,Et=/^([^\.]*|)(?:\.(.+)|)$/,Nt=/(?:^|\s)hover(\.\S+|)\b/,St=/^key/,Rt=/^(?:mouse|contextmenu)|click/,jt=/^(?:focusinfocus|focusoutblur)$/,Ot=function(e){return Y.event.special.hover?e:e.replace(Nt,"mouseenter$1 mouseleave$1")};Y.event={add:function(e,n,r,o,i){var a,s,c,l,u,p,f,d,h,g,m;if(3!==e.nodeType&&8!==e.nodeType&&n&&r&&(a=Y._data(e))){for(r.handler&&(h=r,r=h.handler,i=h.selector),r.guid||(r.guid=Y.guid++),c=a.events,c||(a.events=c={}),s=a.handle,s||(a.handle=s=function(e){return Y===t||e&&Y.event.triggered===e.type?t:Y.event.dispatch.apply(s.elem,arguments)},s.elem=e),n=Y.trim(Ot(n)).split(" "),l=0;n.length>l;l++)u=Et.exec(n[l])||[],p=u[1],f=(u[2]||"").split(".").sort(),m=Y.event.special[p]||{},p=(i?m.delegateType:m.bindType)||p,m=Y.event.special[p]||{},d=Y.extend({type:p,origType:u[1],data:o,handler:r,guid:r.guid,selector:i,needsContext:i&&Y.expr.match.needsContext.test(i),namespace:f.join(".")},h),g=c[p],g||(g=c[p]=[],g.delegateCount=0,m.setup&&m.setup.call(e,o,f,s)!==!1||(e.addEventListener?e.addEventListener(p,s,!1):e.attachEvent&&e.attachEvent("on"+p,s))),m.add&&(m.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),i?g.splice(g.delegateCount++,0,d):g.push(d),Y.event.global[p]=!0;e=null}},global:{},remove:function(e,t,n,r,o){var i,a,s,c,l,u,p,f,d,h,g,m=Y.hasData(e)&&Y._data(e);if(m&&(f=m.events)){for(t=Y.trim(Ot(t||"")).split(" "),i=0;t.length>i;i++)if(a=Et.exec(t[i])||[],s=c=a[1],l=a[2],s){for(d=Y.event.special[s]||{},s=(r?d.delegateType:d.bindType)||s,h=f[s]||[],u=h.length,l=l?RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null,p=0;h.length>p;p++)g=h[p],!o&&c!==g.origType||n&&n.guid!==g.guid||l&&!l.test(g.namespace)||r&&r!==g.selector&&("**"!==r||!g.selector)||(h.splice(p--,1),g.selector&&h.delegateCount--,d.remove&&d.remove.call(e,g));0===h.length&&u!==h.length&&(d.teardown&&d.teardown.call(e,l,m.handle)!==!1||Y.removeEvent(e,s,m.handle),delete f[s])}else for(s in f)Y.event.remove(e,s+t[i],n,r,!0);Y.isEmptyObject(f)&&(delete m.handle,Y.removeData(e,"events",!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,o,i){if(!o||3!==o.nodeType&&8!==o.nodeType){var a,s,c,l,u,p,f,d,h,g,m=n.type||n,y=[];if(!jt.test(m+Y.event.triggered)&&(m.indexOf("!")>=0&&(m=m.slice(0,-1),s=!0),m.indexOf(".")>=0&&(y=m.split("."),m=y.shift(),y.sort()),o&&!Y.event.customEvent[m]||Y.event.global[m]))if(n="object"==typeof n?n[Y.expando]?n:new Y.Event(m,n):new Y.Event(m),n.type=m,n.isTrigger=!0,n.exclusive=s,n.namespace=y.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+y.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,p=0>m.indexOf(":")?"on"+m:"",o){if(n.result=t,n.target||(n.target=o),r=null!=r?Y.makeArray(r):[],r.unshift(n),f=Y.event.special[m]||{},!f.trigger||f.trigger.apply(o,r)!==!1){if(h=[[o,f.bindType||m]],!i&&!f.noBubble&&!Y.isWindow(o)){for(g=f.delegateType||m,l=jt.test(g+m)?o:o.parentNode,u=o;l;l=l.parentNode)h.push([l,g]),u=l;u===(o.ownerDocument||Q)&&h.push([u.defaultView||u.parentWindow||e,g])}for(c=0;h.length>c&&!n.isPropagationStopped();c++)l=h[c][0],n.type=h[c][1],d=(Y._data(l,"events")||{})[n.type]&&Y._data(l,"handle"),d&&d.apply(l,r),d=p&&l[p],d&&Y.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=m,i||n.isDefaultPrevented()||f._default&&f._default.apply(o.ownerDocument,r)!==!1||"click"===m&&Y.nodeName(o,"a")||!Y.acceptData(o)||p&&o[m]&&("focus"!==m&&"blur"!==m||0!==n.target.offsetWidth)&&!Y.isWindow(o)&&(u=o[p],u&&(o[p]=null),Y.event.triggered=m,o[m](),Y.event.triggered=t,u&&(o[p]=u)),n.result}}else{a=Y.cache;for(c in a)a[c].events&&a[c].events[m]&&Y.event.trigger(n,r,a[c].handle.elem,!0)}}},dispatch:function(n){n=Y.event.fix(n||e.event);var r,o,i,a,s,c,l,u,p,f=(Y._data(this,"events")||{})[n.type]||[],d=f.delegateCount,h=J.call(arguments),g=!n.exclusive&&!n.namespace,m=Y.event.special[n.type]||{},y=[];if(h[0]=n,n.delegateTarget=this,!m.preDispatch||m.preDispatch.call(this,n)!==!1){if(d&&(!n.button||"click"!==n.type))for(i=n.target;i!=this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==n.type){for(s={},l=[],r=0;d>r;r++)u=f[r],p=u.selector,s[p]===t&&(s[p]=u.needsContext?Y(p,this).index(i)>=0:Y.find(p,this,null,[i]).length),s[p]&&l.push(u);l.length&&y.push({elem:i,matches:l})}for(f.length>d&&y.push({elem:this,matches:f.slice(d)}),r=0;y.length>r&&!n.isPropagationStopped();r++)for(c=y[r],n.currentTarget=c.elem,o=0;c.matches.length>o&&!n.isImmediatePropagationStopped();o++)u=c.matches[o],(g||!n.namespace&&!u.namespace||n.namespace_re&&n.namespace_re.test(u.namespace))&&(n.data=u.data,n.handleObj=u,a=((Y.event.special[u.origType]||{}).handle||u.handler).apply(c.elem,h),a!==t&&(n.result=a,a===!1&&(n.preventDefault(),n.stopPropagation())));return m.postDispatch&&m.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 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,o,i,a=n.button,s=n.fromElement;return null==e.pageX&&null!=n.clientX&&(r=e.target.ownerDocument||Q,o=r.documentElement,i=r.body,e.pageX=n.clientX+(o&&o.scrollLeft||i&&i.scrollLeft||0)-(o&&o.clientLeft||i&&i.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||i&&i.scrollTop||0)-(o&&o.clientTop||i&&i.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?n.toElement:s),e.which||a===t||(e.which=1&a?1:2&a?3:4&a?2:0),e}},fix:function(e){if(e[Y.expando])return e;var t,n,r=e,o=Y.event.fixHooks[e.type]||{},i=o.props?this.props.concat(o.props):this.props;for(e=Y.Event(r),t=i.length;t;)n=i[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||Q),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,o.filter?o.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){Y.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var o=Y.extend(new Y.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?Y.event.trigger(o,null,t):Y.event.dispatch.call(t,o),o.isDefaultPrevented()&&n.preventDefault()}},Y.event.handle=Y.event.dispatch,Y.removeEvent=Q.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,n,r){var o="on"+n;e.detachEvent&&(e[o]===t&&(e[o]=null),e.detachEvent(o,r))},Y.Event=function(e,n){return this instanceof Y.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?a:i):this.type=e,n&&Y.extend(this,n),this.timeStamp=e&&e.timeStamp||Y.now(),this[Y.expando]=!0,t):new Y.Event(e,n)},Y.Event.prototype={preventDefault:function(){this.isDefaultPrevented=a;var e=this.originalEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=a;var e=this.originalEvent;e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=a,this.stopPropagation()},isDefaultPrevented:i,isPropagationStopped:i,isImmediatePropagationStopped:i},Y.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){Y.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,o=e.relatedTarget,i=e.handleObj;return i.selector,(!o||o!==r&&!Y.contains(r,o))&&(e.type=i.origType,n=i.handler.apply(this,arguments),e.type=t),n}}}),Y.support.submitBubbles||(Y.event.special.submit={setup:function(){return Y.nodeName(this,"form")?!1:(Y.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=Y.nodeName(n,"input")||Y.nodeName(n,"button")?n.form:t;r&&!Y._data(r,"_submit_attached")&&(Y.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),Y._data(r,"_submit_attached",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&Y.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return Y.nodeName(this,"form")?!1:(Y.event.remove(this,"._submit"),t)}}),Y.support.changeBubbles||(Y.event.special.change={setup:function(){return Tt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(Y.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),Y.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),Y.event.simulate("change",this,e,!0)})),!1):(Y.event.add(this,"beforeactivate._change",function(e){var t=e.target;Tt.test(t.nodeName)&&!Y._data(t,"_change_attached")&&(Y.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||Y.event.simulate("change",this.parentNode,e,!0)}),Y._data(t,"_change_attached",!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 Y.event.remove(this,"._change"),!Tt.test(this.nodeName)}}),Y.support.focusinBubbles||Y.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){Y.event.simulate(t,e.target,Y.event.fix(e),!0)};Y.event.special[t]={setup:function(){0===n++&&Q.addEventListener(e,r,!0)},teardown:function(){0===--n&&Q.removeEventListener(e,r,!0)}}}),Y.fn.extend({on:function(e,n,r,o,a){var s,c;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(c in e)this.on(c,n,r,e[c],a);return this}if(null==r&&null==o?(o=n,r=n=t):null==o&&("string"==typeof n?(o=r,r=t):(o=r,r=n,n=t)),o===!1)o=i;else if(!o)return this;return 1===a&&(s=o,o=function(e){return Y().off(e),s.apply(this,arguments)},o.guid=s.guid||(s.guid=Y.guid++)),this.each(function(){Y.event.add(this,e,o,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var o,a;if(e&&e.preventDefault&&e.handleObj)return o=e.handleObj,Y(e.delegateTarget).off(o.namespace?o.origType+"."+o.namespace:o.origType,o.selector,o.handler),this;if("object"==typeof e){for(a in e)this.off(a,n,e[a]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=i),this.each(function(){Y.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 Y(this.context).on(e,this.selector,t,n),this},die:function(e,t){return Y(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 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){Y.event.trigger(e,t,this)})},triggerHandler:function(e,n){return this[0]?Y.event.trigger(e,n,this[0],!0):t},toggle:function(e){var t=arguments,n=e.guid||Y.guid++,r=0,o=function(n){var o=(Y._data(this,"lastToggle"+e.guid)||0)%r;return Y._data(this,"lastToggle"+e.guid,o+1),n.preventDefault(),t[o].apply(this,arguments)||!1};for(o.guid=n;t.length>r;)t[r++].guid=n;return this.click(o)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),Y.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){Y.fn[t]=function(e,n){return null==n&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},St.test(t)&&(Y.event.fixHooks[t]=Y.event.keyHooks),Rt.test(t)&&(Y.event.fixHooks[t]=Y.event.mouseHooks)}),/*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ function(e,t){function n(e,t,n,r){n=n||[],t=t||R;var o,i,a,s,c=t.nodeType;if(!e||"string"!=typeof e)return n;if(1!==c&&9!==c)return[];if(a=C(t),!a&&!r&&(o=nt.exec(e)))if(s=o[1]){if(9===c){if(i=t.getElementById(s),!i||!i.parentNode)return n;if(i.id===s)return n.push(i),n}else if(t.ownerDocument&&(i=t.ownerDocument.getElementById(s))&&x(t,i)&&i.id===s)return n.push(i),n}else{if(o[2])return P.apply(n,H.call(t.getElementsByTagName(e),0)),n;if((s=o[3])&&ft&&t.getElementsByClassName)return P.apply(n,H.call(t.getElementsByClassName(s),0)),n}return g(e.replace(G,"$1"),t,n,r,a)}function r(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function o(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function i(e){return D(function(t){return t=+t,D(function(n,r){for(var o,i=e([],n.length,t),a=i.length;a--;)n[o=i[a]]&&(n[o]=!(r[o]=n[o]))})})}function a(e,t,n){if(e===t)return n;for(var r=e.nextSibling;r;){if(r===t)return-1;r=r.nextSibling}return 1}function s(e,t){var r,o,i,a,s,c,l,u=B[N][e+" "];if(u)return t?0:u.slice(0);for(s=e,c=[],l=b.preFilter;s;){(!r||(o=Z.exec(s)))&&(o&&(s=s.slice(o[0].length)||s),c.push(i=[])),r=!1,(o=et.exec(s))&&(i.push(r=new S(o.shift())),s=s.slice(r.length),r.type=o[0].replace(G," "));for(a in b.filter)!(o=st[a].exec(s))||l[a]&&!(o=l[a](o))||(i.push(r=new S(o.shift())),s=s.slice(r.length),r.type=a,r.matches=o);if(!r)break}return t?s.length:s?n.error(e):B(e,c).slice(0)}function c(e,t,n){var r=t.dir,o=n&&"parentNode"===t.dir,i=I++;return t.first?function(t,n,i){for(;t=t[r];)if(o||1===t.nodeType)return e(t,n,i)}:function(t,n,a){if(a){for(;t=t[r];)if((o||1===t.nodeType)&&e(t,n,a))return t}else for(var s,c=O+" "+i+" ",l=c+y;t=t[r];)if(o||1===t.nodeType){if((s=t[N])===l)return t.sizset;if("string"==typeof s&&0===s.indexOf(c)){if(t.sizset)return t}else{if(t[N]=l,e(t,n,a))return t.sizset=!0,t;t.sizset=!1}}}}function l(e){return e.length>1?function(t,n,r){for(var o=e.length;o--;)if(!e[o](t,n,r))return!1;return!0}:e[0]}function u(e,t,n,r,o){for(var i,a=[],s=0,c=e.length,l=null!=t;c>s;s++)(i=e[s])&&(!n||n(i,r,o))&&(a.push(i),l&&t.push(s));return a}function p(e,t,n,r,o,i){return r&&!r[N]&&(r=p(r)),o&&!o[N]&&(o=p(o,i)),D(function(i,a,s,c){var l,p,f,d=[],g=[],m=a.length,y=i||h(t||"*",s.nodeType?[s]:s,[]),v=!e||!i&&t?y:u(y,d,e,s,c),b=n?o||(i?e:m||r)?[]:a:v;if(n&&n(v,b,s,c),r)for(l=u(b,g),r(l,[],s,c),p=l.length;p--;)(f=l[p])&&(b[g[p]]=!(v[g[p]]=f));if(i){if(o||e){if(o){for(l=[],p=b.length;p--;)(f=b[p])&&l.push(v[p]=f);o(null,b=[],l,c)}for(p=b.length;p--;)(f=b[p])&&(l=o?L.call(i,f):d[p])>-1&&(i[l]=!(a[l]=f))}}else b=u(b===a?b.splice(m,b.length):b),o?o(null,a,b,c):P.apply(a,b)})}function f(e){for(var t,n,r,o=e.length,i=b.relative[e[0].type],a=i||b.relative[" "],s=i?1:0,u=c(function(e){return e===t},a,!0),d=c(function(e){return L.call(t,e)>-1},a,!0),h=[function(e,n,r){return!i&&(r||n!==k)||((t=n).nodeType?u(e,n,r):d(e,n,r))}];o>s;s++)if(n=b.relative[e[s].type])h=[c(l(h),n)];else{if(n=b.filter[e[s].type].apply(null,e[s].matches),n[N]){for(r=++s;o>r&&!b.relative[e[r].type];r++);return p(s>1&&l(h),s>1&&e.slice(0,s-1).join("").replace(G,"$1"),n,r>s&&f(e.slice(s,r)),o>r&&f(e=e.slice(r)),o>r&&e.join(""))}h.push(n)}return l(h)}function d(e,t){var r=t.length>0,o=e.length>0,i=function(a,s,c,l,p){var f,d,h,g=[],m=0,v="0",_=a&&[],C=null!=p,x=k,w=a||o&&b.find.TAG("*",p&&s.parentNode||s),A=O+=null==x?1:Math.E;for(C&&(k=s!==R&&s,y=i.el);null!=(f=w[v]);v++){if(o&&f){for(d=0;h=e[d];d++)if(h(f,s,c)){l.push(f);break}C&&(O=A,y=++i.el)}r&&((f=!h&&f)&&m--,a&&_.push(f))}if(m+=v,r&&v!==m){for(d=0;h=t[d];d++)h(_,g,s,c);if(a){if(m>0)for(;v--;)_[v]||g[v]||(g[v]=M.call(l));g=u(g)}P.apply(l,g),C&&!a&&g.length>0&&m+t.length>1&&n.uniqueSort(l)}return C&&(O=A,k=x),_};return i.el=0,r?D(i):i}function h(e,t,r){for(var o=0,i=t.length;i>o;o++)n(e,t[o],r);return r}function g(e,t,n,r,o){var i,a,c,l,u,p=s(e);if(p.length,!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&!o&&b.relative[a[1].type]){if(t=b.find.ID(c.matches[0].replace(at,""),t,o)[0],!t)return n;e=e.slice(a.shift().length)}for(i=st.POS.test(e)?-1:a.length-1;i>=0&&(c=a[i],!b.relative[l=c.type]);i--)if((u=b.find[l])&&(r=u(c.matches[0].replace(at,""),rt.test(a[0].type)&&t.parentNode||t,o))){if(a.splice(i,1),e=r.length&&a.join(""),!e)return P.apply(n,H.call(r,0)),n;break}}return w(e,p)(r,t,o,n,rt.test(e)),n}function m(){}var y,v,b,_,C,x,w,A,F,k,T=!0,E="undefined",N=("sizcache"+Math.random()).replace(".",""),S=String,R=e.document,j=R.documentElement,O=0,I=0,M=[].pop,P=[].push,H=[].slice,L=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},D=function(e,t){return e[N]=null==t||t,e},U=function(){var e={},t=[];return D(function(n,r){return t.push(n)>b.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},Q=U(),B=U(),q=U(),W="[\\x20\\t\\r\\n\\f]",$="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",z=$.replace("w","w#"),J="([*^$|!~]?=)",V="\\["+W+"*("+$+")"+W+"*(?:"+J+W+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+z+")|)|)"+W+"*\\]",X=":("+$+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+V+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+W+"*((?:-\\d)?\\d*)"+W+"*\\)|)(?=[^-]|$)",G=RegExp("^"+W+"+|((?:^|[^\\\\])(?:\\\\.)*)"+W+"+$","g"),Z=RegExp("^"+W+"*,"+W+"*"),et=RegExp("^"+W+"*([\\x20\\t\\r\\n\\f>+~])"+W+"*"),tt=RegExp(X),nt=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,rt=/[\x20\t\r\n\f]*[+~]/,ot=/h\d/i,it=/input|select|textarea|button/i,at=/\\(?!\\)/g,st={ID:RegExp("^#("+$+")"),CLASS:RegExp("^\\.("+$+")"),NAME:RegExp("^\\[name=['\"]?("+$+")['\"]?\\]"),TAG:RegExp("^("+$.replace("w","w*")+")"),ATTR:RegExp("^"+V),PSEUDO:RegExp("^"+X),POS:RegExp(K,"i"),CHILD:RegExp("^:(only|nth|first|last)-child(?:\\("+W+"*(even|odd|(([+-]|)(\\d*)n|)"+W+"*(?:([+-]|)"+W+"*(\\d+)|))"+W+"*\\)|)","i"),needsContext:RegExp("^"+W+"*[>+~]|"+K,"i")},ct=function(e){var t=R.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},lt=ct(function(e){return e.appendChild(R.createComment("")),!e.getElementsByTagName("*").length}),ut=ct(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==E&&"#"===e.firstChild.getAttribute("href")}),pt=ct(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),ft=ct(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}),dt=ct(function(e){e.id=N+0,e.innerHTML="<a name='"+N+"'></a><div name='"+N+"'></div>",j.insertBefore(e,j.firstChild);var t=R.getElementsByName&&R.getElementsByName(N).length===2+R.getElementsByName(N+0).length;return v=!R.getElementById(N),j.removeChild(e),t});try{H.call(j.childNodes,0)[0].nodeType}catch(ht){H=function(e){for(var t,n=[];t=this[e];e++)n.push(t);return n}}n.matches=function(e,t){return n(e,null,null,t)},n.matchesSelector=function(e,t){return n(t,null,null,[e]).length>0},_=n.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=_(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[r];r++)n+=_(t);return n},C=n.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},x=n.contains=j.contains?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))}:j.compareDocumentPosition?function(e,t){return t&&!!(16&e.compareDocumentPosition(t))}:function(e,t){for(;t=t.parentNode;)if(t===e)return!0;return!1},n.attr=function(e,t){var n,r=C(e);return r||(t=t.toLowerCase()),(n=b.attrHandle[t])?n(e):r||pt?e.getAttribute(t):(n=e.getAttributeNode(t),n?"boolean"==typeof e[t]?e[t]?t:null:n.specified?n.value:null:null)},b=n.selectors={cacheLength:50,createPseudo:D,match:st,attrHandle:ut?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:v?function(e,t,n){if(typeof t.getElementById!==E&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==E&&!r){var o=n.getElementById(e);return o?o.id===e||typeof o.getAttributeNode!==E&&o.getAttributeNode("id").value===e?[o]:t:[]}},TAG:lt?function(e,n){return typeof n.getElementsByTagName!==E?n.getElementsByTagName(e):t}:function(e,t){var n=t.getElementsByTagName(e);if("*"===e){for(var r,o=[],i=0;r=n[i];i++)1===r.nodeType&&o.push(r);return o}return n},NAME:dt&&function(e,n){return typeof n.getElementsByName!==E?n.getElementsByName(name):t},CLASS:ft&&function(e,n,r){return typeof n.getElementsByClassName===E||r?t:n.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(at,""),e[3]=(e[4]||e[5]||"").replace(at,""),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1]?(e[2]||n.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*("even"===e[2]||"odd"===e[2])),e[4]=+(e[6]+e[7]||"odd"===e[2])):e[2]&&n.error(e[0]),e},PSEUDO:function(e){var t,n;return st.CHILD.test(e[0])?null:(e[3]?e[2]=e[3]:(t=e[4])&&(tt.test(t)&&(n=s(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),e.slice(0,3))}},filter:{ID:v?function(e){return e=e.replace(at,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace(at,""),function(t){var n=typeof t.getAttributeNode!==E&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(at,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=Q[N][e+" "];return t||(t=RegExp("(^|"+W+")"+e+"("+W+"|$)"))&&Q(e,function(e){return t.test(e.className||typeof e.getAttribute!==E&&e.getAttribute("class")||"")})},ATTR:function(e,t,r){return function(o){var i=n.attr(o,e);return null==i?"!="===t:t?(i+="","="===t?i===r:"!="===t?i!==r:"^="===t?r&&0===i.indexOf(r):"*="===t?r&&i.indexOf(r)>-1:"$="===t?r&&i.substr(i.length-r.length)===r:"~="===t?(" "+i+" ").indexOf(r)>-1:"|="===t?i===r||i.substr(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r){return"nth"===e?function(e){var t,o,i=e.parentNode;if(1===n&&0===r)return!0;if(i)for(o=0,t=i.firstChild;t&&(1!==t.nodeType||(o++,e!==t));t=t.nextSibling);return o-=r,o===n||0===o%n&&o/n>=0}:function(t){var n=t;switch(e){case"only":case"first":for(;n=n.previousSibling;)if(1===n.nodeType)return!1;if("first"===e)return!0;n=t;case"last":for(;n=n.nextSibling;)if(1===n.nodeType)return!1;return!0}}},PSEUDO:function(e,t){var r,o=b.pseudos[e]||b.setFilters[e.toLowerCase()]||n.error("unsupported pseudo: "+e);return o[N]?o(t):o.length>1?(r=[e,e,"",t],b.setFilters.hasOwnProperty(e.toLowerCase())?D(function(e,n){for(var r,i=o(e,t),a=i.length;a--;)r=L.call(e,i[a]),e[r]=!(n[r]=i[a])}):function(e){return o(e,0,r)}):o}},pseudos:{not:D(function(e){var t=[],n=[],r=w(e.replace(G,"$1"));return r[N]?D(function(e,t,n,o){for(var i,a=r(e,null,o,[]),s=e.length;s--;)(i=a[s])&&(e[s]=!(t[s]=i))}):function(e,o,i){return t[0]=e,r(t,null,i,n),!n.pop()}}),has:D(function(e){return function(t){return n(e,t).length>0}}),contains:D(function(e){return function(t){return(t.textContent||t.innerText||_(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"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!b.pseudos.empty(e)},empty:function(e){var t;for(e=e.firstChild;e;){if(e.nodeName>"@"||3===(t=e.nodeType)||4===t)return!1;e=e.nextSibling}return!0},header:function(e){return ot.test(e.nodeName)},text:function(e){var t,n;return"input"===e.nodeName.toLowerCase()&&"text"===(t=e.type)&&(null==(n=e.getAttribute("type"))||n.toLowerCase()===t)},radio:r("radio"),checkbox:r("checkbox"),file:r("file"),password:r("password"),image:r("image"),submit:o("submit"),reset:o("reset"),button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},input:function(e){return it.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:i(function(){return[0]}),last:i(function(e,t){return[t-1]}),eq:i(function(e,t,n){return[0>n?n+t:n]}),even:i(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:i(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:i(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:i(function(e,t,n){for(var r=0>n?n+t:n;t>++r;)e.push(r);return e})}},A=j.compareDocumentPosition?function(e,t){return e===t?(F=!0,0):(e.compareDocumentPosition&&t.compareDocumentPosition?4&e.compareDocumentPosition(t):e.compareDocumentPosition)?-1:1}:function(e,t){if(e===t)return F=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,o=[],i=[],s=e.parentNode,c=t.parentNode,l=s;if(s===c)return a(e,t);if(!s)return-1;if(!c)return 1;for(;l;)o.unshift(l),l=l.parentNode;for(l=c;l;)i.unshift(l),l=l.parentNode;n=o.length,r=i.length;for(var u=0;n>u&&r>u;u++)if(o[u]!==i[u])return a(o[u],i[u]);return u===n?a(e,i[u],-1):a(o[u],t,1)},[0,0].sort(A),T=!F,n.uniqueSort=function(e){var t,n=[],r=1,o=0;if(F=T,e.sort(A),F){for(;t=e[r];r++)t===e[r-1]&&(o=n.push(r));for(;o--;)e.splice(n[o],1)}return e},n.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},w=n.compile=function(e,t){var n,r=[],o=[],i=q[N][e+" "];if(!i){for(t||(t=s(e)),n=t.length;n--;)i=f(t[n]),i[N]?r.push(i):o.push(i);i=q(e,d(o,r))}return i},R.querySelectorAll&&function(){var e,t=g,r=/'|\\/g,o=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],a=[":active"],c=j.matchesSelector||j.mozMatchesSelector||j.webkitMatchesSelector||j.oMatchesSelector||j.msMatchesSelector;ct(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+W+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),ct(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+W+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=RegExp(i.join("|")),g=function(e,n,o,a,c){if(!a&&!c&&!i.test(e)){var l,u,p=!0,f=N,d=n,h=9===n.nodeType&&e;if(1===n.nodeType&&"object"!==n.nodeName.toLowerCase()){for(l=s(e),(p=n.getAttribute("id"))?f=p.replace(r,"\\$&"):n.setAttribute("id",f),f="[id='"+f+"'] ",u=l.length;u--;)l[u]=f+l[u].join("");d=rt.test(e)&&n.parentNode||n,h=l.join(",")}if(h)try{return P.apply(o,H.call(d.querySelectorAll(h),0)),o}catch(g){}finally{p||n.removeAttribute("id")}}return t(e,n,o,a,c)},c&&(ct(function(t){e=c.call(t,"div");try{c.call(t,"[test!='']:sizzle"),a.push("!=",X)}catch(n){}}),a=RegExp(a.join("|")),n.matchesSelector=function(t,r){if(r=r.replace(o,"='$1']"),!C(t)&&!a.test(r)&&!i.test(r))try{var s=c.call(t,r);if(s||e||t.document&&11!==t.document.nodeType)return s}catch(l){}return n(r,null,null,[t]).length>0})}(),b.pseudos.nth=b.pseudos.eq,b.filters=m.prototype=b.pseudos,b.setFilters=new m,n.attr=Y.attr,Y.find=n,Y.expr=n.selectors,Y.expr[":"]=Y.expr.pseudos,Y.unique=n.uniqueSort,Y.text=n.getText,Y.isXMLDoc=n.isXML,Y.contains=n.contains}(e);var It=/Until$/,Mt=/^(?:parents|prev(?:Until|All))/,Pt=/^.[^:#\[\.,]*$/,Ht=Y.expr.match.needsContext,Lt={children:!0,contents:!0,next:!0,prev:!0};Y.fn.extend({find:function(e){var t,n,r,o,i,a,s=this;if("string"!=typeof e)return Y(e).filter(function(){for(t=0,n=s.length;n>t;t++)if(Y.contains(s[t],this))return!0});for(a=this.pushStack("","find",e),t=0,n=this.length;n>t;t++)if(r=a.length,Y.find(e,this[t],a),t>0)for(o=r;a.length>o;o++)for(i=0;r>i;i++)if(a[i]===a[o]){a.splice(o--,1);break}return a},has:function(e){var t,n=Y(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(Y.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(l(this,e,!1),"not",e)},filter:function(e){return this.pushStack(l(this,e,!0),"filter",e)},is:function(e){return!!e&&("string"==typeof e?Ht.test(e)?Y(e,this.context).index(this[0])>=0:Y.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){for(var n,r=0,o=this.length,i=[],a=Ht.test(e)||"string"!=typeof e?Y(e,t||this.context):0;o>r;r++)for(n=this[r];n&&n.ownerDocument&&n!==t&&11!==n.nodeType;){if(a?a.index(n)>-1:Y.find.matchesSelector(n,e)){i.push(n);break}n=n.parentNode}return i=i.length>1?Y.unique(i):i,this.pushStack(i,"closest",e)},index:function(e){return e?"string"==typeof e?Y.inArray(this[0],Y(e)):Y.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n="string"==typeof e?Y(e,t):Y.makeArray(e&&e.nodeType?[e]:e),r=Y.merge(this.get(),n);return this.pushStack(s(n[0])||s(r[0])?r:Y.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),Y.fn.andSelf=Y.fn.addBack,Y.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return Y.dir(e,"parentNode")},parentsUntil:function(e,t,n){return Y.dir(e,"parentNode",n)},next:function(e){return c(e,"nextSibling")},prev:function(e){return c(e,"previousSibling")},nextAll:function(e){return Y.dir(e,"nextSibling")},prevAll:function(e){return Y.dir(e,"previousSibling")},nextUntil:function(e,t,n){return Y.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return Y.dir(e,"previousSibling",n)},siblings:function(e){return Y.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return Y.sibling(e.firstChild)},contents:function(e){return Y.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:Y.merge([],e.childNodes)}},function(e,t){Y.fn[e]=function(n,r){var o=Y.map(this,t,n);return It.test(e)||(r=n),r&&"string"==typeof r&&(o=Y.filter(r,o)),o=this.length>1&&!Lt[e]?Y.unique(o):o,this.length>1&&Mt.test(e)&&(o=o.reverse()),this.pushStack(o,e,J.call(arguments).join(","))}}),Y.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?Y.find.matchesSelector(t[0],e)?[t[0]]:[]:Y.find.matches(e,t)},dir:function(e,n,r){for(var o=[],i=e[n];i&&9!==i.nodeType&&(r===t||1!==i.nodeType||!Y(i).is(r));)1===i.nodeType&&o.push(i),i=i[n];return o},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});var Dt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Ut=/ jQuery\d+="(?:null|\d+)"/g,Qt=/^\s+/,Bt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,qt=/<([\w:]+)/,Wt=/<tbody/i,$t=/<|&#?\w+;/,zt=/<(?:script|style|link)/i,Jt=/<(?:script|object|embed|option|style)/i,Vt=RegExp("<(?:"+Dt+")[\\s/>]","i"),Xt=/^(?:checkbox|radio)$/,Kt=/checked\s*(?:[^=]|=\s*.checked.)/i,Gt=/\/(java|ecma)script/i,Yt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Zt={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,"",""]},en=u(Q),tn=en.appendChild(Q.createElement("div"));Zt.optgroup=Zt.option,Zt.tbody=Zt.tfoot=Zt.colgroup=Zt.caption=Zt.thead,Zt.th=Zt.td,Y.support.htmlSerialize||(Zt._default=[1,"X<div>","</div>"]),Y.fn.extend({text:function(e){return Y.access(this,function(e){return e===t?Y.text(this):this.empty().append((this[0]&&this[0].ownerDocument||Q).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(Y.isFunction(e))return this.each(function(t){Y(this).wrapAll(e.call(this,t))});if(this[0]){var t=Y(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return Y.isFunction(e)?this.each(function(t){Y(this).wrapInner(e.call(this,t))}):this.each(function(){var t=Y(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=Y.isFunction(e);return this.each(function(n){Y(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){Y.nodeName(this,"body")||Y(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!s(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=Y.clean(arguments);return this.pushStack(Y.merge(e,this),"before",this.selector)}},after:function(){if(!s(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=Y.clean(arguments);return this.pushStack(Y.merge(this,e),"after",this.selector)}},remove:function(e,t){for(var n,r=0;null!=(n=this[r]);r++)(!e||Y.filter(e,[n]).length)&&(t||1!==n.nodeType||(Y.cleanData(n.getElementsByTagName("*")),Y.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)for(1===e.nodeType&&Y.cleanData(e.getElementsByTagName("*"));e.firstChild;)e.removeChild(e.firstChild);return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return Y.clone(this,e,t)})},html:function(e){return Y.access(this,function(e){var n=this[0]||{},r=0,o=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(Ut,""):t;if(!("string"!=typeof e||zt.test(e)||!Y.support.htmlSerialize&&Vt.test(e)||!Y.support.leadingWhitespace&&Qt.test(e)||Zt[(qt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Bt,"<$1></$2>");try{for(;o>r;r++)n=this[r]||{},1===n.nodeType&&(Y.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(i){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return s(this[0])?this.length?this.pushStack(Y(Y.isFunction(e)?e():e),"replaceWith",e):this:Y.isFunction(e)?this.each(function(t){var n=Y(this),r=n.html();n.replaceWith(e.call(this,t,r))}):("string"!=typeof e&&(e=Y(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;Y(this).remove(),t?Y(t).before(e):Y(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var o,i,a,s,c=0,l=e[0],u=[],f=this.length;if(!Y.support.checkClone&&f>1&&"string"==typeof l&&Kt.test(l))return this.each(function(){Y(this).domManip(e,n,r)});if(Y.isFunction(l))return this.each(function(o){var i=Y(this);e[0]=l.call(this,o,n?i.html():t),i.domManip(e,n,r)});if(this[0]){if(o=Y.buildFragment(e,this,u),a=o.fragment,i=a.firstChild,1===a.childNodes.length&&(a=i),i)for(n=n&&Y.nodeName(i,"tr"),s=o.cacheable||f-1;f>c;c++)r.call(n&&Y.nodeName(this[c],"table")?p(this[c],"tbody"):this[c],c===s?a:Y.clone(a,!0,!0));a=i=null,u.length&&Y.each(u,function(e,t){t.src?Y.ajax?Y.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):Y.error("no ajax"):Y.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Yt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),Y.buildFragment=function(e,n,r){var o,i,a,s=e[0];return n=n||Q,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,!(1===e.length&&"string"==typeof s&&512>s.length&&n===Q&&"<"===s.charAt(0))||Jt.test(s)||!Y.support.checkClone&&Kt.test(s)||!Y.support.html5Clone&&Vt.test(s)||(i=!0,o=Y.fragments[s],a=o!==t),o||(o=n.createDocumentFragment(),Y.clean(e,n,o,r),i&&(Y.fragments[s]=a&&o)),{fragment:o,cacheable:i}},Y.fragments={},Y.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){Y.fn[e]=function(n){var r,o=0,i=[],a=Y(n),s=a.length,c=1===this.length&&this[0].parentNode;if((null==c||c&&11===c.nodeType&&1===c.childNodes.length)&&1===s)return a[t](this[0]),this;for(;s>o;o++)r=(o>0?this.clone(!0):this).get(),Y(a[o])[t](r),i=i.concat(r);return this.pushStack(i,e,a.selector)}}),Y.extend({clone:function(e,t,n){var r,o,i,a;if(Y.support.html5Clone||Y.isXMLDoc(e)||!Vt.test("<"+e.nodeName+">")?a=e.cloneNode(!0):(tn.innerHTML=e.outerHTML,tn.removeChild(a=tn.firstChild)),!(Y.support.noCloneEvent&&Y.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||Y.isXMLDoc(e)))for(d(e,a),r=h(e),o=h(a),i=0;r[i];++i)o[i]&&d(r[i],o[i]);if(t&&(f(e,a),n))for(r=h(e),o=h(a),i=0;r[i];++i)f(r[i],o[i]);return r=o=null,a},clean:function(e,n,r,o){var i,a,s,c,l,p,f,d,h,m,y,v=n===Q&&en,b=[];for(n&&n.createDocumentFragment!==t||(n=Q),i=0;null!=(s=e[i]);i++)if("number"==typeof s&&(s+=""),s){if("string"==typeof s)if($t.test(s)){for(v=v||u(n),f=n.createElement("div"),v.appendChild(f),s=s.replace(Bt,"<$1></$2>"),c=(qt.exec(s)||["",""])[1].toLowerCase(),l=Zt[c]||Zt._default,p=l[0],f.innerHTML=l[1]+s+l[2];p--;)f=f.lastChild;if(!Y.support.tbody)for(d=Wt.test(s),h="table"!==c||d?"<table>"!==l[1]||d?[]:f.childNodes:f.firstChild&&f.firstChild.childNodes,a=h.length-1;a>=0;--a)Y.nodeName(h[a],"tbody")&&!h[a].childNodes.length&&h[a].parentNode.removeChild(h[a]);!Y.support.leadingWhitespace&&Qt.test(s)&&f.insertBefore(n.createTextNode(Qt.exec(s)[0]),f.firstChild),s=f.childNodes,f.parentNode.removeChild(f)}else s=n.createTextNode(s);s.nodeType?b.push(s):Y.merge(b,s)}if(f&&(s=f=v=null),!Y.support.appendChecked)for(i=0;null!=(s=b[i]);i++)Y.nodeName(s,"input")?g(s):s.getElementsByTagName!==t&&Y.grep(s.getElementsByTagName("input"),g);if(r)for(m=function(e){return!e.type||Gt.test(e.type)?o?o.push(e.parentNode?e.parentNode.removeChild(e):e):r.appendChild(e):t},i=0;null!=(s=b[i]);i++)Y.nodeName(s,"script")&&m(s)||(r.appendChild(s),s.getElementsByTagName!==t&&(y=Y.grep(Y.merge([],s.getElementsByTagName("script")),m),b.splice.apply(b,[i+1,0].concat(y)),i+=y.length));return b},cleanData:function(e,t){for(var n,r,o,i,a=0,s=Y.expando,c=Y.cache,l=Y.support.deleteExpando,u=Y.event.special;null!=(o=e[a]);a++)if((t||Y.acceptData(o))&&(r=o[s],n=r&&c[r])){if(n.events)for(i in n.events)u[i]?Y.event.remove(o,i):Y.removeEvent(o,i,n.handle);c[r]&&(delete c[r],l?delete o[s]:o.removeAttribute?o.removeAttribute(s):o[s]=null,Y.deletedIds.push(r))}}}),function(){var e,t;Y.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)||0>e.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=Y.uaMatch(q.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),Y.browser=t,Y.sub=function(){function e(t,n){return new e.fn.init(t,n)}Y.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(n,r){return r&&r instanceof Y&&!(r instanceof e)&&(r=e(r)),Y.fn.init.call(this,n,r,t)},e.fn.init.prototype=e.fn;var t=e(Q);return e}}();var nn,rn,on,an=/alpha\([^)]*\)/i,sn=/opacity=([^)]*)/,cn=/^(top|right|bottom|left)$/,ln=/^(none|table(?!-c[ea]).+)/,un=/^margin/,pn=RegExp("^("+Z+")(.*)$","i"),fn=RegExp("^("+Z+")(?!px)[a-z%]+$","i"),dn=RegExp("^([-+])=("+Z+")","i"),hn={BODY:"block"},gn={position:"absolute",visibility:"hidden",display:"block"},mn={letterSpacing:0,fontWeight:400},yn=["Top","Right","Bottom","Left"],vn=["Webkit","O","Moz","ms"],bn=Y.fn.toggle;Y.fn.extend({css:function(e,n){return Y.access(this,function(e,n,r){return r!==t?Y.style(e,n,r):Y.css(e,n)},e,n,arguments.length>1)},show:function(){return v(this,!0)},hide:function(){return v(this)},toggle:function(e,t){var n="boolean"==typeof e;return Y.isFunction(e)&&Y.isFunction(t)?bn.apply(this,arguments):this.each(function(){(n?e:y(this))?Y(this).show():Y(this).hide()})}}),Y.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nn(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":Y.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,o){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,a,s,c=Y.camelCase(n),l=e.style;if(n=Y.cssProps[c]||(Y.cssProps[c]=m(l,c)),s=Y.cssHooks[n]||Y.cssHooks[c],r===t)return s&&"get"in s&&(i=s.get(e,!1,o))!==t?i:l[n];if(a=typeof r,"string"===a&&(i=dn.exec(r))&&(r=(i[1]+1)*i[2]+parseFloat(Y.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||Y.cssNumber[c]||(r+="px"),s&&"set"in s&&(r=s.set(e,r,o))===t)))try{l[n]=r}catch(u){}}},css:function(e,n,r,o){var i,a,s,c=Y.camelCase(n);return n=Y.cssProps[c]||(Y.cssProps[c]=m(e.style,c)),s=Y.cssHooks[n]||Y.cssHooks[c],s&&"get"in s&&(i=s.get(e,!0,o)),i===t&&(i=nn(e,n)),"normal"===i&&n in mn&&(i=mn[n]),r||o!==t?(a=parseFloat(i),r||Y.isNumeric(a)?a||0:i):i},swap:function(e,t,n){var r,o,i={};for(o in t)i[o]=e.style[o],e.style[o]=t[o];r=n.call(e);for(o in t)e.style[o]=i[o];return r}}),e.getComputedStyle?nn=function(t,n){var r,o,i,a,s=e.getComputedStyle(t,null),c=t.style;return s&&(r=s.getPropertyValue(n)||s[n],""!==r||Y.contains(t.ownerDocument,t)||(r=Y.style(t,n)),fn.test(r)&&un.test(n)&&(o=c.width,i=c.minWidth,a=c.maxWidth,c.minWidth=c.maxWidth=c.width=r,r=s.width,c.width=o,c.minWidth=i,c.maxWidth=a)),r}:Q.documentElement.currentStyle&&(nn=function(e,t){var n,r,o=e.currentStyle&&e.currentStyle[t],i=e.style;return null==o&&i&&i[t]&&(o=i[t]),fn.test(o)&&!cn.test(t)&&(n=i.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),i.left="fontSize"===t?"1em":o,o=i.pixelLeft+"px",i.left=n,r&&(e.runtimeStyle.left=r)),""===o?"auto":o}),Y.each(["height","width"],function(e,n){Y.cssHooks[n]={get:function(e,r,o){return r?0===e.offsetWidth&&ln.test(nn(e,"display"))?Y.swap(e,gn,function(){return C(e,n,o)}):C(e,n,o):t},set:function(e,t,r){return b(e,t,r?_(e,n,r,Y.support.boxSizing&&"border-box"===Y.css(e,"boxSizing")):0)}}}),Y.support.opacity||(Y.cssHooks.opacity={get:function(e,t){return sn.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,o=Y.isNumeric(t)?"alpha(opacity="+100*t+")":"",i=r&&r.filter||n.filter||"";n.zoom=1,t>=1&&""===Y.trim(i.replace(an,""))&&n.removeAttribute&&(n.removeAttribute("filter"),r&&!r.filter)||(n.filter=an.test(i)?i.replace(an,o):i+" "+o)}}),Y(function(){Y.support.reliableMarginRight||(Y.cssHooks.marginRight={get:function(e,n){return Y.swap(e,{display:"inline-block"},function(){return n?nn(e,"marginRight"):t})}}),!Y.support.pixelPosition&&Y.fn.position&&Y.each(["top","left"],function(e,t){Y.cssHooks[t]={get:function(e,n){if(n){var r=nn(e,t);return fn.test(r)?Y(e).position()[t]+"px":r}}}})}),Y.expr&&Y.expr.filters&&(Y.expr.filters.hidden=function(e){return 0===e.offsetWidth&&0===e.offsetHeight||!Y.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||nn(e,"display"))},Y.expr.filters.visible=function(e){return!Y.expr.filters.hidden(e)}),Y.each({margin:"",padding:"",border:"Width"},function(e,t){Y.cssHooks[e+t]={expand:function(n){var r,o="string"==typeof n?n.split(" "):[n],i={};for(r=0;4>r;r++)i[e+yn[r]+t]=o[r]||o[r-2]||o[0];return i}},un.test(e)||(Y.cssHooks[e+t].set=b)});var _n=/%20/g,Cn=/\[\]$/,xn=/\r?\n/g,wn=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,An=/^(?:select|textarea)/i; Y.fn.extend({serialize:function(){return Y.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?Y.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||An.test(this.nodeName)||wn.test(this.type))}).map(function(e,t){var n=Y(this).val();return null==n?null:Y.isArray(n)?Y.map(n,function(e){return{name:t.name,value:e.replace(xn,"\r\n")}}):{name:t.name,value:n.replace(xn,"\r\n")}}).get()}}),Y.param=function(e,n){var r,o=[],i=function(e,t){t=Y.isFunction(t)?t():null==t?"":t,o[o.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=Y.ajaxSettings&&Y.ajaxSettings.traditional),Y.isArray(e)||e.jquery&&!Y.isPlainObject(e))Y.each(e,function(){i(this.name,this.value)});else for(r in e)w(r,e[r],n,i);return o.join("&").replace(_n,"+")};var Fn,kn,Tn=/#.*$/,En=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,Sn=/^(?:GET|HEAD)$/,Rn=/^\/\//,jn=/\?/,On=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,In=/([?&])_=[^&]*/,Mn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Pn=Y.fn.load,Hn={},Ln={},Dn=["*/"]+["*"];try{kn=B.href}catch(Un){kn=Q.createElement("a"),kn.href="",kn=kn.href}Fn=Mn.exec(kn.toLowerCase())||[],Y.fn.load=function(e,n,r){if("string"!=typeof e&&Pn)return Pn.apply(this,arguments);if(!this.length)return this;var o,i,a,s=this,c=e.indexOf(" ");return c>=0&&(o=e.slice(c,e.length),e=e.slice(0,c)),Y.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(i="POST"),Y.ajax({url:e,type:i,dataType:"html",data:n,complete:function(e,t){r&&s.each(r,a||[e.responseText,t,e])}}).done(function(e){a=arguments,s.html(o?Y("<div>").append(e.replace(On,"")).find(o):e)}),this},Y.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){Y.fn[t]=function(e){return this.on(t,e)}}),Y.each(["get","post"],function(e,n){Y[n]=function(e,r,o,i){return Y.isFunction(r)&&(i=i||o,o=r,r=t),Y.ajax({type:n,url:e,data:r,success:o,dataType:i})}}),Y.extend({getScript:function(e,n){return Y.get(e,t,n,"script")},getJSON:function(e,t,n){return Y.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?k(e,Y.ajaxSettings):(t=e,e=Y.ajaxSettings),k(e,t),e},ajaxSettings:{url:kn,isLocal:Nn.test(Fn[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","*":Dn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":Y.parseJSON,"text xml":Y.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:A(Hn),ajaxTransport:A(Ln),ajax:function(e,n){function r(e,n,r,a){var l,p,v,b,C,w=n;2!==_&&(_=2,c&&clearTimeout(c),s=t,i=a||"",x.readyState=e>0?4:0,r&&(b=T(f,x,r)),e>=200&&300>e||304===e?(f.ifModified&&(C=x.getResponseHeader("Last-Modified"),C&&(Y.lastModified[o]=C),C=x.getResponseHeader("Etag"),C&&(Y.etag[o]=C)),304===e?(w="notmodified",l=!0):(l=E(f,b),w=l.state,p=l.data,v=l.error,l=!v)):(v=w,(!w||e)&&(w="error",0>e&&(e=0))),x.status=e,x.statusText=(n||w)+"",l?g.resolveWith(d,[p,w,x]):g.rejectWith(d,[x,w,v]),x.statusCode(y),y=t,u&&h.trigger("ajax"+(l?"Success":"Error"),[x,f,l?p:v]),m.fireWith(d,[x,w]),u&&(h.trigger("ajaxComplete",[x,f]),--Y.active||Y.event.trigger("ajaxStop")))}"object"==typeof e&&(n=e,e=t),n=n||{};var o,i,a,s,c,l,u,p,f=Y.ajaxSetup({},n),d=f.context||f,h=d!==f&&(d.nodeType||d instanceof Y)?Y(d):Y.event,g=Y.Deferred(),m=Y.Callbacks("once memory"),y=f.statusCode||{},v={},b={},_=0,C="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!_){var n=e.toLowerCase();e=b[n]=b[n]||e,v[e]=t}return this},getAllResponseHeaders:function(){return 2===_?i:null},getResponseHeader:function(e){var n;if(2===_){if(!a)for(a={};n=En.exec(i);)a[n[1].toLowerCase()]=n[2];n=a[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return _||(f.mimeType=e),this},abort:function(e){return e=e||C,s&&s.abort(e),r(0,e),this}};if(g.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(2>_)for(t in e)y[t]=[y[t],e[t]];else t=e[x.status],x.always(t)}return this},f.url=((e||f.url)+"").replace(Tn,"").replace(Rn,Fn[1]+"//"),f.dataTypes=Y.trim(f.dataType||"*").toLowerCase().split(tt),null==f.crossDomain&&(l=Mn.exec(f.url.toLowerCase()),f.crossDomain=!(!l||l[1]===Fn[1]&&l[2]===Fn[2]&&(l[3]||("http:"===l[1]?80:443))==(Fn[3]||("http:"===Fn[1]?80:443)))),f.data&&f.processData&&"string"!=typeof f.data&&(f.data=Y.param(f.data,f.traditional)),F(Hn,f,n,x),2===_)return x;if(u=f.global,f.type=f.type.toUpperCase(),f.hasContent=!Sn.test(f.type),u&&0===Y.active++&&Y.event.trigger("ajaxStart"),!f.hasContent&&(f.data&&(f.url+=(jn.test(f.url)?"&":"?")+f.data,delete f.data),o=f.url,f.cache===!1)){var w=Y.now(),A=f.url.replace(In,"$1_="+w);f.url=A+(A===f.url?(jn.test(f.url)?"&":"?")+"_="+w:"")}(f.data&&f.hasContent&&f.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",f.contentType),f.ifModified&&(o=o||f.url,Y.lastModified[o]&&x.setRequestHeader("If-Modified-Since",Y.lastModified[o]),Y.etag[o]&&x.setRequestHeader("If-None-Match",Y.etag[o])),x.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Dn+"; q=0.01":""):f.accepts["*"]);for(p in f.headers)x.setRequestHeader(p,f.headers[p]);if(f.beforeSend&&(f.beforeSend.call(d,x,f)===!1||2===_))return x.abort();C="abort";for(p in{success:1,error:1,complete:1})x[p](f[p]);if(s=F(Ln,f,n,x)){x.readyState=1,u&&h.trigger("ajaxSend",[x,f]),f.async&&f.timeout>0&&(c=setTimeout(function(){x.abort("timeout")},f.timeout));try{_=1,s.send(v,r)}catch(k){if(!(2>_))throw k;r(-1,k)}}else r(-1,"No Transport");return x},active:0,lastModified:{},etag:{}});var Qn=[],Bn=/\?/,qn=/(=)\?(?=&|$)|\?\?/,Wn=Y.now();Y.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Qn.pop()||Y.expando+"_"+Wn++;return this[e]=!0,e}}),Y.ajaxPrefilter("json jsonp",function(n,r,o){var i,a,s,c=n.data,l=n.url,u=n.jsonp!==!1,p=u&&qn.test(l),f=u&&!p&&"string"==typeof c&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&qn.test(c);return"jsonp"===n.dataTypes[0]||p||f?(i=n.jsonpCallback=Y.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,a=e[i],p?n.url=l.replace(qn,"$1"+i):f?n.data=c.replace(qn,"$1"+i):u&&(n.url+=(Bn.test(l)?"&":"?")+n.jsonp+"="+i),n.converters["script json"]=function(){return s||Y.error(i+" was not called"),s[0]},n.dataTypes[0]="json",e[i]=function(){s=arguments},o.always(function(){e[i]=a,n[i]&&(n.jsonpCallback=r.jsonpCallback,Qn.push(i)),s&&Y.isFunction(a)&&a(s[0]),s=a=t}),"script"):t}),Y.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return Y.globalEval(e),e}}}),Y.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),Y.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=Q.head||Q.getElementsByTagName("head")[0]||Q.documentElement;return{send:function(o,i){n=Q.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,o){(o||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,o||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var $n,zn=e.ActiveXObject?function(){for(var e in $n)$n[e](0,1)}:!1,Jn=0;Y.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&N()||S()}:N,function(e){Y.extend(Y.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(Y.ajaxSettings.xhr()),Y.support.ajax&&Y.ajaxTransport(function(n){if(!n.crossDomain||Y.support.cors){var r;return{send:function(o,i){var a,s,c=n.xhr();if(n.username?c.open(n.type,n.url,n.async,n.username,n.password):c.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)c[s]=n.xhrFields[s];n.mimeType&&c.overrideMimeType&&c.overrideMimeType(n.mimeType),n.crossDomain||o["X-Requested-With"]||(o["X-Requested-With"]="XMLHttpRequest");try{for(s in o)c.setRequestHeader(s,o[s])}catch(l){}c.send(n.hasContent&&n.data||null),r=function(e,o){var s,l,u,p,f;try{if(r&&(o||4===c.readyState))if(r=t,a&&(c.onreadystatechange=Y.noop,zn&&delete $n[a]),o)4!==c.readyState&&c.abort();else{s=c.status,u=c.getAllResponseHeaders(),p={},f=c.responseXML,f&&f.documentElement&&(p.xml=f);try{p.text=c.responseText}catch(d){}try{l=c.statusText}catch(d){l=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(h){o||i(-1,h)}p&&i(s,l,p,u)},n.async?4===c.readyState?setTimeout(r,0):(a=++Jn,zn&&($n||($n={},Y(e).unload(zn)),$n[a]=r),c.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var Vn,Xn,Kn=/^(?:toggle|show|hide)$/,Gn=RegExp("^(?:([-+])=|)("+Z+")([a-z%]*)$","i"),Yn=/queueHooks$/,Zn=[M],er={"*":[function(e,t){var n,r,o=this.createTween(e,t),i=Gn.exec(t),a=o.cur(),s=+a||0,c=1,l=20;if(i){if(n=+i[2],r=i[3]||(Y.cssNumber[e]?"":"px"),"px"!==r&&s){s=Y.css(o.elem,e,!0)||n||1;do c=c||".5",s/=c,Y.style(o.elem,e,s+r);while(c!==(c=o.cur()/a)&&1!==c&&--l)}o.unit=r,o.start=s,o.end=i[1]?s+(i[1]+1)*n:n}return o}]};Y.Animation=Y.extend(O,{tweener:function(e,t){Y.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,o=e.length;o>r;r++)n=e[r],er[n]=er[n]||[],er[n].unshift(t)},prefilter:function(e,t){t?Zn.unshift(e):Zn.push(e)}}),Y.Tween=P,P.prototype={constructor:P,init:function(e,t,n,r,o,i){this.elem=e,this.prop=n,this.easing=o||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=i||(Y.cssNumber[n]?"":"px")},cur:function(){var e=P.propHooks[this.prop];return e&&e.get?e.get(this):P.propHooks._default.get(this)},run:function(e){var t,n=P.propHooks[this.prop];return this.pos=t=this.options.duration?Y.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):P.propHooks._default.set(this),this}},P.prototype.init.prototype=P.prototype,P.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=Y.css(e.elem,e.prop,!1,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){Y.fx.step[e.prop]?Y.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[Y.cssProps[e.prop]]||Y.cssHooks[e.prop])?Y.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},P.propHooks.scrollTop=P.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},Y.each(["toggle","show","hide"],function(e,t){var n=Y.fn[t];Y.fn[t]=function(r,o,i){return null==r||"boolean"==typeof r||!e&&Y.isFunction(r)&&Y.isFunction(o)?n.apply(this,arguments):this.animate(H(t,!0),r,o,i)}}),Y.fn.extend({fadeTo:function(e,t,n,r){return this.filter(y).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var o=Y.isEmptyObject(e),i=Y.speed(t,n,r),a=function(){var t=O(this,Y.extend({},e),i);o&&t.stop(!0)};return o||i.queue===!1?this.each(a):this.queue(i.queue,a)},stop:function(e,n,r){var o=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",i=Y.timers,a=Y._data(this);if(n)a[n]&&a[n].stop&&o(a[n]);else for(n in a)a[n]&&a[n].stop&&Yn.test(n)&&o(a[n]);for(n=i.length;n--;)i[n].elem!==this||null!=e&&i[n].queue!==e||(i[n].anim.stop(r),t=!1,i.splice(n,1));(t||!r)&&Y.dequeue(this,e)})}}),Y.each({slideDown:H("show"),slideUp:H("hide"),slideToggle:H("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){Y.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),Y.speed=function(e,t,n){var r=e&&"object"==typeof e?Y.extend({},e):{complete:n||!n&&t||Y.isFunction(e)&&e,duration:e,easing:n&&t||t&&!Y.isFunction(t)&&t};return r.duration=Y.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in Y.fx.speeds?Y.fx.speeds[r.duration]:Y.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){Y.isFunction(r.old)&&r.old.call(this),r.queue&&Y.dequeue(this,r.queue)},r},Y.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},Y.timers=[],Y.fx=P.prototype.init,Y.fx.tick=function(){var e,n=Y.timers,r=0;for(Vn=Y.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||Y.fx.stop(),Vn=t},Y.fx.timer=function(e){e()&&Y.timers.push(e)&&!Xn&&(Xn=setInterval(Y.fx.tick,Y.fx.interval))},Y.fx.interval=13,Y.fx.stop=function(){clearInterval(Xn),Xn=null},Y.fx.speeds={slow:600,fast:200,_default:400},Y.fx.step={},Y.expr&&Y.expr.filters&&(Y.expr.filters.animated=function(e){return Y.grep(Y.timers,function(t){return e===t.elem}).length});var tr=/^(?:body|html)$/i;Y.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){Y.offset.setOffset(this,e,t)});var n,r,o,i,a,s,c,l={top:0,left:0},u=this[0],p=u&&u.ownerDocument;if(p)return(r=p.body)===u?Y.offset.bodyOffset(u):(n=p.documentElement,Y.contains(n,u)?(u.getBoundingClientRect!==t&&(l=u.getBoundingClientRect()),o=L(p),i=n.clientTop||r.clientTop||0,a=n.clientLeft||r.clientLeft||0,s=o.pageYOffset||n.scrollTop,c=o.pageXOffset||n.scrollLeft,{top:l.top+s-i,left:l.left+c-a}):l)},Y.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return Y.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(Y.css(e,"marginTop"))||0,n+=parseFloat(Y.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=Y.css(e,"position");"static"===r&&(e.style.position="relative");var o,i,a=Y(e),s=a.offset(),c=Y.css(e,"top"),l=Y.css(e,"left"),u=("absolute"===r||"fixed"===r)&&Y.inArray("auto",[c,l])>-1,p={},f={};u?(f=a.position(),o=f.top,i=f.left):(o=parseFloat(c)||0,i=parseFloat(l)||0),Y.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(p.top=t.top-s.top+o),null!=t.left&&(p.left=t.left-s.left+i),"using"in t?t.using.call(e,p):a.css(p)}},Y.fn.extend({position:function(){if(this[0]){var e=this[0],t=this.offsetParent(),n=this.offset(),r=tr.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(Y.css(e,"marginTop"))||0,n.left-=parseFloat(Y.css(e,"marginLeft"))||0,r.top+=parseFloat(Y.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(Y.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||Q.body;e&&!tr.test(e.nodeName)&&"static"===Y.css(e,"position");)e=e.offsetParent;return e||Q.body})}}),Y.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);Y.fn[e]=function(o){return Y.access(this,function(e,o,i){var a=L(e);return i===t?a?n in a?a[n]:a.document.documentElement[o]:e[o]:(a?a.scrollTo(r?Y(a).scrollLeft():i,r?i:Y(a).scrollTop()):e[o]=i,t)},e,o,arguments.length,null)}}),Y.each({Height:"height",Width:"width"},function(e,n){Y.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,o){Y.fn[o]=function(o,i){var a=arguments.length&&(r||"boolean"!=typeof o),s=r||(o===!0||i===!0?"margin":"border");return Y.access(this,function(n,r,o){var i;return Y.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(i=n.documentElement,Math.max(n.body["scroll"+e],i["scroll"+e],n.body["offset"+e],i["offset"+e],i["client"+e])):o===t?Y.css(n,r,o,s):Y.style(n,r,o,s)},n,a?o:t,a,null)}})}),e.jQuery=e.$=Y,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return Y})}(window);/*! * This file creates $ and jQuery variables within the F2 closure scope */ var $,jQuery=$=window.jQuery.noConflict(!0);/*! * 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(e){function t(){this._events={}}function n(e){e&&(e.delimiter&&(this.delimiter=e.delimiter),e.wildcard&&(this.wildcard=e.wildcard),this.wildcard&&(this.listenerTree={}))}function r(e){this._events={},n.call(this,e)}function o(e,t,n,r){if(!n)return[];var i,a,s,c,l,u,p,f=[],d=t.length,h=t[r],g=t[r+1];if(r===d&&n._listeners){if("function"==typeof n._listeners)return e&&e.push(n._listeners),[n];for(i=0,a=n._listeners.length;a>i;i++)e&&e.push(n._listeners[i]);return[n]}if("*"===h||"**"===h||n[h]){if("*"===h){for(s in n)"_listeners"!==s&&n.hasOwnProperty(s)&&(f=f.concat(o(e,t,n[s],r+1)));return f}if("**"===h){p=r+1===d||r+2===d&&"*"===g,p&&n._listeners&&(f=f.concat(o(e,t,n,d)));for(s in n)"_listeners"!==s&&n.hasOwnProperty(s)&&("*"===s||"**"===s?(n[s]._listeners&&!p&&(f=f.concat(o(e,t,n[s],d))),f=f.concat(o(e,t,n[s],r))):f=s===g?f.concat(o(e,t,n[s],r+2)):f.concat(o(e,t,n[s],r)));return f}f=f.concat(o(e,t,n[h],r+1))}if(c=n["*"],c&&o(e,t,c,r+1),l=n["**"])if(d>r){l._listeners&&o(e,t,l,d);for(s in l)"_listeners"!==s&&l.hasOwnProperty(s)&&(s===g?o(e,t,l[s],r+2):s===h?o(e,t,l[s],r+1):(u={},u[s]=l[s],o(e,t,{"**":u},r+1)))}else l._listeners?o(e,t,l,d):l["*"]&&l["*"]._listeners&&o(e,t,l["*"],d);return f}function i(e,t){e="string"==typeof e?e.split(this.delimiter):e.slice();for(var n=0,r=e.length;r>n+1;n++)if("**"===e[n]&&"**"===e[n+1])return;for(var o=this.listenerTree,i=e.shift();i;){if(o[i]||(o[i]={}),o=o[i],0===e.length){if(o._listeners){if("function"==typeof o._listeners)o._listeners=[o._listeners,t];else if(a(o._listeners)&&(o._listeners.push(t),!o._listeners.warned)){var c=s;this._events.maxListeners!==undefined&&(c=this._events.maxListeners),c>0&&o._listeners.length>c&&(o._listeners.warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",o._listeners.length),console.trace())}}else o._listeners=t;return!0}i=e.shift()}return!0}var a=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},s=10;r.prototype.delimiter=".",r.prototype.setMaxListeners=function(e){this._events||t.call(this),this._events.maxListeners=e},r.prototype.event="",r.prototype.once=function(e,t){return this.many(e,1,t),this},r.prototype.many=function(e,t,n){function r(){0===--t&&o.off(e,r),n.apply(this,arguments)}var o=this;if("function"!=typeof n)throw Error("many only accepts instances of Function");return r._origin=n,this.on(e,r),o},r.prototype.emit=function(){this._events||t.call(this);var e=arguments[0];if("newListener"===e&&!this._events.newListener)return!1;if(this._all){for(var n=arguments.length,r=Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];for(i=0,n=this._all.length;n>i;i++)this.event=e,this._all[i].apply(this,r)}if("error"===e&&!(this._all||this._events.error||this.wildcard&&this.listenerTree.error))throw arguments[1]instanceof Error?arguments[1]:Error("Uncaught, unspecified 'error' event.");var a;if(this.wildcard){a=[];var s="string"==typeof e?e.split(this.delimiter):e.slice();o.call(this,a,s,this.listenerTree,0)}else a=this._events[e];if("function"==typeof a){if(this.event=e,1===arguments.length)a.call(this);else if(arguments.length>1)switch(arguments.length){case 2:a.call(this,arguments[1]);break;case 3:a.call(this,arguments[1],arguments[2]);break;default:for(var n=arguments.length,r=Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];a.apply(this,r)}return!0}if(a){for(var n=arguments.length,r=Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];for(var c=a.slice(),i=0,n=c.length;n>i;i++)this.event=e,c[i].apply(this,r);return c.length>0||this._all}return this._all},r.prototype.on=function(e,n){if("function"==typeof e)return this.onAny(e),this;if("function"!=typeof n)throw Error("on only accepts instances of Function");if(this._events||t.call(this),this.emit("newListener",e,n),this.wildcard)return i.call(this,e,n),this;if(this._events[e]){if("function"==typeof this._events[e])this._events[e]=[this._events[e],n];else if(a(this._events[e])&&(this._events[e].push(n),!this._events[e].warned)){var r=s;this._events.maxListeners!==undefined&&(r=this._events.maxListeners),r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),console.trace())}}else this._events[e]=n;return this},r.prototype.onAny=function(e){if(this._all||(this._all=[]),"function"!=typeof e)throw Error("onAny only accepts instances of Function");return this._all.push(e),this},r.prototype.addListener=r.prototype.on,r.prototype.off=function(e,t){if("function"!=typeof t)throw Error("removeListener only takes instances of Function");var n,r=[];if(this.wildcard){var i="string"==typeof e?e.split(this.delimiter):e.slice();r=o.call(this,null,i,this.listenerTree,0)}else{if(!this._events[e])return this;n=this._events[e],r.push({_listeners:n})}for(var s=0;r.length>s;s++){var c=r[s];if(n=c._listeners,a(n)){for(var l=-1,u=0,p=n.length;p>u;u++)if(n[u]===t||n[u].listener&&n[u].listener===t||n[u]._origin&&n[u]._origin===t){l=u;break}if(0>l)return this;this.wildcard?c._listeners.splice(l,1):this._events[e].splice(l,1),0===n.length&&(this.wildcard?delete c._listeners:delete this._events[e])}else(n===t||n.listener&&n.listener===t||n._origin&&n._origin===t)&&(this.wildcard?delete c._listeners:delete this._events[e])}return this},r.prototype.offAny=function(e){var t,n=0,r=0;if(e&&this._all&&this._all.length>0){for(t=this._all,n=0,r=t.length;r>n;n++)if(e===t[n])return t.splice(n,1),this}else this._all=[];return this},r.prototype.removeListener=r.prototype.off,r.prototype.removeAllListeners=function(e){if(0===arguments.length)return!this._events||t.call(this),this;if(this.wildcard)for(var n="string"==typeof e?e.split(this.delimiter):e.slice(),r=o.call(this,null,n,this.listenerTree,0),i=0;r.length>i;i++){var a=r[i];a._listeners=null}else{if(!this._events[e])return this;this._events[e]=null}return this},r.prototype.listeners=function(e){if(this.wildcard){var n=[],r="string"==typeof e?e.split(this.delimiter):e.slice();return o.call(this,n,r,this.listenerTree,0),n}return this._events||t.call(this),this._events[e]||(this._events[e]=[]),a(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]},r.prototype.listenersAny=function(){return this._all?this._all:[]},e.EventEmitter2=r}("undefined"!=typeof process&&process.title!==void 0&&exports!==void 0?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(e,t,n,r,o,i){function a(e,t){var n=typeof e[t];return"function"==n||!("object"!=n||!e[t])||"unknown"==n}function s(e,t){return!("object"!=typeof e[t]||!e[t])}function c(e){return"[object Array]"===Object.prototype.toString.call(e)}function l(){try{var e=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");return E=Array.prototype.slice.call(e.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/),1),N=parseInt(E[0],10)>9&&parseInt(E[1],10)>0,e=null,!0}catch(t){return!1}}function u(){if(!W){W=!0;for(var e=0;$.length>e;e++)$[e]();$.length=0}}function p(e,t){return W?(e.call(t),void 0):($.push(function(){e.call(t)}),void 0)}function f(){var e=parent;if(""!==L)for(var t=0,n=L.split(".");n.length>t;t++)e=e[n[t]];return e.easyXDM}function d(t){return e.easyXDM=U,L=t,L&&(Q="easyXDM_"+L.replace(".","_")+"_"),D}function h(e){return e.match(M)[3]}function g(e){return e.match(M)[4]||""}function m(e){var t=e.toLowerCase().match(M),n=t[2],r=t[3],o=t[4]||"";return("http:"==n&&":80"==o||"https:"==n&&":443"==o)&&(o=""),n+"//"+r+o}function y(e){if(e=e.replace(H,"$1/"),!e.match(/^(http||https):\/\//)){var t="/"===e.substring(0,1)?"":n.pathname;"/"!==t.substring(t.length-1)&&(t=t.substring(0,t.lastIndexOf("/")+1)),e=n.protocol+"//"+n.host+t+e}for(;P.test(e);)e=e.replace(P,"");return e}function v(e,t){var n="",r=e.indexOf("#");-1!==r&&(n=e.substring(r),e=e.substring(0,r));var o=[];for(var a in t)t.hasOwnProperty(a)&&o.push(a+"="+i(t[a]));return e+(B?"#":-1==e.indexOf("?")?"?":"&")+o.join("&")+n}function b(e){return e===void 0}function _(e,t,n){var r;for(var o in t)t.hasOwnProperty(o)&&(o in e?(r=t[o],"object"==typeof r?_(e[o],r,n):n||(e[o]=t[o])):e[o]=t[o]);return e}function C(){var e=t.body.appendChild(t.createElement("form")),n=e.appendChild(t.createElement("input"));n.name=Q+"TEST"+O,T=n!==e.elements[n.name],t.body.removeChild(e)}function x(e){b(T)&&C();var n;T?n=t.createElement('<iframe name="'+e.props.name+'"/>'):(n=t.createElement("IFRAME"),n.name=e.props.name),n.id=n.name=e.props.name,delete e.props.name,e.onLoad&&S(n,"load",e.onLoad),"string"==typeof e.container&&(e.container=t.getElementById(e.container)),e.container||(_(n.style,{position:"absolute",top:"-2000px"}),e.container=t.body);var r=e.props.src;return delete e.props.src,_(n,e.props),n.border=n.frameBorder=0,n.allowTransparency=!0,e.container.appendChild(n),n.src=r,e.props.src=r,n}function w(e,t){"string"==typeof e&&(e=[e]);for(var n,r=e.length;r--;)if(n=e[r],n=RegExp("^"==n.substr(0,1)?n:"^"+n.replace(/(\*)/g,".$1").replace(/\?/g,".")+"$"),n.test(t))return!0;return!1}function A(r){var o,i=r.protocol;if(r.isHost=r.isHost||b(J.xdm_p),B=r.hash||!1,r.props||(r.props={}),r.isHost)r.remote=y(r.remote),r.channel=r.channel||"default"+O++,r.secret=Math.random().toString(16).substring(2),b(i)&&(m(n.href)==m(r.remote)?i="4":a(e,"postMessage")||a(t,"postMessage")?i="1":r.swf&&a(e,"ActiveXObject")&&l()?i="6":"Gecko"===navigator.product&&"frameElement"in e&&-1==navigator.userAgent.indexOf("WebKit")?i="5":r.remoteHelper?(r.remoteHelper=y(r.remoteHelper),i="2"):i="0");else if(r.channel=J.xdm_c,r.secret=J.xdm_s,r.remote=J.xdm_e,i=J.xdm_p,r.acl&&!w(r.acl,r.remote))throw Error("Access denied for "+r.remote);switch(r.protocol=i,i){case"0":if(_(r,{interval:100,delay:2e3,useResize:!0,useParent:!1,usePolling:!1},!0),r.isHost){if(!r.local){for(var s,c=n.protocol+"//"+n.host,u=t.body.getElementsByTagName("img"),p=u.length;p--;)if(s=u[p],s.src.substring(0,c.length)===c){r.local=s.src;break}r.local||(r.local=e)}var f={xdm_c:r.channel,xdm_p:0};r.local===e?(r.usePolling=!0,r.useParent=!0,r.local=n.protocol+"//"+n.host+n.pathname+n.search,f.xdm_e=r.local,f.xdm_pa=1):f.xdm_e=y(r.local),r.container&&(r.useResize=!1,f.xdm_po=1),r.remote=v(r.remote,f)}else _(r,{channel:J.xdm_c,remote:J.xdm_e,useParent:!b(J.xdm_pa),usePolling:!b(J.xdm_po),useResize:r.useParent?!1:r.useResize});o=[new D.stack.HashTransport(r),new D.stack.ReliableBehavior({}),new D.stack.QueueBehavior({encode:!0,maxLength:4e3-r.remote.length}),new D.stack.VerifyBehavior({initiate:r.isHost})];break;case"1":o=[new D.stack.PostMessageTransport(r)];break;case"2":o=[new D.stack.NameTransport(r),new D.stack.QueueBehavior,new D.stack.VerifyBehavior({initiate:r.isHost})];break;case"3":o=[new D.stack.NixTransport(r)];break;case"4":o=[new D.stack.SameOriginTransport(r)];break;case"5":o=[new D.stack.FrameElementTransport(r)];break;case"6":E||l(),o=[new D.stack.FlashTransport(r)]}return o.push(new D.stack.QueueBehavior({lazy:r.lazy,remove:!0})),o}function F(e){for(var t,n={incoming:function(e,t){this.up.incoming(e,t)},outgoing:function(e,t){this.down.outgoing(e,t)},callback:function(e){this.up.callback(e)},init:function(){this.down.init()},destroy:function(){this.down.destroy()}},r=0,o=e.length;o>r;r++)t=e[r],_(t,n,!0),0!==r&&(t.down=e[r-1]),r!==o-1&&(t.up=e[r+1]);return t}function k(e){e.up.down=e.down,e.down.up=e.up,e.up=e.down=null}var T,E,N,S,R,j=this,O=Math.floor(1e4*Math.random()),I=Function.prototype,M=/^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/,P=/[\-\w]+\/\.\.\//,H=/([^:])\/\//g,L="",D={},U=e.easyXDM,Q="easyXDM_",B=!1;if(a(e,"addEventListener"))S=function(e,t,n){e.addEventListener(t,n,!1)},R=function(e,t,n){e.removeEventListener(t,n,!1)};else{if(!a(e,"attachEvent"))throw Error("Browser not supported");S=function(e,t,n){e.attachEvent("on"+t,n)},R=function(e,t,n){e.detachEvent("on"+t,n)}}var q,W=!1,$=[];if("readyState"in t?(q=t.readyState,W="complete"==q||~navigator.userAgent.indexOf("AppleWebKit/")&&("loaded"==q||"interactive"==q)):W=!!t.body,!W){if(a(e,"addEventListener"))S(t,"DOMContentLoaded",u);else if(S(t,"readystatechange",function(){"complete"==t.readyState&&u()}),t.documentElement.doScroll&&e===top){var z=function(){if(!W){try{t.documentElement.doScroll("left")}catch(e){return r(z,1),void 0}u()}};z()}S(e,"load",u)}var J=function(e){e=e.substring(1).split("&");for(var t,n={},r=e.length;r--;)t=e[r].split("="),n[t[0]]=o(t[1]);return n}(/xdm_e=/.test(n.search)?n.search:n.hash),V=function(){var e={},t={a:[1,2,3]},n='{"a":[1,2,3]}';return"undefined"!=typeof JSON&&"function"==typeof JSON.stringify&&JSON.stringify(t).replace(/\s/g,"")===n?JSON:(Object.toJSON&&Object.toJSON(t).replace(/\s/g,"")===n&&(e.stringify=Object.toJSON),"function"==typeof String.prototype.evalJSON&&(t=n.evalJSON(),t.a&&3===t.a.length&&3===t.a[2]&&(e.parse=function(e){return e.evalJSON()})),e.stringify&&e.parse?(V=function(){return e},e):null)};_(D,{version:"2.4.15.118",query:J,stack:{},apply:_,getJSONObject:V,whenReady:p,noConflict:d}),D.DomHelper={on:S,un:R,requiresJSON:function(n){s(e,"JSON")||t.write('<script type="text/javascript" src="'+n+'"><'+"/script>")}},function(){var e={};D.Fn={set:function(t,n){e[t]=n},get:function(t,n){var r=e[t];return n&&delete e[t],r}}}(),D.Socket=function(e){var t=F(A(e).concat([{incoming:function(t,n){e.onMessage(t,n)},callback:function(t){e.onReady&&e.onReady(t)}}])),n=m(e.remote);this.origin=m(e.remote),this.destroy=function(){t.destroy()},this.postMessage=function(e){t.outgoing(e,n)},t.init()},D.Rpc=function(e,t){if(t.local)for(var n in t.local)if(t.local.hasOwnProperty(n)){var r=t.local[n];"function"==typeof r&&(t.local[n]={method:r})}var o=F(A(e).concat([new D.stack.RpcBehavior(this,t),{callback:function(t){e.onReady&&e.onReady(t)}}]));this.origin=m(e.remote),this.destroy=function(){o.destroy()},o.init()},D.stack.SameOriginTransport=function(e){var t,o,i,a;return t={outgoing:function(e,t,n){i(e),n&&n()},destroy:function(){o&&(o.parentNode.removeChild(o),o=null)},onDOMReady:function(){a=m(e.remote),e.isHost?(_(e.props,{src:v(e.remote,{xdm_e:n.protocol+"//"+n.host+n.pathname,xdm_c:e.channel,xdm_p:4}),name:Q+e.channel+"_provider"}),o=x(e),D.Fn.set(e.channel,function(e){return i=e,r(function(){t.up.callback(!0)},0),function(e){t.up.incoming(e,a)}})):(i=f().Fn.get(e.channel,!0)(function(e){t.up.incoming(e,a)}),r(function(){t.up.callback(!0)},0))},init:function(){p(t.onDOMReady,t)}}},D.stack.FlashTransport=function(e){function o(e){r(function(){a.up.incoming(e,c)},0)}function i(n){var r=e.swf+"?host="+e.isHost,o="easyXDM_swf_"+Math.floor(1e4*Math.random());D.Fn.set("flash_loaded"+n.replace(/[\-.]/g,"_"),function(){D.stack.FlashTransport[n].swf=l=u.firstChild;for(var e=D.stack.FlashTransport[n].queue,t=0;e.length>t;t++)e[t]();e.length=0}),e.swfContainer?u="string"==typeof e.swfContainer?t.getElementById(e.swfContainer):e.swfContainer:(u=t.createElement("div"),_(u.style,N&&e.swfNoThrottle?{height:"20px",width:"20px",position:"fixed",right:0,top:0}:{height:"1px",width:"1px",position:"absolute",overflow:"hidden",right:0,top:0}),t.body.appendChild(u));var i="callback=flash_loaded"+n.replace(/[\-.]/g,"_")+"&proto="+j.location.protocol+"&domain="+h(j.location.href)+"&port="+g(j.location.href)+"&ns="+L;u.innerHTML="<object height='20' width='20' type='application/x-shockwave-flash' id='"+o+"' data='"+r+"'>"+"<param name='allowScriptAccess' value='always'></param>"+"<param name='wmode' value='transparent'>"+"<param name='movie' value='"+r+"'></param>"+"<param name='flashvars' value='"+i+"'></param>"+"<embed type='application/x-shockwave-flash' FlashVars='"+i+"' allowScriptAccess='always' wmode='transparent' src='"+r+"' height='1' width='1'></embed>"+"</object>"}var a,s,c,l,u;return a={outgoing:function(t,n,r){l.postMessage(e.channel,""+t),r&&r()},destroy:function(){try{l.destroyChannel(e.channel)}catch(t){}l=null,s&&(s.parentNode.removeChild(s),s=null)},onDOMReady:function(){c=e.remote,D.Fn.set("flash_"+e.channel+"_init",function(){r(function(){a.up.callback(!0)})}),D.Fn.set("flash_"+e.channel+"_onMessage",o),e.swf=y(e.swf);var t=h(e.swf),u=function(){D.stack.FlashTransport[t].init=!0,l=D.stack.FlashTransport[t].swf,l.createChannel(e.channel,e.secret,m(e.remote),e.isHost),e.isHost&&(N&&e.swfNoThrottle&&_(e.props,{position:"fixed",right:0,top:0,height:"20px",width:"20px"}),_(e.props,{src:v(e.remote,{xdm_e:m(n.href),xdm_c:e.channel,xdm_p:6,xdm_s:e.secret}),name:Q+e.channel+"_provider"}),s=x(e))};D.stack.FlashTransport[t]&&D.stack.FlashTransport[t].init?u():D.stack.FlashTransport[t]?D.stack.FlashTransport[t].queue.push(u):(D.stack.FlashTransport[t]={queue:[u]},i(t))},init:function(){p(a.onDOMReady,a)}}},D.stack.PostMessageTransport=function(t){function o(e){if(e.origin)return m(e.origin);if(e.uri)return m(e.uri);if(e.domain)return n.protocol+"//"+e.domain;throw"Unable to retrieve the origin of the event"}function i(e){var n=o(e);n==l&&e.data.substring(0,t.channel.length+1)==t.channel+" "&&a.up.incoming(e.data.substring(t.channel.length+1),n)}var a,s,c,l;return a={outgoing:function(e,n,r){c.postMessage(t.channel+" "+e,n||l),r&&r()},destroy:function(){R(e,"message",i),s&&(c=null,s.parentNode.removeChild(s),s=null)},onDOMReady:function(){if(l=m(t.remote),t.isHost){var o=function(n){n.data==t.channel+"-ready"&&(c="postMessage"in s.contentWindow?s.contentWindow:s.contentWindow.document,R(e,"message",o),S(e,"message",i),r(function(){a.up.callback(!0)},0))};S(e,"message",o),_(t.props,{src:v(t.remote,{xdm_e:m(n.href),xdm_c:t.channel,xdm_p:1}),name:Q+t.channel+"_provider"}),s=x(t)}else S(e,"message",i),c="postMessage"in e.parent?e.parent:e.parent.document,c.postMessage(t.channel+"-ready",l),r(function(){a.up.callback(!0)},0)},init:function(){p(a.onDOMReady,a)}}},D.stack.FrameElementTransport=function(o){var i,a,s,c;return i={outgoing:function(e,t,n){s.call(this,e),n&&n()},destroy:function(){a&&(a.parentNode.removeChild(a),a=null)},onDOMReady:function(){c=m(o.remote),o.isHost?(_(o.props,{src:v(o.remote,{xdm_e:m(n.href),xdm_c:o.channel,xdm_p:5}),name:Q+o.channel+"_provider"}),a=x(o),a.fn=function(e){return delete a.fn,s=e,r(function(){i.up.callback(!0)},0),function(e){i.up.incoming(e,c)}}):(t.referrer&&m(t.referrer)!=J.xdm_e&&(e.top.location=J.xdm_e),s=e.frameElement.fn(function(e){i.up.incoming(e,c)}),i.up.callback(!0))},init:function(){p(i.onDOMReady,i)}}},D.stack.NameTransport=function(e){function t(t){var n=e.remoteHelper+(s?"#_3":"#_2")+e.channel;c.contentWindow.sendMessage(t,n)}function n(){s?2!==++u&&s||a.up.callback(!0):(t("ready"),a.up.callback(!0))}function o(e){a.up.incoming(e,d)}function i(){f&&r(function(){f(!0)},0)}var a,s,c,l,u,f,d,h;return a={outgoing:function(e,n,r){f=r,t(e)},destroy:function(){c.parentNode.removeChild(c),c=null,s&&(l.parentNode.removeChild(l),l=null)},onDOMReady:function(){s=e.isHost,u=0,d=m(e.remote),e.local=y(e.local),s?(D.Fn.set(e.channel,function(t){s&&"ready"===t&&(D.Fn.set(e.channel,o),n())}),h=v(e.remote,{xdm_e:e.local,xdm_c:e.channel,xdm_p:2}),_(e.props,{src:h+"#"+e.channel,name:Q+e.channel+"_provider"}),l=x(e)):(e.remoteHelper=e.remote,D.Fn.set(e.channel,o)),c=x({props:{src:e.local+"#_4"+e.channel},onLoad:function t(){var o=c||this;R(o,"load",t),D.Fn.set(e.channel+"_load",i),function a(){"function"==typeof o.contentWindow.sendMessage?n():r(a,50)}()}})},init:function(){p(a.onDOMReady,a)}}},D.stack.HashTransport=function(t){function n(e){if(g){var n=t.remote+"#"+d++ +"_"+e;(c||!y?g.contentWindow:g).location=n}}function o(e){f=e,s.up.incoming(f.substring(f.indexOf("_")+1),v)}function i(){if(h){var e=h.location.href,t="",n=e.indexOf("#");-1!=n&&(t=e.substring(n)),t&&t!=f&&o(t)}}function a(){l=setInterval(i,u)}var s,c,l,u,f,d,h,g,y,v;return s={outgoing:function(e){n(e)},destroy:function(){e.clearInterval(l),(c||!y)&&g.parentNode.removeChild(g),g=null},onDOMReady:function(){if(c=t.isHost,u=t.interval,f="#"+t.channel,d=0,y=t.useParent,v=m(t.remote),c){if(t.props={src:t.remote,name:Q+t.channel+"_provider"},y)t.onLoad=function(){h=e,a(),s.up.callback(!0)};else{var n=0,o=t.delay/50;(function i(){if(++n>o)throw Error("Unable to reference listenerwindow");try{h=g.contentWindow.frames[Q+t.channel+"_consumer"]}catch(e){}h?(a(),s.up.callback(!0)):r(i,50)})()}g=x(t)}else h=e,a(),y?(g=parent,s.up.callback(!0)):(_(t,{props:{src:t.remote+"#"+t.channel+new Date,name:Q+t.channel+"_consumer"},onLoad:function(){s.up.callback(!0)}}),g=x(t))},init:function(){p(s.onDOMReady,s)}}},D.stack.ReliableBehavior=function(){var e,t,n=0,r=0,o="";return e={incoming:function(i,a){var s=i.indexOf("_"),c=i.substring(0,s).split(",");i=i.substring(s+1),c[0]==n&&(o="",t&&t(!0)),i.length>0&&(e.down.outgoing(c[1]+","+n+"_"+o,a),r!=c[1]&&(r=c[1],e.up.incoming(i,a)))},outgoing:function(i,a,s){o=i,t=s,e.down.outgoing(r+","+ ++n+"_"+i,a)}}},D.stack.QueueBehavior=function(e){function t(){if(e.remove&&0===s.length)return k(n),void 0;if(!c&&0!==s.length&&!a){c=!0;var o=s.shift();n.down.outgoing(o.data,o.origin,function(e){c=!1,o.callback&&r(function(){o.callback(e)},0),t()})}}var n,a,s=[],c=!0,l="",u=0,p=!1,f=!1;return n={init:function(){b(e)&&(e={}),e.maxLength&&(u=e.maxLength,f=!0),e.lazy?p=!0:n.down.init()},callback:function(e){c=!1;var r=n.up;t(),r.callback(e)},incoming:function(t,r){if(f){var i=t.indexOf("_"),a=parseInt(t.substring(0,i),10);l+=t.substring(i+1),0===a&&(e.encode&&(l=o(l)),n.up.incoming(l,r),l="")}else n.up.incoming(t,r)},outgoing:function(r,o,a){e.encode&&(r=i(r));var c,l=[];if(f){for(;0!==r.length;)c=r.substring(0,u),r=r.substring(c.length),l.push(c);for(;c=l.shift();)s.push({data:l.length+"_"+c,origin:o,callback:0===l.length?a:null})}else s.push({data:r,origin:o,callback:a});p?n.down.init():t()},destroy:function(){a=!0,n.down.destroy()}}},D.stack.VerifyBehavior=function(e){function t(){r=Math.random().toString(16).substring(2),n.down.outgoing(r)}var n,r,o;return n={incoming:function(i,a){var s=i.indexOf("_");-1===s?i===r?n.up.callback(!0):o||(o=i,e.initiate||t(),n.down.outgoing(i)):i.substring(0,s)===o&&n.up.incoming(i.substring(s+1),a)},outgoing:function(e,t,o){n.down.outgoing(r+"_"+e,t,o)},callback:function(){e.initiate&&t()}}},D.stack.RpcBehavior=function(e,t){function n(e){e.jsonrpc="2.0",i.down.outgoing(a.stringify(e))}function r(e,t){var r=Array.prototype.slice;return function(){var o,i=arguments.length,a={method:t};i>0&&"function"==typeof arguments[i-1]?(i>1&&"function"==typeof arguments[i-2]?(o={success:arguments[i-2],error:arguments[i-1]},a.params=r.call(arguments,0,i-2)):(o={success:arguments[i-1]},a.params=r.call(arguments,0,i-1)),l[""+ ++s]=o,a.id=s):a.params=r.call(arguments,0),e.namedParams&&1===a.params.length&&(a.params=a.params[0]),n(a)}}function o(e,t,r,o){if(!r)return t&&n({id:t,error:{code:-32601,message:"Procedure not found."}}),void 0;var i,a;t?(i=function(e){i=I,n({id:t,result:e})},a=function(e,r){a=I;var o={id:t,error:{code:-32099,message:e}};r&&(o.error.data=r),n(o)}):i=a=I,c(o)||(o=[o]);try{var s=r.method.apply(r.scope,o.concat([i,a]));b(s)||i(s)}catch(l){a(l.message)}}var i,a=t.serializer||V(),s=0,l={};return i={incoming:function(e){var r=a.parse(e);if(r.method)t.handle?t.handle(r,n):o(r.method,r.id,t.local[r.method],r.params);else{var i=l[r.id];r.error?i.error&&i.error(r.error):i.success&&i.success(r.result),delete l[r.id]}},init:function(){if(t.remote)for(var n in t.remote)t.remote.hasOwnProperty(n)&&(e[n]=r(t.remote[n],n));i.down.init()},destroy:function(){for(var n in t.remote)t.remote.hasOwnProperty(n)&&e.hasOwnProperty(n)&&delete e[n];i.down.destroy()}}},j.easyXDM=D}(window,document,location,window.setTimeout,decodeURIComponent,encodeURIComponent);/*! * F2 v1.3.1 10-15-2013 * 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;F2=function(){var e=function(e,n){function r(e){var t=[];return e.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?t.pop():t.push(e)}),t.join("").replace(/^\//,"/"===e.charAt(0)?"/":"")}return n=t(n||""),e=t(e||""),n&&e?(n.protocol||e.protocol)+(n.protocol||n.authority?n.authority:e.authority)+r(n.protocol||n.authority||"/"===n.pathname.charAt(0)?n.pathname:n.pathname?(e.authority&&!e.pathname?"/":"")+e.pathname.slice(0,e.pathname.lastIndexOf("/")+1)+n.pathname:e.pathname)+(n.protocol||n.authority||n.pathname?n.search:n.search||e.search)+n.hash:null},t=function(e){var t=(e+"").replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return t?{href:t[0]||"",protocol:t[1]||"",authority:t[2]||"",host:t[3]||"",hostname:t[4]||"",port:t[5]||"",pathname:t[6]||"",search:t[7]||"",hash:t[8]||""}:null};return{appConfigReplacer:function(e,t){return"root"==e||"ui"==e||"height"==e?void 0:t},Apps:{},extend:function(e,t,n){var r="function"==typeof t,o=e?e.split("."):[],i=this;t=t||{},"F2"===o[0]&&(o=o.slice(1));for(var a=0,s=o.length;s>a;a++)i[o[a]]||(i[o[a]]=r&&a+1==s?t:{}),i=i[o[a]];if(!r)for(var c in t)(i[c]===void 0||n)&&(i[c]=t[c]);return i},guid:function(){var e=function(){return(0|65536*(1+Math.random())).toString(16).substring(1)};return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},inArray:function(e,t){return jQuery.inArray(e,t)>-1},isLocalRequest:function(t){var n,r,o=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,i=t.toLowerCase(),a=o.exec(i);try{n=location.href}catch(s){n=document.createElement("a"),n.href="",n=n.href}n=n.toLowerCase(),a||(i=e(n,i).toLowerCase(),a=o.exec(i)),r=o.exec(n)||[];var c=!(a&&(a[1]!==r[1]||a[2]!==r[2]||(a[3]||("http:"===a[1]?"80":"443"))!==(r[3]||("http:"===r[1]?"80":"443"))));return c},isNativeDOMNode:function(e){var t="object"==typeof Node?e instanceof Node:e&&"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName,n="object"==typeof HTMLElement?e instanceof HTMLElement:e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.nodeName;return t||n},log:function(){for(var e,t,n,r="log",o=function(){},i=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","table","time","timeEnd","timeStamp","trace","warn"],a=i.length,s=window.console=window.console||{};a--;)t=i[a],s[t]||(s[t]=o),arguments&&arguments.length>1&&arguments[0]==t&&(r=t,n=Array.prototype.slice.call(arguments,1));e=Function.prototype.bind?Function.prototype.bind.call(s[r],s):function(){Function.prototype.apply.call(s[r],s,n||arguments)},e.apply(this,n||arguments)},parse:function(e){return JSON.parse(e)},stringify:function(e,t,n){return JSON.stringify(e,t,n)},version:function(){return"{{sdk.version}}"}}}(),F2.extend("AppHandlers",function(){var e=F2.guid(),t=F2.guid(),n={appCreateRoot:[],appRenderBefore:[],appDestroyBefore:[],appRenderAfter:[],appDestroyAfter:[],appRender:[],appDestroy:[],appScriptLoadFailed:[]},r={appRender:function(e,t){var n=null;F2.isNativeDOMNode(e.root)?(n=jQuery(e.root),n.append(t)):(e.root=jQuery(t).get(0),n=jQuery(e.root)),jQuery("body").append(n)},appDestroy:function(e){e&&e.app&&e.app.destroy&&"function"==typeof e.app.destroy?e.app.destroy():e&&e.app&&e.app.destroy&&F2.log(e.config.appId+" has a destroy property, but destroy is not of type function and as such will not be executed."),jQuery(e.config.root).fadeOut(500,function(){jQuery(this).remove()})}},o=function(e,t,n,r){i(e);var o={func:n,namespace:t,domNode:F2.isNativeDOMNode(n)?n:null};if(!o.func&&!o.domNode)throw"Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.";if(o.domNode&&!r)throw"Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.";return o},i=function(n){if(e!=n&&t!=n)throw"Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken()."},a=function(e,t,r){if(i(e),r||t)if(!r&&t)n[t]=[];else if(r&&!t){r=r.toLowerCase();for(var o in n){for(var a=n[o],s=[],c=0,l=a.length;l>c;c++){var u=a[c];u&&(u.namespace&&u.namespace.toLowerCase()==r||s.push(u))}a=s}}else if(r&&n[t]){r=r.toLowerCase();for(var p=[],f=0,d=n[t].length;d>f;f++){var h=n[t][f];h&&(h.namespace&&h.namespace.toLowerCase()==r||p.push(h))}n[t]=p}};return{getToken:function(){return delete this.getToken,e},__f2GetToken:function(){return delete this.__f2GetToken,t},__trigger:function(e,o){if(e!=t)throw"Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().";if(!n||!n[o])throw"Invalid EventKey passed. Check your inputs and try again.";for(var i=[],a=2,s=arguments.length;s>a;a++)i.push(arguments[a]);if(0===n[o].length&&r[o])return r[o].apply(F2,i),this;if(0===n[o].length&&!n[o])return this;for(var c=0,l=n[o].length;l>c;c++){var u=n[o][c];if(u.domNode&&arguments[2]&&arguments[2].root&&arguments[3]){var p=jQuery(arguments[2].root).append(arguments[3]);jQuery(u.domNode).append(p)}else u.domNode&&arguments[2]&&!arguments[2].root&&arguments[3]?(arguments[2].root=jQuery(arguments[3]).get(0),jQuery(u.domNode).append(arguments[2].root)):u.func.apply(F2,i)}return this},on:function(e,t,r){var i=null;if(!t)throw"eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.";if(t.indexOf(".")>-1){var a=t.split(".");t=a[0],i=a[1]}if(!n||!n[t])throw"Invalid EventKey passed. Check your inputs and try again.";return n[t].push(o(e,i,r,"appRender"==t)),this},off:function(e,t){var r=null;if(!t)throw"eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.";if(t.indexOf(".")>-1){var o=t.split(".");t=o[0],r=o[1]}if(!n||!n[t])throw"Invalid EventKey passed. Check your inputs and try again.";return a(e,t,r),this}}}()),F2.extend("Constants",{AppHandlers:function(){return{APP_CREATE_ROOT:"appCreateRoot",APP_RENDER_BEFORE:"appRenderBefore",APP_RENDER:"appRender",APP_RENDER_AFTER:"appRenderAfter",APP_DESTROY_BEFORE:"appDestroyBefore",APP_DESTROY:"appDestroy",APP_DESTROY_AFTER:"appDestroyAfter",APP_SCRIPT_LOAD_FAILED:"appScriptLoadFailed"}}()}),F2.extend("",{App:function(){return{init:function(){}}},AppConfig:{appId:"",context:{},enableBatchRequests:!1,height:0,instanceId:"",isSecure:!1,manifestUrl:"",maxWidth:0,minGridSize:4,minWidth:300,name:"",root:void 0,ui:void 0,views:[]},AppManifest:{apps:[],inlineScripts:[],scripts:[],styles:[]},AppContent:{data:{},html:"",status:""},ContainerConfig:{afterAppRender:function(){},appRender:function(){},beforeAppRender:function(){},debugMode:!1,scriptErrorTimeout:7e3,isSecureAppPage:!1,secureAppPagePath:"",supportedViews:[],UI:{Mask:{backgroundColor:"#FFF",loadingIcon:"",opacity:.6,useClasses:!1,zIndex:2}},xhr:{dataType:function(){},type:function(){},url:function(){}}}}),F2.extend("Constants",{Css:function(){var e="f2-";return{APP:e+"app",APP_CONTAINER:e+"app-container",APP_TITLE:e+"app-title",APP_VIEW:e+"app-view",APP_VIEW_TRIGGER:e+"app-view-trigger",MASK:e+"mask",MASK_CONTAINER:e+"mask-container"}}(),Events:function(){var e="App.",t="Container.";return{APP_SYMBOL_CHANGE:e+"symbolChange",APP_WIDTH_CHANGE:e+"widthChange.",CONTAINER_SYMBOL_CHANGE:t+"symbolChange",CONTAINER_WIDTH_CHANGE:t+"widthChange"}}(),JSONP_CALLBACK:"F2_jsonpCallback_",Sockets:{EVENT:"__event__",LOAD:"__socketLoad__",RPC:"__rpc__",RPC_CALLBACK:"__rpcCallback__",UI_RPC:"__uiRpc__"},Views:{DATA_ATTRIBUTE:"data-f2-view",ABOUT:"about",HELP:"help",HOME:"home",REMOVE:"remove",SETTINGS:"settings"}}),F2.extend("Events",function(){var e=new EventEmitter2({wildcard:!0});return e.setMaxListeners(0),{_socketEmit:function(){return EventEmitter2.prototype.emit.apply(e,[].slice.call(arguments))},emit:function(){return F2.Rpc.broadcast(F2.Constants.Sockets.EVENT,[].slice.call(arguments)),EventEmitter2.prototype.emit.apply(e,[].slice.call(arguments))},many:function(t,n,r){return e.many(t,n,r)},off:function(t,n){return e.off(t,n)},on:function(t,n){return e.on(t,n)},once:function(t,n){return e.once(t,n)}}}()),F2.extend("Rpc",function(){var e={},t="",n={},r=RegExp("^"+F2.Constants.Sockets.EVENT),o=RegExp("^"+F2.Constants.Sockets.RPC),i=RegExp("^"+F2.Constants.Sockets.RPC_CALLBACK),a=RegExp("^"+F2.Constants.Sockets.LOAD),s=RegExp("^"+F2.Constants.Sockets.UI_RPC),c=function(){var e,t=!1,r=[],o=new easyXDM.Socket({onMessage:function(i,s){if(!t&&a.test(i)){i=i.replace(a,"");var c=F2.parse(i);2==c.length&&(e=c[0],n[e.instanceId]={config:e,socket:o},F2.registerApps([e],[c[1]]),jQuery.each(r,function(){p(e,i,s)}),t=!0)}else t?p(e,i,s):r.push(i)}})},l=function(e,n){var r=jQuery(e.root);if(r.is("."+F2.Constants.Css.APP_CONTAINER)||r.find("."+F2.Constants.Css.APP_CONTAINER),!r.length)return F2.log("Unable to locate app in order to establish secure connection."),void 0;var o={scrolling:"no",style:{width:"100%"}};e.height&&(o.style.height=e.height+"px");var i=new easyXDM.Socket({remote:t,container:r.get(0),props:o,onMessage:function(t,n){p(e,t,n)},onReady:function(){i.postMessage(F2.Constants.Sockets.LOAD+F2.stringify([e,n],F2.appConfigReplacer))}});return i},u=function(e,t){return function(){F2.Rpc.call(e,F2.Constants.Sockets.RPC_CALLBACK,t,[].slice.call(arguments).slice(2))}},p=function(t,n){function a(e,t){for(var n=(t+"").split("."),r=0;n.length>r;r++){if(void 0===e[n[r]]){e=void 0;break}e=e[n[r]]}return e}function c(e,t,n){var r=F2.parse(t.replace(e,""));return r.params&&r.params.length&&r.callbacks&&r.callbacks.length&&jQuery.each(r.callbacks,function(e,t){jQuery.each(r.params,function(e,o){t==o&&(r.params[e]=u(n,t))})}),r}var l,p;s.test(n)?(l=c(s,n,t.instanceId),p=a(t.ui,l.functionName),void 0!==p?p.apply(t.ui,l.params):F2.log("Unable to locate UI RPC function: "+l.functionName)):o.test(n)?(l=c(o,n,t.instanceId),p=a(window,l.functionName),void 0!==p?p.apply(p,l.params):F2.log("Unable to locate RPC function: "+l.functionName)):i.test(n)?(l=c(i,n,t.instanceId),void 0!==e[l.functionName]&&(e[l.functionName].apply(e[l.functionName],l.params),delete e[l.functionName])):r.test(n)&&(l=c(r,n,t.instanceId),F2.Events._socketEmit.apply(F2.Events,l))},f=function(t){var n=F2.guid();return e[n]=t,n};return{broadcast:function(e,t){var r=e+F2.stringify(t);jQuery.each(n,function(e,t){t.socket.postMessage(r)})},call:function(e,t,r,o){var i=[];jQuery.each(o,function(e,t){if("function"==typeof t){var n=f(t);o[e]=n,i.push(n)}}),n[e].socket.postMessage(t+F2.stringify({functionName:r,params:o,callbacks:i}))},init:function(e){t=e,t||c()},isRemote:function(e){return void 0!==n[e]&&n[e].config.isSecure&&0===jQuery(n[e].config.root).find("iframe").length},register:function(e,t){e&&t?n[e.instanceId]={config:e,socket:l(e,t)}:F2.log("Unable to register socket connection. Please check container configuration.")}}}()),F2.extend("UI",function(){var e,t=function(e){var t=e,n=jQuery(e.root),r=function(e){e=e||jQuery(t.root).outerHeight(),F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"updateHeight",[e]):(t.height=e,n.find("iframe").height(t.height))};return{hideMask:function(e){F2.UI.hideMask(t.instanceId,e)},Modals:function(){var e=function(e){return['<div class="modal">','<header class="modal-header">',"<h3>Alert!</h3>","</header>",'<div class="modal-body">',"<p>",e,"</p>","</div>",'<div class="modal-footer">','<button class="btn btn-primary btn-ok">OK</button>',"</div>","</div>"].join("")},n=function(e){return['<div class="modal">','<header class="modal-header">',"<h3>Confirm</h3>","</header>",'<div class="modal-body">',"<p>",e,"</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{alert:function(n,r){return F2.isInit()?(F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"Modals.alert",[].slice.call(arguments)):jQuery(e(n)).on("show",function(){var e=this;jQuery(e).find(".btn-primary").on("click",function(){jQuery(e).modal("hide").remove(),(r||jQuery.noop)()})}).modal({backdrop:!0}),void 0):(F2.log("F2.init() must be called before F2.UI.Modals.alert()"),void 0)},confirm:function(e,r,o){return F2.isInit()?(F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"Modals.confirm",[].slice.call(arguments)):jQuery(n(e)).on("show",function(){var e=this;jQuery(e).find(".btn-ok").on("click",function(){jQuery(e).modal("hide").remove(),(r||jQuery.noop)()}),jQuery(e).find(".btn-cancel").on("click",function(){jQuery(e).modal("hide").remove(),(o||jQuery.noop)()})}).modal({backdrop:!0}),void 0):(F2.log("F2.init() must be called before F2.UI.Modals.confirm()"),void 0)}}}(),setTitle:function(e){F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"setTitle",[e]):jQuery(t.root).find("."+F2.Constants.Css.APP_TITLE).text(e)},showMask:function(e,n){F2.UI.showMask(t.instanceId,e,n)},updateHeight:r,Views:function(){var e=new EventEmitter2,o=/change/i;e.setMaxListeners(0);var i=function(e){return o.test(e)?!0:(F2.log('"'+e+'" is not a valid F2.UI.Views event name'),!1)};return{change:function(o){"function"==typeof o?this.on("change",o):"string"==typeof o&&(t.isSecure&&!F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"Views.change",[].slice.call(arguments)):F2.inArray(o,t.views)&&(jQuery("."+F2.Constants.Css.APP_VIEW,n).addClass("hide").filter('[data-f2-view="'+o+'"]',n).removeClass("hide"),r(),e.emit("change",o)))},off:function(t,n){i(t)&&e.off(t,n)},on:function(t,n){i(t)&&e.on(t,n)}}}()}};return t.hideMask=function(e,t){if(!F2.isInit())return F2.log("F2.init() must be called before F2.UI.hideMask()"),void 0;if(F2.Rpc.isRemote(e)&&!jQuery(t).is("."+F2.Constants.Css.APP))F2.Rpc.call(e,F2.Constants.Sockets.RPC,"F2.UI.hideMask",[e,jQuery(t).selector]);else{var n=jQuery(t);n.find("> ."+F2.Constants.Css.MASK).remove(),n.removeClass(F2.Constants.Css.MASK_CONTAINER),n.data(F2.Constants.Css.MASK_CONTAINER)&&n.css({position:"static"})}},t.init=function(t){e=t,e.UI=jQuery.extend(!0,{},F2.ContainerConfig.UI,e.UI||{})},t.showMask=function(t,n,r){if(!F2.isInit())return F2.log("F2.init() must be called before F2.UI.showMask()"),void 0;if(F2.Rpc.isRemote(t)&&jQuery(n).is("."+F2.Constants.Css.APP))F2.Rpc.call(t,F2.Constants.Sockets.RPC,"F2.UI.showMask",[t,jQuery(n).selector,r]);else{r&&!e.UI.Mask.loadingIcon&&F2.log("Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();");var o=jQuery(n).addClass(F2.Constants.Css.MASK_CONTAINER),i=jQuery("<div>").height("100%").width("100%").addClass(F2.Constants.Css.MASK);e.UI.Mask.useClasses||i.css({"background-color":e.UI.Mask.backgroundColor,"background-image":e.UI.Mask.loadingIcon?"url("+e.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":e.UI.Mask.zIndex,filter:"alpha(opacity="+100*e.UI.Mask.opacity+")",opacity:e.UI.Mask.opacity}),"static"===o.css("position")&&(o.css({position:"relative"}),o.data(F2.Constants.Css.MASK_CONTAINER,!0)),o.append(i)}},t}()),F2.extend("",function(){var _apps={},_config=!1,_bUsesAppHandlers=!1,_sAppHandlerToken=F2.AppHandlers.__f2GetToken(),_afterAppRender=function(e,t){var n=_config.afterAppRender||function(e,t){return jQuery(t).appendTo("body")},r=n(e,t);return _config.afterAppRender&&!r?(F2.log("F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app"),void 0):(jQuery(r).addClass(F2.Constants.Css.APP),r.get(0))},_appRender=function(e,t){return t=_outerHtml(jQuery(t).addClass(F2.Constants.Css.APP_CONTAINER+" "+e.appId)),_config.appRender&&(t=_config.appRender(e,t)),_outerHtml(t)},_beforeAppRender=function(e){var t=_config.beforeAppRender||jQuery.noop;return t(e)},_appScriptLoadFailed=function(e,t){var n=_config.appScriptLoadFailed||jQuery.noop;return n(e,t)},_createAppConfig=function(e){return e=jQuery.extend(!0,{},e),e.instanceId=e.instanceId||F2.guid(),e.views=e.views||[],F2.inArray(F2.Constants.Views.HOME,e.views)||e.views.push(F2.Constants.Views.HOME),e},_hydrateContainerConfig=function(e){e.scriptErrorTimeout||(e.scriptErrorTimeout=F2.ContainerConfig.scriptErrorTimeout),e.debugMode!==!0&&(e.debugMode=F2.ContainerConfig.debugMode)},_initAppEvents=function(e){jQuery(e.root).on("click","."+F2.Constants.Css.APP_VIEW_TRIGGER+"["+F2.Constants.Views.DATA_ATTRIBUTE+"]",function(t){t.preventDefault();var n=jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();n==F2.Constants.Views.REMOVE?F2.removeApp(e.instanceId):e.ui.Views.change(n)})},_initContainerEvents=function(){var e,t=function(){F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE)};jQuery(window).on("resize",function(){clearTimeout(e),e=setTimeout(t,100)})},_isInit=function(){return!!_config},_createAppInstance=function(e,t){e.ui=new F2.UI(e),void 0!==F2.Apps[e.appId]&&("function"==typeof F2.Apps[e.appId]?setTimeout(function(){_apps[e.instanceId].app=new F2.Apps[e.appId](e,t,e.root),void 0!==_apps[e.instanceId].app.init&&_apps[e.instanceId].app.init()},0):F2.log("app initialization class is defined but not a function. ("+e.appId+")"))},_loadApps=function(appConfigs,appManifest){if(appConfigs=[].concat(appConfigs),1==appConfigs.length&&appConfigs[0].isSecure&&!_config.isSecureAppPage)return _loadSecureApp(appConfigs[0],appManifest),void 0;if(appConfigs.length!=appManifest.apps.length)return F2.log("The number of apps defined in the AppManifest do not match the number requested.",appManifest),void 0;var scripts=appManifest.scripts||[],styles=appManifest.styles||[],inlines=appManifest.inlineScripts||[],scriptCount=scripts.length,scriptsLoaded=0,appInit=function(){jQuery.each(appConfigs,function(e,t){_createAppInstance(t,appManifest.apps[e])})},isFileReady=function(e){return!e||"loaded"==e||"complete"==e||"uninitialized"==e},_onload=function(e){if("load"==e.type||isFileReady((e.currentTarget||e.srcElement).readyState)){var t=e.currentTarget||e.srcElement;t.detachEvent?t.detachEvent("onreadystatechange",_onload):(removeEventListener(t,_onload,"load"),removeEventListener(t,_error,"error"))}++scriptsLoaded==scriptCount&&(evalInlines(),appInit())},_error=function(e){setTimeout(function(){var t={src:e.target.src,appId:appConfigs[0].appId};F2.log("Script defined in '"+t.appId+"' failed to load '"+t.src+"'"),F2.Events.emit("RESOURCE_FAILED_TO_LOAD",t),_bUsesAppHandlers?F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,appConfigs[0],t.src):_appScriptLoadFailed(appConfigs[0],t.src)},_config.scriptErrorTimeout)},evalInlines=function(){jQuery.each(inlines,function(i,e){try{eval(e)}catch(exception){F2.log("Error loading inline script: "+exception+"\n\n"+e),_bUsesAppHandlers?F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,appConfigs[0],exception):_appScriptLoadFailed(appConfigs[0],exception)}})},stylesFragment=null,useCreateStyleSheet=!!document.createStyleSheet;jQuery.each(styles,function(e,t){useCreateStyleSheet?document.createStyleSheet(t):(stylesFragment=stylesFragment||[],stylesFragment.push('<link rel="stylesheet" type="text/css" href="'+t+'"/>'))}),stylesFragment&&jQuery("head").append(stylesFragment.join("")),jQuery.each(appManifest.apps,function(e,t){if(_bUsesAppHandlers){F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER,appConfigs[e],_outerHtml(t.html));var n=appConfigs[e].appId;if(!appConfigs[e].root)throw"Root for "+n+" 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.";var r=jQuery(appConfigs[e].root);if(0===r.parents("body:first").length)throw"App root for "+n+" was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.";if(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER_AFTER,appConfigs[e]),!F2.isNativeDOMNode(appConfigs[e].root))throw"App root for "+n+" must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.";r.addClass(F2.Constants.Css.APP_CONTAINER+" "+n)}else appConfigs[e].root=_afterAppRender(appConfigs[e],_appRender(appConfigs[e],t.html));_initAppEvents(appConfigs[e])}),jQuery.each(scripts,function(e,t){var n=document,r=n.createElement("script"),o=t;_config.debugMode&&(o+="?cachebuster="+(new Date).getTime()),r.async=!1,r.src=o,r.type="text/javascript",r.charset="utf-8",!r.attachEvent||r.attachEvent.toString&&0>(""+r.attachEvent).indexOf("[native code")?(r.addEventListener("load",_onload,!1),r.addEventListener("error",_error,!1)):r.attachEvent("onreadystatechange",_onload),n.body.appendChild(r)}),scriptCount||(evalInlines(),appInit())},_loadSecureApp=function(e,t){if(_config.secureAppPagePath){if(_bUsesAppHandlers){var n=jQuery(e.root);if(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER,e,t.html),0===n.parents("body:first").length)throw"App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.";if(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER_AFTER,e),!e.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(e.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(e.root).addClass(F2.Constants.Css.APP_CONTAINER+" "+e.appId)}else e.root=_afterAppRender(e,_appRender(e,"<div></div>"));e.ui=new F2.UI(e),_initAppEvents(e),F2.Rpc.register(e,t)}else F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.')},_outerHtml=function(e){return jQuery("<div></div>").append(e).html()},_validateApp=function(e){return e.appId?e.root||e.manifestUrl?!0:(F2.log('"manifestUrl" missing from app object'),!1):(F2.log('"appId" missing from app object'),!1)},_validateContainerConfig=function(){if(_config&&_config.xhr){if("function"!=typeof _config.xhr&&"object"!=typeof _config.xhr)throw"ContainerConfig.xhr should be a function or an object";if(_config.xhr.dataType&&"function"!=typeof _config.xhr.dataType)throw"ContainerConfig.xhr.dataType should be a function";if(_config.xhr.type&&"function"!=typeof _config.xhr.type)throw"ContainerConfig.xhr.type should be a function";if(_config.xhr.url&&"function"!=typeof _config.xhr.url)throw"ContainerConfig.xhr.url should be a function"}return!0};return{getContainerState:function(){return _isInit()?jQuery.map(_apps,function(e){return{appId:e.config.appId}}):(F2.log("F2.init() must be called before F2.getContainerState()"),void 0)},init:function(e){_config=e||{},_validateContainerConfig(),_hydrateContainerConfig(_config),_bUsesAppHandlers=!(_config.beforeAppRender||_config.appRender||_config.afterAppRender||_config.appScriptLoadFailed),(_config.secureAppPagePath||_config.isSecureAppPage)&&F2.Rpc.init(_config.secureAppPagePath?_config.secureAppPagePath:!1),F2.UI.init(_config),_config.isSecureAppPage||_initContainerEvents()},isInit:_isInit,registerApps:function(e,t){if(!_isInit())return F2.log("F2.init() must be called before F2.registerApps()"),void 0;if(!e)return F2.log("At least one AppConfig must be passed when calling F2.registerApps()"),void 0;var n=[],r={},o={},i=!1;return e=[].concat(e),t=[].concat(t||[]),i=!!t.length,e.length?e.length&&i&&e.length!=t.length?(F2.log('The length of "apps" does not equal the length of "appManifests"'),void 0):(jQuery.each(e,function(e,o){if(o=_createAppConfig(o),o.root=o.root||null,_validateApp(o)){if(_apps[o.instanceId]={config:o},o.root){if(!o.root&&"string"!=typeof o.root&&!F2.isNativeDOMNode(o.root))throw F2.log("AppConfig invalid for pre-load, not a valid string and not dom node"),F2.log("AppConfig instance:",o),"Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.";if(1!=jQuery(o.root).length)throw F2.log("AppConfig invalid for pre-load, root not unique"),F2.log("AppConfig instance:",o),F2.log("Number of dom node instances:",jQuery(o.root).length),"Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.";return _createAppInstance(o),_initAppEvents(o),void 0}_bUsesAppHandlers?(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_CREATE_ROOT,o),F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER_BEFORE,o)):o.root=_beforeAppRender(o),i?_loadApps(o,t[e]):o.enableBatchRequests&&!o.isSecure?(r[o.manifestUrl.toLowerCase()]=r[o.manifestUrl.toLowerCase()]||[],r[o.manifestUrl.toLowerCase()].push(o)):n.push({apps:[o],url:o.manifestUrl})}}),i||(jQuery.each(r,function(e,t){n.push({url:e,apps:t})}),jQuery.each(n,function(e,t){var n=F2.Constants.JSONP_CALLBACK+t.apps[0].appId;o[n]=o[n]||[],o[n].push(t)}),jQuery.each(o,function(e,t){var n=function(r,o){if(o){var i=o.url,a="GET",s="jsonp",c=function(){n(e,t.pop())},l=function(){jQuery.each(o.apps,function(e,t){F2.log("Removed failed "+t.name+" app",t),F2.removeApp(t.instanceId)})},u=function(e){_loadApps(o.apps,e)};if(_config.xhr&&_config.xhr.dataType&&(s=_config.xhr.dataType(o.url,o.apps),"string"!=typeof s))throw"ContainerConfig.xhr.dataType should return a string";if(_config.xhr&&_config.xhr.type&&(a=_config.xhr.type(o.url,o.apps),"string"!=typeof a))throw"ContainerConfig.xhr.type should return a string";if(_config.xhr&&_config.xhr.url&&(i=_config.xhr.url(o.url,o.apps),"string"!=typeof i))throw"ContainerConfig.xhr.url should return a string";var p=_config.xhr;"function"!=typeof p&&(p=function(e,t,n,i,c){jQuery.ajax({url:e,type:a,data:{params:F2.stringify(o.apps,F2.appConfigReplacer)},jsonp:!1,jsonpCallback:r,dataType:s,success:n,error:function(e,t,n){F2.log("Failed to load app(s)",""+n,o.apps),i()},complete:c})}),p(i,o.apps,u,l,c)}};n(e,t.pop())})),void 0):(F2.log("At least one AppConfig must be passed when calling F2.registerApps()"),void 0)},removeAllApps:function(){return _isInit()?(jQuery.each(_apps,function(e,t){F2.removeApp(t.config.instanceId)}),void 0):(F2.log("F2.init() must be called before F2.removeAllApps()"),void 0)},removeApp:function(e){return _isInit()?(_apps[e]&&(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_DESTROY_BEFORE,_apps[e]),F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_DESTROY,_apps[e]),F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_DESTROY_AFTER,_apps[e]),delete _apps[e]),void 0):(F2.log("F2.init() must be called before F2.removeApp()"),void 0)}}}()),exports.F2=F2,"undefined"!=typeof define&&define.amd&&define(function(){return F2})}})("undefined"!=typeof exports?exports:window);
client/templates/layout/footer/footer.js
allpoolspa/allpoolspa.com
/* * This is an example of a customized template. * This footer replaces the "layoutFooter" template defined in the reactioncommerce:core package. * https://github.com/reactioncommerce/reaction-core/blob/master/client/templates/layout/footer/footer.html */ Template.layoutFooter.helpers({ customSocialSettings: function() { return { placement: 'footer', faClass: 'square', faSize: 'fa-3x', appsOrder: ['facebook', 'twitter', 'pinterest', 'googleplus'] }; } }); //Template.{TemplateYouWishToUse}.replaces("{templateYouWishToReplace}") Template.footer.replaces("layoutFooter");
ajax/libs/recompose/0.18.0/Recompose.js
joeyparrish/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["Recompose"] = factory(require("react")); else root["Recompose"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_3__) { 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__) { module.exports = __webpack_require__(31); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var createHelper = function createHelper(func, helperName) { var setDisplayName = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2]; var noArgs = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; if (false) { var _ret = function () { var wrapDisplayName = require('./wrapDisplayName').default; if (noArgs) { return { v: function v(BaseComponent) { var Component = func(BaseComponent); Component.displayName = wrapDisplayName(BaseComponent, helperName); return Component; } }; } return { v: function v() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (process.env.NODE_ENV !== 'production' && args.length > func.length) { /* eslint-disable */ console.error( /* eslint-enable */ 'Too many arguments passed to ' + helperName + '(). It should called ' + ('like so: ' + helperName + '(...args)(BaseComponent).')); } return function (BaseComponent) { var Component = noArgs ? func(BaseComponent) : func.apply(undefined, args)(BaseComponent); Component.displayName = wrapDisplayName(BaseComponent, helperName); return Component; }; } }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } return func; }; exports.default = createHelper; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.internalCreateElement = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _isReferentiallyTransparentFunctionComponent = __webpack_require__(32); var _isReferentiallyTransparentFunctionComponent2 = _interopRequireDefault(_isReferentiallyTransparentFunctionComponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _createElement = function _createElement(hasKey, isReferentiallyTransparent, Component, props, children) { if (!hasKey && isReferentiallyTransparent) { var component = Component; if (children) { return component(_extends({}, props, { children: children })); } return component(props); } if (children) { return _react2.default.createElement( Component, props, children ); } return _react2.default.createElement(Component, props); }; var internalCreateElement = exports.internalCreateElement = function internalCreateElement(Component) { var isReferentiallyTransparent = (0, _isReferentiallyTransparentFunctionComponent2.default)(Component); return function (p, c) { return _createElement(false, isReferentiallyTransparent, Component, p, c); }; }; var createElement = function createElement(Component, props, children) { var isReferentiallyTransparent = (0, _isReferentiallyTransparentFunctionComponent2.default)(Component); /* eslint-disable */ var hasKey = props && props.hasOwnProperty('key'); /* eslint-enable */ return _createElement(hasKey, isReferentiallyTransparent, Component, props, children); }; exports.default = createElement; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var mapProps = function mapProps(propsMapper) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); return function (props) { return createElement(propsMapper(props)); }; }; }; exports.default = (0, _createHelper2.default)(mapProps, 'mapProps'); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _shallowEqual = __webpack_require__(50); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _shallowEqual2.default; /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var omit = function omit(obj, keys) { var rest = _objectWithoutProperties(obj, []); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (rest.hasOwnProperty(key)) { delete rest[key]; } } return rest; }; exports.default = omit; /***/ }, /* 7 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var getDisplayName = function getDisplayName(Component) { if (typeof Component === 'string') { return Component; } if (!Component) { return undefined; } return Component.displayName || Component.name || 'Component'; }; exports.default = getDisplayName; /***/ }, /* 8 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var isClassComponent = function isClassComponent(Component) { return Boolean(Component && Component.prototype && _typeof(Component.prototype.isReactComponent) === 'object'); }; exports.default = isClassComponent; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var setStatic = function setStatic(key, value) { return function (BaseComponent) { BaseComponent[key] = value; return BaseComponent; }; }; exports.default = (0, _createHelper2.default)(setStatic, 'setStatic', false); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); 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; } var shouldUpdate = function shouldUpdate(test) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); return function (_Component) { _inherits(_class, _Component); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, Object.getPrototypeOf(_class).apply(this, arguments)); } _createClass(_class, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { return test(this.props, nextProps); } }, { key: 'render', value: function render() { return createElement(this.props); } }]); return _class; }(_react.Component); }; }; exports.default = (0, _createHelper2.default)(shouldUpdate, 'shouldUpdate'); /***/ }, /* 11 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var pick = function pick(obj, keys) { var result = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (obj.hasOwnProperty(key)) { result[key] = obj[key]; } } return result; }; exports.default = pick; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(17), baseLodash = __webpack_require__(14); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; module.exports = LazyWrapper; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(17), baseLodash = __webpack_require__(14); /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; module.exports = LodashWrapper; /***/ }, /* 14 */ /***/ function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }, /* 15 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @type {Function} * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _shouldUpdate = __webpack_require__(10); var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate); var _shallowEqual = __webpack_require__(5); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _pick = __webpack_require__(11); var _pick2 = _interopRequireDefault(_pick); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) { return (0, _shouldUpdate2.default)(function (props, nextProps) { return !(0, _shallowEqual2.default)((0, _pick2.default)(nextProps, propKeys), (0, _pick2.default)(props, propKeys)); }); }; exports.default = (0, _createHelper2.default)(onlyUpdateForKeys, 'onlyUpdateForKeys'); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(21); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(proto) { return isObject(proto) ? objectCreate(proto) : {}; } module.exports = baseCreate; /***/ }, /* 18 */ /***/ function(module, exports) { /** * A no-operation function that returns `undefined` regardless of the * arguments it receives. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * var object = { 'user': 'fred' }; * * _.noop(object) === undefined; * // => true */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var realNames = __webpack_require__(61); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } module.exports = getFuncName; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(65), isObjectLike = __webpack_require__(22); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 21 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 22 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); var _createElement2 = _interopRequireDefault(_createElement); 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; } var branch = function branch(test, left, right) { return function (BaseComponent) { return function (_React$Component) { _inherits(_class2, _React$Component); function _class2(props, context) { _classCallCheck(this, _class2); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class2).call(this, props, context)); _this.LeftComponent = null; _this.RightComponent = null; _this.computeChildComponent(_this.props); return _this; } _createClass(_class2, [{ key: 'computeChildComponent', value: function computeChildComponent(props) { if (test(props)) { this.LeftComponent = this.LeftComponent || left(BaseComponent); this.Component = this.LeftComponent; } else { this.RightComponent = this.RightComponent || right(BaseComponent); this.Component = this.RightComponent; } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.computeChildComponent(nextProps); } }, { key: 'render', value: function render() { var Component = this.Component; return (0, _createElement2.default)(Component, this.props); } }]); return _class2; }(_react2.default.Component); }; }; exports.default = (0, _createHelper2.default)(branch, 'branch'); /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit = __webpack_require__(6); var _omit2 = _interopRequireDefault(_omit); var _createElement = __webpack_require__(2); var _createElement2 = _interopRequireDefault(_createElement); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var componentFromProp = function componentFromProp(propName) { var Component = function Component(props) { return (0, _createElement2.default)(props[propName], (0, _omit2.default)(props, [propName])); }; Component.displayName = 'componentFromProp(' + propName + ')'; return Component; }; exports.default = componentFromProp; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _flowRight = __webpack_require__(63); var _flowRight2 = _interopRequireDefault(_flowRight); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _flowRight2.default; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); 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; } var createSink = function createSink(callback) { return function (_Component) { _inherits(Sink, _Component); function Sink() { _classCallCheck(this, Sink); return _possibleConstructorReturn(this, Object.getPrototypeOf(Sink).apply(this, arguments)); } _createClass(Sink, [{ key: 'componentWillMount', value: function componentWillMount() { callback(this.props); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { callback(nextProps); } }, { key: 'render', value: function render() { return null; } }]); return Sink; }(_react.Component); }; exports.default = createSink; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultProps = function defaultProps(props) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); var DefaultProps = function DefaultProps(ownerProps) { return createElement(ownerProps); }; DefaultProps.defaultProps = props; return DefaultProps; }; }; exports.default = (0, _createHelper2.default)(defaultProps, 'defaultProps'); /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _omit = __webpack_require__(6); var _omit2 = _interopRequireDefault(_omit); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var flattenProp = function flattenProp(propName) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); return function (props) { return createElement(_extends({}, (0, _omit2.default)(props, [propName]), props[propName])); }; }; }; exports.default = (0, _createHelper2.default)(flattenProp, 'flattenProp'); /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var getContext = function getContext(contextTypes) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); var GetContext = function GetContext(ownerProps, context) { return createElement(_extends({}, ownerProps, context)); }; GetContext.contextTypes = contextTypes; return GetContext; }; }; exports.default = (0, _createHelper2.default)(getContext, 'getContext'); /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _hoistNonReactStatics = __webpack_require__(51); var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var hoistStatics = function hoistStatics(higherOrderComponent) { return function (BaseComponent) { var NewComponent = higherOrderComponent(BaseComponent); (0, _hoistNonReactStatics2.default)(NewComponent, BaseComponent); return NewComponent; }; }; exports.default = hoistStatics; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.hoistStatics = exports.nest = exports.componentFromProp = exports.createSink = exports.isClassComponent = exports.shallowEqual = exports.wrapDisplayName = exports.getDisplayName = exports.compose = exports.setDisplayName = exports.setPropTypes = exports.setStatic = exports.toClass = exports.getContext = exports.withContext = exports.onlyUpdateForPropTypes = exports.onlyUpdateForKeys = exports.pure = exports.shouldUpdate = exports.renderNothing = exports.renderComponent = exports.branch = exports.withReducer = exports.withState = exports.flattenProp = exports.renameProps = exports.renameProp = exports.defaultProps = exports.withHandlers = exports.withPropsOnChange = exports.withProps = exports.mapProps = undefined; var _mapProps2 = __webpack_require__(4); var _mapProps3 = _interopRequireDefault(_mapProps2); var _withProps2 = __webpack_require__(45); var _withProps3 = _interopRequireDefault(_withProps2); var _withPropsOnChange2 = __webpack_require__(46); var _withPropsOnChange3 = _interopRequireDefault(_withPropsOnChange2); var _withHandlers2 = __webpack_require__(44); var _withHandlers3 = _interopRequireDefault(_withHandlers2); var _defaultProps2 = __webpack_require__(27); var _defaultProps3 = _interopRequireDefault(_defaultProps2); var _renameProp2 = __webpack_require__(36); var _renameProp3 = _interopRequireDefault(_renameProp2); var _renameProps2 = __webpack_require__(37); var _renameProps3 = _interopRequireDefault(_renameProps2); var _flattenProp2 = __webpack_require__(28); var _flattenProp3 = _interopRequireDefault(_flattenProp2); var _withState2 = __webpack_require__(48); var _withState3 = _interopRequireDefault(_withState2); var _withReducer2 = __webpack_require__(47); var _withReducer3 = _interopRequireDefault(_withReducer2); var _branch2 = __webpack_require__(23); var _branch3 = _interopRequireDefault(_branch2); var _renderComponent2 = __webpack_require__(38); var _renderComponent3 = _interopRequireDefault(_renderComponent2); var _renderNothing2 = __webpack_require__(39); var _renderNothing3 = _interopRequireDefault(_renderNothing2); var _shouldUpdate2 = __webpack_require__(10); var _shouldUpdate3 = _interopRequireDefault(_shouldUpdate2); var _pure2 = __webpack_require__(35); var _pure3 = _interopRequireDefault(_pure2); var _onlyUpdateForKeys2 = __webpack_require__(16); var _onlyUpdateForKeys3 = _interopRequireDefault(_onlyUpdateForKeys2); var _onlyUpdateForPropTypes2 = __webpack_require__(34); var _onlyUpdateForPropTypes3 = _interopRequireDefault(_onlyUpdateForPropTypes2); var _withContext2 = __webpack_require__(43); var _withContext3 = _interopRequireDefault(_withContext2); var _getContext2 = __webpack_require__(29); var _getContext3 = _interopRequireDefault(_getContext2); var _toClass2 = __webpack_require__(42); var _toClass3 = _interopRequireDefault(_toClass2); var _setStatic2 = __webpack_require__(9); var _setStatic3 = _interopRequireDefault(_setStatic2); var _setPropTypes2 = __webpack_require__(41); var _setPropTypes3 = _interopRequireDefault(_setPropTypes2); var _setDisplayName2 = __webpack_require__(40); var _setDisplayName3 = _interopRequireDefault(_setDisplayName2); var _compose2 = __webpack_require__(25); var _compose3 = _interopRequireDefault(_compose2); var _getDisplayName2 = __webpack_require__(7); var _getDisplayName3 = _interopRequireDefault(_getDisplayName2); var _wrapDisplayName2 = __webpack_require__(49); var _wrapDisplayName3 = _interopRequireDefault(_wrapDisplayName2); var _shallowEqual2 = __webpack_require__(5); var _shallowEqual3 = _interopRequireDefault(_shallowEqual2); var _isClassComponent2 = __webpack_require__(8); var _isClassComponent3 = _interopRequireDefault(_isClassComponent2); var _createSink2 = __webpack_require__(26); var _createSink3 = _interopRequireDefault(_createSink2); var _componentFromProp2 = __webpack_require__(24); var _componentFromProp3 = _interopRequireDefault(_componentFromProp2); var _nest2 = __webpack_require__(33); var _nest3 = _interopRequireDefault(_nest2); var _hoistStatics2 = __webpack_require__(30); var _hoistStatics3 = _interopRequireDefault(_hoistStatics2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.mapProps = _mapProps3.default; // Higher-order component helpers exports.withProps = _withProps3.default; exports.withPropsOnChange = _withPropsOnChange3.default; exports.withHandlers = _withHandlers3.default; exports.defaultProps = _defaultProps3.default; exports.renameProp = _renameProp3.default; exports.renameProps = _renameProps3.default; exports.flattenProp = _flattenProp3.default; exports.withState = _withState3.default; exports.withReducer = _withReducer3.default; exports.branch = _branch3.default; exports.renderComponent = _renderComponent3.default; exports.renderNothing = _renderNothing3.default; exports.shouldUpdate = _shouldUpdate3.default; exports.pure = _pure3.default; exports.onlyUpdateForKeys = _onlyUpdateForKeys3.default; exports.onlyUpdateForPropTypes = _onlyUpdateForPropTypes3.default; exports.withContext = _withContext3.default; exports.getContext = _getContext3.default; exports.toClass = _toClass3.default; // Static property helpers exports.setStatic = _setStatic3.default; exports.setPropTypes = _setPropTypes3.default; exports.setDisplayName = _setDisplayName3.default; // Composition function exports.compose = _compose3.default; // Other utils exports.getDisplayName = _getDisplayName3.default; exports.wrapDisplayName = _wrapDisplayName3.default; exports.shallowEqual = _shallowEqual3.default; exports.isClassComponent = _isClassComponent3.default; exports.createSink = _createSink3.default; exports.componentFromProp = _componentFromProp3.default; exports.nest = _nest3.default; exports.hoistStatics = _hoistStatics3.default; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isClassComponent = __webpack_require__(8); var _isClassComponent2 = _interopRequireDefault(_isClassComponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var isReferentiallyTransparentFunctionComponent = function isReferentiallyTransparentFunctionComponent(Component) { return Boolean(typeof Component === 'function' && !(0, _isClassComponent2.default)(Component) && !Component.defaultProps && !Component.contextTypes && !Component.propTypes); }; exports.default = isReferentiallyTransparentFunctionComponent; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createElement = __webpack_require__(2); function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var nest = function nest() { for (var _len = arguments.length, Components = Array(_len), _key = 0; _key < _len; _key++) { Components[_key] = arguments[_key]; } var createElements = Components.map(_createElement.internalCreateElement); var Nest = function Nest(_ref) { var props = _objectWithoutProperties(_ref, []); var children = _ref.children; return createElements.reduceRight(function (child, createElement) { return createElement(props, child); }, children); }; if (false) { var getDisplayName = require('./getDisplayName').default; var displayNames = Components.map(getDisplayName); Nest.displayName = 'nest(' + displayNames.join(', ') + ')'; } return Nest; }; exports.default = nest; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _onlyUpdateForKeys = __webpack_require__(16); var _onlyUpdateForKeys2 = _interopRequireDefault(_onlyUpdateForKeys); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) { var propTypes = BaseComponent.propTypes; if (false) { var getDisplayName = require('./getDisplayName').default; if (!propTypes) { /* eslint-disable */ console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + ('component with display name "' + getDisplayName(BaseComponent) + '".')); /* eslint-enable */ } } var propKeys = Object.keys(propTypes || {}); var OnlyUpdateForPropTypes = (0, _onlyUpdateForKeys2.default)(propKeys)(BaseComponent); return OnlyUpdateForPropTypes; }; exports.default = (0, _createHelper2.default)(onlyUpdateForPropTypes, 'onlyUpdateForPropTypes', true, true); /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _shouldUpdate = __webpack_require__(10); var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate); var _shallowEqual = __webpack_require__(5); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var pure = (0, _shouldUpdate2.default)(function (props, nextProps) { return !(0, _shallowEqual2.default)(props, nextProps); }); exports.default = (0, _createHelper2.default)(pure, 'pure', true, true); /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _omit = __webpack_require__(6); var _omit2 = _interopRequireDefault(_omit); var _mapProps = __webpack_require__(4); var _mapProps2 = _interopRequireDefault(_mapProps); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var renameProp = function renameProp(oldName, newName) { return (0, _mapProps2.default)(function (props) { return _extends({}, (0, _omit2.default)(props, [oldName]), _defineProperty({}, newName, props[oldName])); }); }; exports.default = (0, _createHelper2.default)(renameProp, 'renameProp'); /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _omit = __webpack_require__(6); var _omit2 = _interopRequireDefault(_omit); var _pick = __webpack_require__(11); var _pick2 = _interopRequireDefault(_pick); var _mapProps = __webpack_require__(4); var _mapProps2 = _interopRequireDefault(_mapProps); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var keys = Object.keys; var mapKeys = function mapKeys(obj, func) { return keys(obj).reduce(function (result, key) { var val = obj[key]; result[func(val, key)] = val; return result; }, {}); }; var renameProps = function renameProps(nameMap) { return (0, _mapProps2.default)(function (props) { return _extends({}, (0, _omit2.default)(props, keys(nameMap)), mapKeys((0, _pick2.default)(props, keys(nameMap)), function (_, oldName) { return nameMap[oldName]; })); }); }; exports.default = (0, _createHelper2.default)(renameProps, 'renameProps'); /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var renderComponent = function renderComponent(Component) { return function (_) { var createElement = (0, _createElement.internalCreateElement)(Component); var RenderComponent = function RenderComponent(props) { return createElement(props); }; if (false) { var wrapDisplayName = require('./wrapDisplayName').default; RenderComponent.displayName = wrapDisplayName(Component, 'renderComponent'); } return RenderComponent; }; }; exports.default = (0, _createHelper2.default)(renderComponent, 'renderComponent', false); /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var renderNothing = function renderNothing(_) { var Nothing = function Nothing() { return null; }; Nothing.displayName = 'Nothing'; return Nothing; }; exports.default = (0, _createHelper2.default)(renderNothing, 'renderNothing', false, true); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _setStatic = __webpack_require__(9); var _setStatic2 = _interopRequireDefault(_setStatic); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var setDisplayName = function setDisplayName(displayName) { return (0, _setStatic2.default)('displayName', displayName); }; exports.default = (0, _createHelper2.default)(setDisplayName, 'setDisplayName', false); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _setStatic = __webpack_require__(9); var _setStatic2 = _interopRequireDefault(_setStatic); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var setPropTypes = function setPropTypes(propTypes) { return (0, _setStatic2.default)('propTypes', propTypes); }; exports.default = (0, _createHelper2.default)(setPropTypes, 'setPropTypes', false); /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _getDisplayName = __webpack_require__(7); var _getDisplayName2 = _interopRequireDefault(_getDisplayName); var _isClassComponent = __webpack_require__(8); var _isClassComponent2 = _interopRequireDefault(_isClassComponent); 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; } var toClass = function toClass(baseComponent) { if ((0, _isClassComponent2.default)(baseComponent)) { return baseComponent; } var ToClass = function (_Component) { _inherits(ToClass, _Component); function ToClass() { _classCallCheck(this, ToClass); return _possibleConstructorReturn(this, Object.getPrototypeOf(ToClass).apply(this, arguments)); } _createClass(ToClass, [{ key: 'render', value: function render() { if (typeof baseComponent === 'string') { return _react2.default.createElement('baseComponent', this.props); } return baseComponent(this.props, this.context); } }]); return ToClass; }(_react.Component); ToClass.displayName = (0, _getDisplayName2.default)(baseComponent); ToClass.propTypes = baseComponent.propTypes; ToClass.contextTypes = baseComponent.contextTypes; ToClass.defaultProps = baseComponent.defaultProps; return ToClass; }; exports.default = toClass; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); 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; } var withContext = function withContext(childContextTypes, getChildContext) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); var WithContext = function (_Component) { _inherits(WithContext, _Component); function WithContext() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, WithContext); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(WithContext)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.getChildContext = function () { return getChildContext(_this.props); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(WithContext, [{ key: 'render', value: function render() { return createElement(this.props); } }]); return WithContext; }(_react.Component); WithContext.childContextTypes = childContextTypes; return WithContext; }; }; exports.default = (0, _createHelper2.default)(withContext, 'withContext'); /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _createElement = __webpack_require__(2); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); 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; } var mapValues = function mapValues(obj, func) { return Object.keys(obj).reduce(function (result, key, i) { result[key] = func(obj[key], key, i); return result; }, {}); }; var withHandlers = function withHandlers(handlers) { return function (BaseComponent) { var _class, _temp2, _initialiseProps; var createElement = (0, _createElement.internalCreateElement)(BaseComponent); return _temp2 = _class = function (_Component) { _inherits(_class, _Component); function _class() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, _class); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(_class)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), _possibleConstructorReturn(_this, _ret); } _createClass(_class, [{ key: 'render', value: function render() { return createElement(_extends({}, this.props, this.handlers)); } }]); return _class; }(_react.Component), _initialiseProps = function _initialiseProps() { var _this2 = this; this.handlers = mapValues(handlers, function (createHandler) { return function () { var handler = createHandler(_this2.props); if (false) { console.error('withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.'); } return handler.apply(undefined, arguments); }; }); }, _temp2; }; }; exports.default = (0, _createHelper2.default)(withHandlers, 'withHandlers'); /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _mapProps = __webpack_require__(4); var _mapProps2 = _interopRequireDefault(_mapProps); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var withProps = function withProps(input) { return (0, _mapProps2.default)(function (props) { return _extends({}, props, typeof input === 'function' ? input(props) : input); }); }; exports.default = (0, _createHelper2.default)(withProps, 'withProps'); /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _pick = __webpack_require__(11); var _pick2 = _interopRequireDefault(_pick); var _shallowEqual = __webpack_require__(5); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); var _createElement2 = _interopRequireDefault(_createElement); 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; } var withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) { return function (BaseComponent) { var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) { return !(0, _shallowEqual2.default)((0, _pick2.default)(props, shouldMapOrKeys), (0, _pick2.default)(nextProps, shouldMapOrKeys)); }; return function (_Component) { _inherits(_class2, _Component); function _class2() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(_class2)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.computedProps = propsMapper(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } _createClass(_class2, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (shouldMap(this.props, nextProps)) { this.computedProps = propsMapper(nextProps); } } }, { key: 'render', value: function render() { return (0, _createElement2.default)(BaseComponent, _extends({}, this.props, this.computedProps)); } }]); return _class2; }(_react.Component); }; }; exports.default = (0, _createHelper2.default)(withPropsOnChange, 'withPropsOnChange'); /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _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; } var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); return function (_Component) { _inherits(_class2, _Component); function _class2() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(_class2)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState }, _this.dispatch = function (action) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: reducer(stateValue, action) }; }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(_class2, [{ key: 'render', value: function render() { var _extends2; return createElement(_extends({}, this.props, (_extends2 = {}, _defineProperty(_extends2, stateName, this.state.stateValue), _defineProperty(_extends2, dispatchName, this.dispatch), _extends2))); } }]); return _class2; }(_react.Component); }; }; exports.default = (0, _createHelper2.default)(withReducer, 'withReducer'); /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _createHelper = __webpack_require__(1); var _createHelper2 = _interopRequireDefault(_createHelper); var _createElement = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _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; } var withState = function withState(stateName, stateUpdaterName, initialState) { return function (BaseComponent) { var createElement = (0, _createElement.internalCreateElement)(BaseComponent); return function (_Component) { _inherits(_class2, _Component); function _class2() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(_class2)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState }, _this.updateStateValue = function (updateFn, callback) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn }; }, callback); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(_class2, [{ key: 'render', value: function render() { var _extends2; return createElement(_extends({}, this.props, (_extends2 = {}, _defineProperty(_extends2, stateName, this.state.stateValue), _defineProperty(_extends2, stateUpdaterName, this.updateStateValue), _extends2))); } }]); return _class2; }(_react.Component); }; }; exports.default = (0, _createHelper2.default)(withState, 'withState'); /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getDisplayName = __webpack_require__(7); var _getDisplayName2 = _interopRequireDefault(_getDisplayName); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) { return hocName + '(' + (0, _getDisplayName2.default)(BaseComponent) + ')'; }; exports.default = wrapDisplayName; /***/ }, /* 50 */ /***/ function(module, exports) { /** * 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. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * 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 */ 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; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 51 */ /***/ function(module, exports) { /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) { var keys = Object.getOwnPropertyNames(sourceComponent); for (var i=0; i<keys.length; ++i) { if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) { } } } return targetComponent; }; /***/ }, /* 52 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { var length = args.length; switch (length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 53 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(53), isFlattenable = __webpack_require__(59); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 55 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 56 */ /***/ function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var LodashWrapper = __webpack_require__(13), baseFlatten = __webpack_require__(54), getData = __webpack_require__(18), getFuncName = __webpack_require__(19), isArray = __webpack_require__(15), isLaziable = __webpack_require__(60), rest = __webpack_require__(68); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to compose bitmasks for wrapper metadata. */ var CURRY_FLAG = 8, PARTIAL_FLAG = 32, ARY_FLAG = 128, REARG_FLAG = 256; /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return rest(function(funcs) { funcs = baseFlatten(funcs, 1); var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } module.exports = createFlow; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(55); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a * [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects * Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var isArguments = __webpack_require__(64), isArray = __webpack_require__(15), isArrayLikeObject = __webpack_require__(20); /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArrayLikeObject(value) && (isArray(value) || isArguments(value)); } module.exports = isFlattenable; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(12), getData = __webpack_require__(18), getFuncName = __webpack_require__(19), lodash = __webpack_require__(70); /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } module.exports = isLaziable; /***/ }, /* 61 */ /***/ function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(12), LodashWrapper = __webpack_require__(13), copyArray = __webpack_require__(56); /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } module.exports = wrapperClone; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var createFlow = __webpack_require__(57); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] Functions to invoke. * @returns {Function} Returns the new function. * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight(square, _.add); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); module.exports = flowRight; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(20); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } module.exports = isArguments; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(58), isFunction = __webpack_require__(66), isLength = __webpack_require__(67); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(getLength(value)) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(21); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /***/ }, /* 67 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, * else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(52), toInteger = __webpack_require__(69); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } switch (start) { case 0: return func.call(this, array); case 1: return func.call(this, args[0], array); case 2: return func.call(this, args[0], args[1], array); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } module.exports = rest; /***/ }, /* 69 */ /***/ function(module, exports) { /** * This method returns the first argument given to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(12), LodashWrapper = __webpack_require__(13), baseLodash = __webpack_require__(14), isArray = __webpack_require__(15), isObjectLike = __webpack_require__(22), wrapperClone = __webpack_require__(62); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array of at least `200` elements * and any iteratees accept only one argument. The heuristic for whether a * section qualifies for shortcut fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `deburr`, `divide`, `each`, * `eachRight`, `endsWith`, `eq`, `escape`, `escapeRegExp`, `every`, `find`, * `findIndex`, `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `first`, * `floor`, `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, * `forOwnRight`, `get`, `gt`, `gte`, `has`, `hasIn`, `head`, `identity`, * `includes`, `indexOf`, `inRange`, `invoke`, `isArguments`, `isArray`, * `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, `isBoolean`, `isBuffer`, * `isDate`, `isElement`, `isEmpty`, `isEqual`, `isEqualWith`, `isError`, * `isFinite`, `isFunction`, `isInteger`, `isLength`, `isMap`, `isMatch`, * `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, `isNumber`, * `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, `isSafeInteger`, * `isSet`, `isString`, `isUndefined`, `isTypedArray`, `isWeakMap`, `isWeakSet`, * `join`, `kebabCase`, `last`, `lastIndexOf`, `lowerCase`, `lowerFirst`, * `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, `min`, `minBy`, `multiply`, * `noConflict`, `noop`, `now`, `nth`, `pad`, `padEnd`, `padStart`, `parseInt`, * `pop`, `random`, `reduce`, `reduceRight`, `repeat`, `result`, `round`, * `runInContext`, `sample`, `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, * `sortedIndexBy`, `sortedLastIndex`, `sortedLastIndexBy`, `startCase`, * `startsWith`, `subtract`, `sum`, `sumBy`, `template`, `times`, `toInteger`, * `toJSON`, `toLength`, `toLower`, `toNumber`, `toSafeInteger`, `toString`, * `toUpper`, `trim`, `trimEnd`, `trimStart`, `truncate`, `unescape`, * `uniqueId`, `upperCase`, `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; module.exports = lodash; /***/ } /******/ ]) }); ;
frontend/components/Shared/Select.js
IGGAMEMAKER/startup-game
import { h, Component } from 'preact'; // import React, { Component, PropTypes } from 'react'; type PropsType = {}; type StateType = {}; type ResponseType = {}; export default class Select extends Component { render() { // props: PropsType, state: StateType const props = this.props; // send info to server, that user pressed the button with some id let { options } = props; const optionList = options.map((o, i) => { return <option value={o.value}>{o.text}</option>; }); const onchange = props.onChange ? (e) => props.onChange(e.target.value) : () => {}; return ( <select value={props.value} onChange={onchange}> {optionList} </select> ); } }
src/components/Loading/Loading.js
labzero/lunch
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Loading.scss'; const Loading = () => ( <div className={s.root}> <div><div /></div> <div><div /></div> <div><div /></div> <div><div /></div> <div><div /></div> </div> ); export default withStyles(s)(Loading);
fields/types/preview/PreviewColumn.js
nickhsine/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; var PreviewColumn = React.createClass({ displayName: 'PreviewColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const previewOrigin = Keystone.previewOrigin || 'https://keystone-preview.twreporter.org' return ( <ItemsTableValue truncate={false} field={this.props.col.type}> <a style={{ textDecoration: 'underline' }} href={`${previewOrigin}/a/${this.props.data.slug}`} target="_blank" >{this.props.col.label}</a> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = PreviewColumn;
node_modules/react-router-dom/node_modules/react-router/es/withRouter.js
amybingzhao/savings-planner-web
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import PropTypes from 'prop-types'; import hoistStatics from 'hoist-non-react-statics'; import Route from './Route'; /** * A public higher-order component to access the imperative API */ var withRouter = function withRouter(Component) { var C = function C(props) { var wrappedComponentRef = props.wrappedComponentRef, remainingProps = _objectWithoutProperties(props, ['wrappedComponentRef']); return React.createElement(Route, { render: function render(routeComponentProps) { return React.createElement(Component, _extends({}, remainingProps, routeComponentProps, { ref: wrappedComponentRef })); } }); }; C.displayName = 'withRouter(' + (Component.displayName || Component.name) + ')'; C.WrappedComponent = Component; C.propTypes = { wrappedComponentRef: PropTypes.func }; return hoistStatics(C, Component); }; export default withRouter;
ajax/libs/6to5/3.1.0/browser-polyfill.js
ErikSchierboom/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(require,module,exports){(function(global){"use strict";if(global._6to5Polyfill){throw new Error("only one instance of 6to5/polyfill is allowed")}global._6to5Polyfill=true;require("core-js/shim");require("regenerator-6to5/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":2,"regenerator-6to5/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},DOT,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);AllSymbols[tag]=true;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(key);return result}})}(safeSymbol("tag"),{},{},true);!function(RegExpProto,isFinite,tmp,NAME){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1},E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames");if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}});if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){var _RegExp=RegExp;RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(RegExp);setSpecies(Array)}(RegExp[PROTOTYPE],isFinite,{},"name");isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&&notify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){return iter.o=undefined,iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;entry.p=entry.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&DESC&&new WeakMap([[Object.freeze(tmp),7]]).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result }return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList);!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({})}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]);
src/main.js
georgezee/cabango
console.log('Cabango loaded.'); import React from 'react'; import ReactDOM from 'react-dom'; import App from './containers/App'; document.addEventListener('DOMContentLoaded', function() { ReactDOM.render( <App/>, document.getElementById('root') ); });
src/components/Popups/Login/index.js
nahkar/react_cms
import React, { Component } from 'react'; export default class LoginPopup extends Component { render() { return ( <div className="login-popup popup"> <form> <h3>Login form</h3> <div className="row"> <input type='text' placeholder='Login' /> </div> <div className="row"> <input type='text' placeholder='Password' /> </div> <div className="row"> <button type="button" className="btn btn-default">Send</button> </div> </form> </div> ); } }
src/aria/widgets/form/MultiSelect.js
fbasso/ariatemplates
/* * Copyright 2012 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Aria = require("../../Aria"); var ariaWidgetsFormListList = require("./list/List"); var ariaWidgetsControllersMultiSelectController = require("../controllers/MultiSelectController"); var ariaDomEvent = require("../../DomEvent"); var ariaWidgetsFormMultiSelectStyle = require("./MultiSelectStyle.tpl.css"); var ariaWidgetsFormListListStyle = require("./list/ListStyle.tpl.css"); var ariaWidgetsContainerDivStyle = require("../container/DivStyle.tpl.css"); var ariaWidgetsFormCheckBoxStyle = require("./CheckBoxStyle.tpl.css"); var ariaWidgetsFormDropDownTextInput = require("./DropDownTextInput"); var DomNavigationManager = require("../../utils/DomNavigationManager"); /** * Multi-select widget which is a list of checkboxes and labels passed in an array of predefined values * @extends aria.widgets.form.DropDownTextInput * @class aria.widgets.form.MultiSelect */ module.exports = Aria.classDefinition({ $classpath : "aria.widgets.form.MultiSelect", $extends : ariaWidgetsFormDropDownTextInput, $css : [ariaWidgetsFormMultiSelectStyle, ariaWidgetsFormListListStyle, ariaWidgetsContainerDivStyle, ariaWidgetsFormCheckBoxStyle], $constructor : function (cfg, ctxt, lineNumber) { var controller = new ariaWidgetsControllersMultiSelectController(); // The following line was added for PTR 04557432: if the value in cfg is not set to [] as a default, then the // handle specified as the onchange configuration property will be executed also on the first click cfg.value = cfg.value || []; this.$DropDownTextInput.constructor.call(this, cfg, ctxt, lineNumber, controller); // set control options controller.setListOptions(cfg.items); controller.setSeparator(cfg.fieldSeparator); controller.setMaxOptions(cfg.maxOptions); controller.setFieldDisplay(cfg.fieldDisplay); controller.setValueDisplay(cfg.valueDisplay); controller.checkError(); /** * Whether to update the data model instantly when the user checks/unchecks the checkboxes, or only when the * dropdown list is closed * @protected * @type Boolean */ this._instantBind = (cfg.instantBind === true); /** * Flag whether the drop down is open * @protected * @type Boolean */ this._dropDownOpen = false; /** * Flag whether template of template based widget has been intialised * @public * @type String */ this.refreshPopup = false; /** * Whether the list is focuses * @protected * @type String */ this._listFocused = false; /** * List widget associated with the multiselect * @protected * @type aria.widgets.form.list.List */ this._dropDownList = null; }, $destructor : function () { this._dropDownOpen = null; this.refreshPopup = null; this._listFocused = null; this.$DropDownTextInput.$destructor.call(this); this._dropDownList = null; }, $prototype : { /** * Skinnable class to use for this widget. * @protected * @type String */ _skinnableClass : "MultiSelect", /** * Callback called when the user clicks on a checkbox (or its label) on a dropdown list. * @protected * @param {Array} newVals array of values that will be selected after the change */ _clickOnItem : function (newVals) { // when clicking on an item in the dropdown list, close the dropdown and save the selected item var report = this.controller.checkValue(this.controller.getDataModel().value); var arg = { stopValueProp : !this._instantBind }; this._reactToControllerReport(report, arg); if (this._instantBind && this._dropdownPopup) { this._dropdownPopup.updatePosition(); } }, /** * Checks if the currently focused item has the power to close the popup. * @return {Boolean} */ _checkCloseItem : function (evt) { return evt.focusIndex === evt.closeItem.id; }, /** * Handle key event not handled by the list, in this case arrow up to close the dropdown * * @protected * * @param {Object} information Information about the key event. * * @return {Boolean} */ _keyPressed : function (information) { var event = information.event; var keyCode = event.keyCode; if (this._isShiftF10Pressed(event) || (keyCode == ariaDomEvent.KC_ARROW_UP && this._checkCloseItem(information))) { this.focus(); this._toggleDropdown(); return true; } if (keyCode == ariaDomEvent.KC_ESCAPE) { if (this._dropDownOpen) { this._toggleDropdown(); return true; } } if (keyCode == ariaDomEvent.KC_TAB) { return true; } return false; }, /** * Internal method called when the popup should be either closed or opened depending on the state of the * controller and whether it is currently opened or closed. In any case, keep the focus on the field. Called by * the widget button for example. * @protected */ _toggleDropdown : function () { this._updateFocusNoKeyboard(true); if (!this._hasFocus) { this.focus(null, true); } this._keepFocus = false; var report = this.controller.toggleDropdown(this.getTextInputField().value, this._dropdownPopup != null); this._reactToControllerReport(report, { hasFocus : true }); }, /** * Internal function to render the content of the dropdown div * @param {aria.templates.MarkupWriter} out Markup writer which should receive the content of the popup. */ _renderDropdownContent : function (out) { var cfg = this._cfg; var dm = this.controller.getDataModel(); var list = new ariaWidgetsFormListList({ defaultTemplate : cfg.listTemplate, waiAria : cfg.waiAria, tabIndex : -1, block : true, sclass : cfg.listSclass || this._skinObj.listSclass, onchange : { fn : this._clickOnItem, scope : this }, onkeyevent : { fn : this._keyPressed, scope : this }, onclose : { fn : this._toggleDropdown, scope : this }, minWidth : this._inputMarkupWidth + this._skinObj.offsetRight, width : (cfg.popupWidth > 0 && cfg.popupWidth > this._inputMarkupWidth) ? cfg.popupWidth : null, multipleSelect : true, maxHeight : 250, activateSort : cfg.activateSort, maxOptions : cfg.maxOptions, bind : { items : { to : "listContent", inside : dm }, selectedIndex : { to : "selectedIdx", inside : dm }, selectedValues : { to : "selectedValues", inside : dm } }, numberOfColumns : cfg.numberOfColumns, numberOfRows : cfg.numberOfRows, displayOptions : cfg.displayOptions }, this._context, this._lineNumber); out.registerBehavior(list); list.writeMarkup(out); this.controller.setListWidget(list); list.$on({ 'widgetContentReady' : { fn : this._refreshPopup, scope : this, args : { list : list } } }); this._dropDownList = list; }, /** * Called when the dropdown is closed * @protected */ _afterDropdownClose : function () { this.navigationInterceptor.destroyElements(); this.navigationInterceptor = null; if (this._cfg.waiAria) { var dropDownIcon = this._getDropdownIcon(); if (dropDownIcon) { dropDownIcon.setAttribute("aria-expanded", "false"); } } this._setPopupOpenProperty(false); this.controller.setListWidget(null); var report = null; // Check _toggleDropdown already triggered if (!this._hasFocus) { // Added to keep the behaviour similar to click on close button click PTR 04661445 report = this.controller.toggleDropdown(this.getTextInputField().value, this._dropdownPopup != null); // to reset the dropdown display report.displayDropDown = false; } this.$DropDownTextInput._afterDropdownClose.call(this); if (report) { this._reactToControllerReport(report, { hasFocus : false }); // note that _reactToControllerReport might destroy the widget (this._cfg may be null here) } this._dropDownOpen = false; this.refreshPopup = false; this._keepFocus = false; }, /** * This method focuses the list if the dropdown is open and the popup has been refreshed This is necessary * because this can happen in either order * @protected * @param {aria.widgets.form.List} list */ _focusMultiSelect : function (list) { if (this._dropDownOpen && this.refreshPopup) { list.focus(); } }, /** * Called after the popup has opened * @protected */ _afterDropdownOpen : function () { var waiAria = this._cfg.waiAria; this.navigationInterceptor = DomNavigationManager.ModalNavigationHandler(this._dropdownPopup.domElement, !waiAria); this.navigationInterceptor.ensureElements(); this._setPopupOpenProperty(true); // when the popup is clicked, don't give it focus, allow focus to be passed to the List in _refreshPopup this._keepFocus = true; var list = this.controller.getListWidget(); this._dropDownOpen = true; this._focusMultiSelect(list); if (waiAria) { var dropDownIcon = this._getDropdownIcon(); if (dropDownIcon) { dropDownIcon.setAttribute("aria-expanded", "true"); } } }, /** * This is called when the template content is displayed for a template based widget * @param {aria.DomEvent} evt Click event * @param {Object} args Arguments that are passed to this callback */ _refreshPopup : function (evt, args) { if (this._dropdownPopup) { this.refreshPopup = true; this._dropdownPopup.refresh(); } this._focusMultiSelect(args.list); }, /** * Override $DropDownTextInput._reactToControllerReport * @protected * @param {aria.widgets.controllers.reports.DropDownControllerReport} report * @param {Object} arg Optional parameters */ _reactToControllerReport : function (report, arg) { this.$DropDownTextInput._reactToControllerReport.call(this, report, arg); }, /** * Called then the list is ready * @protected * @param {Object} args */ _widgetContentReady : function (args) { // focus the list when popup is opened this._refreshPopup(args); this._dropDownList.focus(); }, /** * DOM Event raised when the focus is given to the datepicker. */ _dom_onfocus : function (event, avoidCallback) { this._iconFocus = event.target == this._getDropdownIcon(); this.$DropDownTextInput._dom_onfocus.apply(this, arguments); }, /** * Set the caret position in the field * @param {Number} start * @param {Number} end */ setCaretPosition : function (start, end) { if (this._iconFocus) { this._currentCaretPosition = { start : start, end : end }; } else { return this.$DropDownTextInput.setCaretPosition.apply(this, arguments); } }, /** * Returns whether the text input is read-only. * @return {Boolean} true if the text input should be read-only. * @override */ isTextInputReadOnly : function () { return this._cfg.readOnlyTextField || this.$DropDownTextInput.isTextInputReadOnly.call(this); }, /** * Return the caret position in the DatePicker. It works also if the focus is on the expand icon. * @return {Object} the caret position (start end end) */ getCaretPosition : function () { if (this._iconFocus) { var currentCaretPosition = this._currentCaretPosition; if (currentCaretPosition) { return currentCaretPosition; } return { start : 0, end : 0 }; } else { return this.$DropDownTextInput.getCaretPosition.apply(this, arguments); } } } });
src/pages/music/Music.js
hinzed1127/fayraysite
import React from 'react'; import './music.css'; import singleArt from '../../img/ep/ep_art.jpg'; import {LINKS} from '../../constants/Links'; export default function Music() { return ( <div className='music-wrapper'> <div className='music-container'> <div> <img className='ep-art' src={singleArt} alt='Artwork for the Single "Stuck"' /> </div> <div className='links-and-content'> <p className='description'> <i>No Love EP</i> <br></br> Released October 2017 </p> <div className='links'> <div> <div className='no-love-link-button'> <a href={LINKS.BANDCAMP}>Bandcamp</a> </div> <div className='no-love-link-button'> <a href={LINKS.SPOTIFY}>Spotify</a> </div> </div> <div> <div className='no-love-link-button'> <a href={LINKS.ITUNES}>iTunes</a> </div> <div className='no-love-link-button'> <a href={LINKS.SOUNDCLOUD}>SoundCloud</a> </div> </div> </div> </div> </div> </div> ); }
src/svg-icons/device/signal-wifi-1-bar.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/><path d="M6.67 14.86L12 21.49v.01l.01-.01 5.33-6.63C17.06 14.65 15.03 13 12 13s-5.06 1.65-5.33 1.86z"/> </SvgIcon> ); DeviceSignalWifi1Bar = pure(DeviceSignalWifi1Bar); DeviceSignalWifi1Bar.displayName = 'DeviceSignalWifi1Bar'; DeviceSignalWifi1Bar.muiName = 'SvgIcon'; export default DeviceSignalWifi1Bar;
examples/redirect-using-index/app.js
MattSPalmer/react-router
import React from 'react'; import { Router, Route, IndexRoute, Link } from 'react-router'; var App = React.createClass({ render() { return ( <div> {this.props.children} </div> ); } }); var Index = React.createClass({ render () { return ( <div> <h1>You should not see this.</h1> {this.props.children} </div> ) } }); var Child = React.createClass({ render () { return ( <div> <h2>Redirected to "/child"</h2> <Link to="/">Try going to "/"</Link> </div> ) } }); function redirectToChild(location, replaceWith) { replaceWith(null, '/child'); } React.render(( <Router> <Route path="/" component={App}> <IndexRoute component={Index} onEnter={redirectToChild}/> <Route path="/child" component={Child}/> </Route> </Router> ), document.getElementById('example'));
components/scenes/street.js
dbow/89-steps
import React from 'react'; class Street extends React.Component { render() { return ( <div> <h2>The Street</h2> <p>This will be good!!</p> </div> ); } } export default Street;
ajax/libs/forerunnerdb/1.3.363/fdb-core.min.js
pombredanne/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/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Shim.IE8":27}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),!0}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,e){e=e||[],this._left&&this._left.findRange(a,b,c,d,e);var f=this.sortAsc(this._data[b],c),g=this.sortAsc(this._data[b],d);if(!(0!==f&&1!==f||0!==g&&-1!==g))switch(a){case"hash":e.push(this._hash);break;case"data":e.push(this._data);break;default:e.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,e),e},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._index),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}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":23,"./Shared":26}],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,b){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._options=b||{changeTimestamp:!1},this._metaData={},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"),d.mixin(n.prototype,"Mixin.Tags"),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"),d.synthesize(n.prototype,"metaData"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;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],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)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" 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._onChange(),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 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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(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(this.isDropped())throw this.logIdentifier()+" 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._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" 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(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};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._onChange(),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 this.logIdentifier()+" 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":case"$min":case"$max":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],d,"",{})&&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":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(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 this.logIdentifier()+" 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 this.logIdentifier()+" 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],d,"",{})&&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 this.logIdentifier()+" 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 this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(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 this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" 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 this.logIdentifier()+" 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],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),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 this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[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(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),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._onChange(),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.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" 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,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},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=this.jStringify(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=this.jStringify(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._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" 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=this.jStringify(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,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" 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,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.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(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=m[n].query),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g=this;if("string"==typeof a)return"$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b)[0]:new h(a).value(b)[0];c={};for(f in a)if(a.hasOwnProperty(f))switch(d=typeof a[f],e=a[f],d){case"string":"$$."===e.substr(0,3)?c[f]=new h(e.substr(3,e.length-3)).value(b)[0]:c[f]=e;break;case"object":c[f]=g._resolveDynamicQuery(e,b);break;default:c[f]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},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=String(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,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,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 this.logIdentifier()+" $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,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},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),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(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(d=d||{},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];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},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(this.isDropped())throw this.logIdentifier()+" 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 this.logIdentifier()+" 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({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):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 this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.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()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.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=i},{"./Db.js":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[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}},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),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"),d.synthesize(j.prototype,"mongoEmulation"),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="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},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="string"===e?d.concat(c.peek(a)):d.concat(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(!this.isDropped()){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(!this.isDropped()){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(!this.isDropped()){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(!this.isDropped()){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 instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),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},d.finishModule("Db"),b.exports=j},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.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",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.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(h.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}},i.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++},i.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--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.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}},i.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},i.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},i.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=i},{"./BinaryTree":2,"./Path":23,"./Shared":26}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},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":26}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":26}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":21,"./Shared":26}],11:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],12:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),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||d.isDropped()))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!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],13:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,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]}},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=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},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}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":22,"./Serialiser":25}],14:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],15:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),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,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":22}],16:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)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],c,l,e));h++);if(g){if("or"===d)return!0}else o=!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],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)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],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){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"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(c)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d=this.tagLookup(a);if(d.length)for(c=0;c<d.length;c++)d[c]===this&&d.drop(b);return!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(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"'); },_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(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_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,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};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":26}],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,g=[];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++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}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.Common"),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 b?f.push({path:g,value:a[d]}):f.push({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.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.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":26}],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 this.isDropped()||(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.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":26}],25:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.363",modules:{},plugins:{},_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.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,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:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),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:d,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"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]);
ajax/libs/yui/3.5.1/event-custom-base/event-custom-base-debug.js
sjlu/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']});
packages/material-ui-icons/src/GradientSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M11 9h2v2h-2V9zm-2 2h2v2H9v-2zm4 0h2v2h-2v-2zm2-2h2v2h-2V9zM7 9h2v2H7V9zm14-6H3v18h18V3zM9 18H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm2-7h-2v2h2v2h-2v-2h-2v2h-2v-2h-2v2H9v-2H7v2H5v-2h2v-2H5V5h14v6z" /> , 'GradientSharp');
node_modules/antd/es/checkbox/Checkbox.js
prodigalyijun/demo-by-antd
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import RcCheckbox from 'rc-checkbox'; import shallowEqual from 'shallowequal'; var Checkbox = function (_React$Component) { _inherits(Checkbox, _React$Component); function Checkbox() { _classCallCheck(this, Checkbox); return _possibleConstructorReturn(this, (Checkbox.__proto__ || Object.getPrototypeOf(Checkbox)).apply(this, arguments)); } _createClass(Checkbox, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState, nextContext) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState) || !shallowEqual(this.context.checkboxGroup, nextContext.checkboxGroup); } }, { key: 'render', value: function render() { var props = this.props, context = this.context; var prefixCls = props.prefixCls, className = props.className, children = props.children, indeterminate = props.indeterminate, style = props.style, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, restProps = __rest(props, ["prefixCls", "className", "children", "indeterminate", "style", "onMouseEnter", "onMouseLeave"]); var checkboxGroup = context.checkboxGroup; var checkboxProps = Object.assign({}, restProps); if (checkboxGroup) { checkboxProps.onChange = function () { return checkboxGroup.toggleOption({ label: children, value: props.value }); }; checkboxProps.checked = checkboxGroup.value.indexOf(props.value) !== -1; checkboxProps.disabled = 'disabled' in props ? props.disabled : checkboxGroup.disabled; } var classString = classNames(className, _defineProperty({}, prefixCls + '-wrapper', true)); var checkboxClass = classNames(_defineProperty({}, prefixCls + '-indeterminate', indeterminate)); return React.createElement( 'label', { className: classString, style: style, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave }, React.createElement(RcCheckbox, _extends({}, checkboxProps, { prefixCls: prefixCls, className: checkboxClass })), children !== undefined ? React.createElement( 'span', null, children ) : null ); } }]); return Checkbox; }(React.Component); export default Checkbox; Checkbox.defaultProps = { prefixCls: 'ant-checkbox', indeterminate: false }; Checkbox.contextTypes = { checkboxGroup: PropTypes.any };
RNTester/js/ViewExample.js
shrutic123/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule ViewExample */ 'use strict'; var React = require('react'); var ReactNative = require('react-native'); var { StyleSheet, Text, View, } = ReactNative; var TouchableWithoutFeedback = require('TouchableWithoutFeedback'); var styles = StyleSheet.create({ box: { backgroundColor: '#527FE4', borderColor: '#000033', borderWidth: 1, }, zIndex: { justifyContent: 'space-around', width: 100, height: 50, marginTop: -10, }, }); class ViewBorderStyleExample extends React.Component { state = { showBorder: true }; render() { return ( <TouchableWithoutFeedback onPress={this._handlePress}> <View> <View style={{ borderWidth: 1, borderStyle: this.state.showBorder ? 'dashed' : null, padding: 5 }}> <Text style={{fontSize: 11}}> Dashed border style </Text> </View> <View style={{ marginTop: 5, borderWidth: 1, borderRadius: 5, borderStyle: this.state.showBorder ? 'dotted' : null, padding: 5 }}> <Text style={{fontSize: 11}}> Dotted border style </Text> </View> </View> </TouchableWithoutFeedback> ); } _handlePress = () => { this.setState({showBorder: !this.state.showBorder}); }; } class ZIndexExample extends React.Component { state = { flipped: false }; render() { const indices = this.state.flipped ? [-1, 0, 1, 2] : [2, 1, 0, -1]; return ( <TouchableWithoutFeedback onPress={this._handlePress}> <View> <Text style={{paddingBottom: 10}}>Tap to flip sorting order</Text> <View style={[ styles.zIndex, {marginTop: 0, backgroundColor: '#E57373', zIndex: indices[0]} ]}> <Text>ZIndex {indices[0]}</Text> </View> <View style={[ styles.zIndex, {marginLeft: 50, backgroundColor: '#FFF176', zIndex: indices[1]} ]}> <Text>ZIndex {indices[1]}</Text> </View> <View style={[ styles.zIndex, {marginLeft: 100, backgroundColor: '#81C784', zIndex: indices[2]} ]}> <Text>ZIndex {indices[2]}</Text> </View> <View style={[ styles.zIndex, {marginLeft: 150, backgroundColor: '#64B5F6', zIndex: indices[3]} ]}> <Text>ZIndex {indices[3]}</Text> </View> </View> </TouchableWithoutFeedback> ); } _handlePress = () => { this.setState({flipped: !this.state.flipped}); }; } exports.title = '<View>'; exports.description = 'Basic building block of all UI, examples that ' + 'demonstrate some of the many styles available.'; exports.displayName = 'ViewExample'; exports.examples = [ { title: 'Background Color', render: function() { return ( <View style={{backgroundColor: '#527FE4', padding: 5}}> <Text style={{fontSize: 11}}> Blue background </Text> </View> ); }, }, { title: 'Border', render: function() { return ( <View style={{borderColor: '#527FE4', borderWidth: 5, padding: 10}}> <Text style={{fontSize: 11}}>5px blue border</Text> </View> ); }, }, { title: 'Padding/Margin', render: function() { return ( <View style={{borderColor: '#bb0000', borderWidth: 0.5}}> <View style={[styles.box, {padding: 5}]}> <Text style={{fontSize: 11}}>5px padding</Text> </View> <View style={[styles.box, {margin: 5}]}> <Text style={{fontSize: 11}}>5px margin</Text> </View> <View style={[styles.box, {margin: 5, padding: 5, alignSelf: 'flex-start'}]}> <Text style={{fontSize: 11}}> 5px margin and padding, </Text> <Text style={{fontSize: 11}}> widthAutonomous=true </Text> </View> </View> ); }, }, { title: 'Border Radius', render: function() { return ( <View style={{borderWidth: 0.5, borderRadius: 5, padding: 5}}> <Text style={{fontSize: 11}}> Too much use of `borderRadius` (especially large radii) on anything which is scrolling may result in dropped frames. Use sparingly. </Text> </View> ); }, }, { title: 'Border Style', render: function() { return <ViewBorderStyleExample />; }, }, { title: 'Circle with Border Radius', render: function() { return ( <View style={{borderRadius: 10, borderWidth: 1, width: 20, height: 20}} /> ); }, }, { title: 'Overflow', render: function() { return ( <View style={{flexDirection: 'row'}}> <View style={{ width: 95, height: 10, marginRight: 10, marginBottom: 5, overflow: 'hidden', borderWidth: 0.5, }}> <View style={{width: 200, height: 20}}> <Text>Overflow hidden</Text> </View> </View> <View style={{width: 95, height: 10, marginBottom: 5, borderWidth: 0.5}}> <View style={{width: 200, height: 20}}> <Text>Overflow visible</Text> </View> </View> </View> ); }, }, { title: 'Opacity', render: function() { return ( <View> <View style={{opacity: 0}}><Text>Opacity 0</Text></View> <View style={{opacity: 0.1}}><Text>Opacity 0.1</Text></View> <View style={{opacity: 0.3}}><Text>Opacity 0.3</Text></View> <View style={{opacity: 0.5}}><Text>Opacity 0.5</Text></View> <View style={{opacity: 0.7}}><Text>Opacity 0.7</Text></View> <View style={{opacity: 0.9}}><Text>Opacity 0.9</Text></View> <View style={{opacity: 1}}><Text>Opacity 1</Text></View> </View> ); }, }, { title: 'ZIndex', render: function() { return <ZIndexExample />; }, }, ];
webpack.config.js
aldendaniels/react-router
var webpack = require('webpack'); var plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }) ]; if (process.env.COMPRESS) { plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ); } module.exports = { output: { library: 'ReactRouter', libraryTarget: 'var' }, externals: { react: 'React' }, node: { Buffer: false }, plugins: plugins };
clientSide/resources/js/lib/jquery/jquery-1.10.2.min.js
wallet77/tinydailytaskmanager
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;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 x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.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(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.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?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},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||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.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||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},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:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.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 d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},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}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(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]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?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},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.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},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-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 S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(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?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.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+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===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]||at.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]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.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,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!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[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[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]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[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[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(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:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("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===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.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!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.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:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(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 xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.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?x.extend(e,r):r}},i={};return r.pipe=r.then,x.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=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.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],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.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;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[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%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.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&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),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 x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.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=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.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,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._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(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t: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,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.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 t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={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}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[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),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=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));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,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]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),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=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),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=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=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 x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):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,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.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))},x.Event=function(e,n){return this instanceof x.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&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.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()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._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 x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.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 x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.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,x(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(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.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?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(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(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.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,Ct=/^(?:checkbox|radio)$/i,Nt=/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:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.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 x.clone(this,e,t)})},html:function(e){return x.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)||!x.support.htmlSerialize&&mt.test(e)||!x.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&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._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++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.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)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(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||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.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),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(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,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(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 x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});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("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","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"===x.css(e,"display")||!x.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]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.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}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.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,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],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||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});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+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.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=x.support.boxSizing&&"border-box"===x.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&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<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=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.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,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.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=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.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)||(x.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;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.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(x.isArray(t))x.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"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},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)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.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(T)||[];if(x.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(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.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",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.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,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){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===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.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=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],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=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.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&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.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)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.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 Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=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 l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.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,Fn.push(o)),s&&x.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){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.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,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.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,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.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||(x.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?x.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=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.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)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.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=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._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=x.timers,a=x._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)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),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}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.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,x.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},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.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?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.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?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
packages/material-ui-icons/src/Replay30Sharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z" /><path d="M9.56 13.49h.45c.21 0 .37-.05.48-.16s.16-.25.16-.43c0-.08-.01-.15-.04-.22s-.06-.12-.11-.17-.11-.09-.18-.11-.16-.04-.25-.04c-.08 0-.15.01-.22.03s-.13.05-.18.1-.09.09-.12.15-.05.13-.05.2h-.85c0-.18.04-.34.11-.48s.17-.27.3-.37.27-.18.44-.23.35-.08.54-.08c.21 0 .41.03.59.08s.33.13.46.23.23.23.3.38.11.33.11.53c0 .09-.01.18-.04.27s-.07.17-.13.25-.12.15-.2.22-.17.12-.28.17c.24.09.42.21.54.39s.18.38.18.61c0 .2-.04.38-.12.53s-.18.29-.32.39-.29.19-.48.24-.38.08-.6.08c-.18 0-.36-.02-.53-.07s-.33-.12-.46-.23-.25-.23-.33-.38-.12-.34-.12-.55h.85c0 .08.02.15.05.22s.07.12.13.17.12.09.2.11.16.04.25.04c.1 0 .19-.01.27-.04s.15-.07.2-.12.1-.11.13-.18.04-.15.04-.24c0-.11-.02-.21-.05-.29s-.08-.15-.14-.2-.13-.09-.22-.11-.18-.04-.29-.04h-.47v-.65zM15.3 14.24c0 .32-.03.6-.1.82s-.17.42-.29.57-.28.26-.45.33-.37.1-.59.1-.41-.03-.59-.1-.33-.18-.46-.33-.23-.34-.3-.57-.11-.5-.11-.82v-.74c0-.32.03-.6.1-.82s.17-.42.29-.57.28-.26.45-.33.37-.1.59-.1.41.03.59.1.33.18.46.33.23.34.3.57.11.5.11.82v.74zm-.85-.86c0-.19-.01-.35-.04-.48s-.07-.23-.12-.31-.11-.14-.19-.17-.16-.05-.25-.05-.18.02-.25.05-.14.09-.19.17-.09.18-.12.31-.04.29-.04.48v.97c0 .19.01.35.04.48s.07.24.12.32.11.14.19.17.16.05.25.05.18-.02.25-.05.14-.09.19-.17.09-.19.11-.32c.03-.13.04-.29.04-.48v-.97z" /></React.Fragment> , 'Replay30Sharp');
frontend/app/js/components/genericform/htmlfield.js
serverboards/serverboards
import React from 'react' import plugin from 'app/utils/plugin' import i18n from 'app/utils/i18n' import Flash from 'app/flash' import {MarkdownPreview} from 'react-marked-markdown' class HTMLField extends React.Component { constructor(props){ super(props) this.state = { loading: true, html: "", id: Math.random().toString(36).substring(7), } } componentDidMount(){ const plugin_id = this.props.form_data.service.type.split('/')[0] let tasks if (this.props.js) tasks = plugin.load(`${plugin_id}/${this.props.js}`) else tasks = Promise.resolved("") tasks .then(() => plugin.load(`${plugin_id}/${this.props.html}`)) .then(html => html.replace(/{{field_name}}/g, this.state.id)) .then(html => { this.setState({html, loading: false}) if (this.refs.me) this.refs.me.innerHTML = html; }) .catch( e => { console.error(e) Flash.error(e) }) } componentDidUpdate(){ if (this.refs.me && this.refs.me.innerHTML == "") this.refs.me.innerHTML = this.state.html; } render(){ const props = this.props const state = this.state return ( <div className={`field ${props.className || ""}`}> <label>{i18n(props.label)}</label> <div> <MarkdownPreview className={`ui meta ${props.extraClass}`} value={props.description}/> {state.loading ? ( <div><i className="ui loading notched circle icon"/></div> ) : ( <div ref="me"></div> )} <input type="text" style={{display: "none"}} name={state.id} id={state.id} onChange={(ev) => {console.log("Change", ev); props.onChange(ev)}}/> </div> </div> ) } } export default HTMLField
ajax/libs/angular-google-maps/1.0.9/angular-google-maps.js
samthor/cdnjs
/* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ (function() { _.intersectionObjects = function(array1, array2, comparison) { var res, _this = this; if (comparison == null) { comparison = void 0; } res = _.map(array1, function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }); return _.filter(res, function(o) { return o != null; }); }; }).call(this); /* ! 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/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { (function() { var app; app = angular.module("google-maps", []); return app.factory("debounce", [ "$timeout", function($timeout) { return function(fn) { var nthCall; nthCall = 0; return function() { var argz, later, that; that = this; argz = arguments; nthCall++; later = (function(version) { return function() { if (version === nthCall) { return fn.apply(that, argz); } }; })(nthCall); return $timeout(later, 0, true); }; }; } ]); })(); }).call(this); (function() { this.ngGmapModule = function(names, fn) { var space, _name; if (fn == null) { fn = function() {}; } if (typeof names === 'string') { names = names.split('.'); } space = this[_name = names.shift()] || (this[_name] = {}); space.ngGmapModule || (space.ngGmapModule = this.ngGmapModule); if (names.length) { return space.ngGmapModule(names, fn); } else { return fn.call(space); } }; }).call(this); (function() { angular.module("google-maps").factory("array-sync", [ "add-events", function(mapEvents) { var LatLngArraySync; return LatLngArraySync = function(mapArray, scope, pathEval) { var mapArrayListener, scopeArray, watchListener; scopeArray = scope.$eval(pathEval); mapArrayListener = mapEvents(mapArray, { set_at: function(index) { var value; value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scopeArray[index].latitude = value.lat(); return scopeArray[index].longitude = value.lng(); }, insert_at: function(index) { var value; value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return scopeArray.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); }, remove_at: function(index) { return scopeArray.splice(index, 1); } }); watchListener = scope.$watch(pathEval, function(newArray) { var i, l, newLength, newValue, oldArray, oldLength, oldValue, _results; oldArray = mapArray; if (newArray) { i = 0; oldLength = oldArray.getLength(); newLength = newArray.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newArray[i]; if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); } i++; } while (i < newLength) { newValue = newArray[i]; oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); i++; } _results = []; while (i < oldLength) { oldArray.pop(); _results.push(i++); } return _results; } }, true); return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); (function() { angular.module("google-maps").factory("add-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(fn) { if (_.isFunction(fn)) { fn(); } if (fn.e !== null && _.isFunction(fn.e)) { return fn.e(); } }); return remove = null; }; }; return addEvents; } ]); }).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; }; this.ngGmapModule("oo", function() { var baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; return this.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(0); } 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(0); } return this; }; return 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; }; this.ngGmapModule("directives.api.managers", function() { return this.ClustererMarkerManager = (function(_super) { __extends(ClustererMarkerManager, _super); function ClustererMarkerManager(gMap, opt_markers, opt_options) { 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.add = __bind(this.add, this); var self; ClustererMarkerManager.__super__.constructor.call(this); self = this; this.opt_options = opt_options; if ((opt_options != null) && opt_markers === void 0) { this.clusterer = new MarkerClusterer(gMap, void 0, opt_options); } else if ((opt_options != null) && (opt_markers != null)) { this.clusterer = new MarkerClusterer(gMap, opt_markers, opt_options); } else { this.clusterer = new MarkerClusterer(gMap); } this.clusterer.setIgnoreHidden(true); this.$log = directives.api.utils.Logger; this.noDrawOnSingleAddRemoves = true; this.$log.info(this); } ClustererMarkerManager.prototype.add = function(gMarker) { return this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return this.clusterer.addMarkers(gMarkers); }; ClustererMarkerManager.prototype.remove = function(gMarker) { return this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return this.clusterer.addMarkers(gMarkers); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.clusterer.clearMarkers(); return this.clusterer.repaint(); }; return ClustererMarkerManager; })(oo.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; }; this.ngGmapModule("directives.api.managers", function() { return this.MarkerManager = (function(_super) { __extends(MarkerManager, _super); function MarkerManager(gMap, opt_markers, opt_options) { 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.add = __bind(this.add, this); var self; MarkerManager.__super__.constructor.call(this); self = this; this.gMap = gMap; this.gMarkers = []; this.$log = directives.api.utils.Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.push(gMarker); }; MarkerManager.prototype.addMany = function(gMarkers) { var gMarker, _i, _len, _results; _results = []; for (_i = 0, _len = gMarkers.length; _i < _len; _i++) { gMarker = gMarkers[_i]; _results.push(this.add(gMarker)); } return _results; }; MarkerManager.prototype.remove = function(gMarker, optDraw) { var index, tempIndex; this.handleOptDraw(gMarker, optDraw, false); if (!optDraw) { return; } index = void 0; if (this.gMarkers.indexOf != null) { index = this.gMarkers.indexOf(gMarker); } else { tempIndex = 0; _.find(this.gMarkers, function(marker) { tempIndex += 1; if (marker === gMarker) { index = tempIndex; } }); } if (index != null) { return this.gMarkers.splice(index, 1); } }; MarkerManager.prototype.removeMany = function(gMarkers) { var marker, _i, _len, _ref, _results; _ref = this.gMarkers; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { marker = _ref[_i]; _results.push(this.remove(marker)); } return _results; }; MarkerManager.prototype.draw = function() { var deletes, gMarker, _fn, _i, _j, _len, _len1, _ref, _results, _this = this; deletes = []; _ref = this.gMarkers; _fn = function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { return gMarker.setMap(_this.gMap); } else { return deletes.push(gMarker); } } }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { gMarker = _ref[_i]; _fn(gMarker); } _results = []; for (_j = 0, _len1 = deletes.length; _j < _len1; _j++) { gMarker = deletes[_j]; _results.push(this.remove(gMarker, true)); } return _results; }; MarkerManager.prototype.clear = function() { var gMarker, _i, _len, _ref; _ref = this.gMarkers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { gMarker = _ref[_i]; gMarker.setMap(null); } delete this.gMarkers; return this.gMarkers = []; }; 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; } }; return MarkerManager; })(oo.BaseObject); }); }).call(this); /* Author: Nicholas McCready & jfriend00 AsyncProcessor 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 */ (function() { this.ngGmapModule("directives.api.utils", function() { return this.AsyncProcessor = { handleLargeArray: function(array, callback, pausedCallBack, doneCallBack, chunk, index) { var doChunk; if (chunk == null) { chunk = 100; } if (index == null) { index = 0; } if (array === void 0 || array.length <= 0) { doneCallBack(); return; } doChunk = function() { var cnt, i; cnt = chunk; i = index; while (cnt-- && i < array.length) { callback(array[i]); ++i; } if (i < array.length) { index = i; if (pausedCallBack != null) { pausedCallBack(); } return setTimeout(doChunk, 1); } else { return doneCallBack(); } }; return doChunk(); } }; }); }).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() { this.ngGmapModule("directives.api.utils", function() { return this.ChildEvents = { onChildCreation: function(child) {} }; }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { return this.GmapUtil = { getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([\d\.]+)\s([\d\.]+)$/.exec(anchor); xPos = anchor[1]; yPos = anchor[2]; if (xPos && yPos) { return new google.maps.Point(xPos, yPos); } }, createMarkerOptions: function(coords, icon, defaults, map) { var opts; if (map == null) { map = void 0; } if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : new google.maps.LatLng(coords.latitude, coords.longitude), icon: defaults.icon != null ? defaults.icon : icon, visible: defaults.visible != null ? defaults.visible : (coords.latitude != null) && (coords.longitude != null) }); if (map != null) { opts.map = map; } return opts; }, createWindowOptions: function(gMarker, scope, content, defaults) { if ((content != null) && (defaults != null)) { return angular.extend({}, defaults, { content: defaults.content != null ? defaults.content : content, position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude) }); } }, defaultDelay: 50 }; }); }).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; }; this.ngGmapModule("directives.api.utils", function() { return this.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; })(oo.BaseObject); }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { var logger; this.Logger = { logger: void 0, doLog: false, info: function(msg) { if (logger.doLog) { if (logger.logger != null) { return logger.logger.info(msg); } else { return console.info(msg); } } }, error: function(msg) { if (logger.doLog) { if (logger.logger != null) { return logger.logger.error(msg); } else { return console.error(msg); } } } }; return logger = this.Logger; }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { return this.ModelsWatcher = { didModelsChange: function(newValue, oldValue) { var didModelsChange, hasIntersectionDiff; if (!_.isArray(newValue)) { directives.api.utils.Logger.error("models property must be an array newValue of: " + (newValue.toString()) + " is not!!"); return false; } if (newValue === oldValue) { return false; } hasIntersectionDiff = _.intersectionObjects(newValue, oldValue).length !== oldValue.length; didModelsChange = true; if (!hasIntersectionDiff) { didModelsChange = newValue.length !== oldValue.length; } return didModelsChange; } }; }); }).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; }; this.ngGmapModule("directives.api.models.child", function() { return this.MarkerLabelChildModel = (function(_super) { __extends(MarkerLabelChildModel, _super); MarkerLabelChildModel.include(directives.api.utils.GmapUtil); function MarkerLabelChildModel(gMarker, opt_options) { this.destroy = __bind(this.destroy, this); this.draw = __bind(this.draw, this); this.setPosition = __bind(this.setPosition, this); this.setZIndex = __bind(this.setZIndex, this); this.setVisible = __bind(this.setVisible, this); this.setAnchor = __bind(this.setAnchor, this); this.setMandatoryStyles = __bind(this.setMandatoryStyles, this); this.setStyles = __bind(this.setStyles, this); this.setContent = __bind(this.setContent, this); this.setTitle = __bind(this.setTitle, this); this.getSharedCross = __bind(this.getSharedCross, this); var self, _ref, _ref1; MarkerLabelChildModel.__super__.constructor.call(this); self = this; this.marker = gMarker; this.marker.set("labelContent", opt_options.labelContent); this.marker.set("labelAnchor", this.getLabelPositionPoint(opt_options.labelAnchor)); this.marker.set("labelClass", opt_options.labelClass || 'labels'); this.marker.set("labelStyle", opt_options.labelStyle || { opacity: 100 }); this.marker.set("labelInBackground", opt_options.labelInBackground || false); if (!opt_options.labelVisible) { this.marker.set("labelVisible", true); } if (!opt_options.raiseOnDrag) { this.marker.set("raiseOnDrag", true); } if (!opt_options.clickable) { this.marker.set("clickable", true); } if (!opt_options.draggable) { this.marker.set("draggable", false); } if (!opt_options.optimized) { this.marker.set("optimized", false); } opt_options.crossImage = (_ref = opt_options.crossImage) != null ? _ref : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = (_ref1 = opt_options.handCursor) != null ? _ref1 : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; this.markerLabel = new MarkerLabel_(this.marker, opt_options.crossImage, opt_options.handCursor); this.marker.set("setMap", function(theMap) { google.maps.Marker.prototype.setMap.apply(this, arguments); return self.markerLabel.setMap(theMap); }); this.marker.setMap(this.marker.getMap()); } MarkerLabelChildModel.prototype.getSharedCross = function(crossUrl) { return this.markerLabel.getSharedCross(crossUrl); }; MarkerLabelChildModel.prototype.setTitle = function() { return this.markerLabel.setTitle(); }; MarkerLabelChildModel.prototype.setContent = function() { return this.markerLabel.setContent(); }; MarkerLabelChildModel.prototype.setStyles = function() { return this.markerLabel.setStyles(); }; MarkerLabelChildModel.prototype.setMandatoryStyles = function() { return this.markerLabel.setMandatoryStyles(); }; MarkerLabelChildModel.prototype.setAnchor = function() { return this.markerLabel.setAnchor(); }; MarkerLabelChildModel.prototype.setVisible = function() { return this.markerLabel.setVisible(); }; MarkerLabelChildModel.prototype.setZIndex = function() { return this.markerLabel.setZIndex(); }; MarkerLabelChildModel.prototype.setPosition = function() { return this.markerLabel.setPosition(); }; MarkerLabelChildModel.prototype.draw = function() { return this.markerLabel.draw(); }; MarkerLabelChildModel.prototype.destroy = function() { if ((this.markerLabel.labelDiv_.parentNode != null) && (this.markerLabel.eventDiv_.parentNode != null)) { return this.markerLabel.onRemove(); } }; return MarkerLabelChildModel; })(oo.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; }; this.ngGmapModule("directives.api.models.child", function() { return this.MarkerChildModel = (function(_super) { __extends(MarkerChildModel, _super); MarkerChildModel.include(directives.api.utils.GmapUtil); function MarkerChildModel(index, model, parentScope, gMap, $timeout, defaults, doClick, gMarkerManager) { var self, _this = this; this.index = index; this.model = model; this.parentScope = parentScope; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gMarkerManager = gMarkerManager; this.watchDestroy = __bind(this.watchDestroy, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.isLabelDefined = __bind(this.isLabelDefined, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.destroy = __bind(this.destroy, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); self = this; this.iconKey = this.parentScope.icon; this.coordsKey = this.parentScope.coords; this.clickKey = this.parentScope.click(); this.labelContentKey = this.parentScope.labelContent; this.optionsKey = this.parentScope.options; this.labelOptionsKey = this.parentScope.labelOptions; this.myScope = this.parentScope.$new(false); this.myScope.model = this.model; this.setMyScope(this.model, void 0, true); this.createMarker(this.model); this.myScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setMyScope(newValue, oldValue); } }, true); this.$log = directives.api.utils.Logger; this.$log.info(self); this.watchDestroy(this.myScope); } MarkerChildModel.prototype.setMyScope = function(model, oldModel, isInit) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon); this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords); this.maybeSetScopeValue('labelContent', model, oldModel, this.labelContentKey, this.evalModelHandle, isInit); this.maybeSetScopeValue('click', model, oldModel, this.clickKey, this.evalModelHandle, isInit); return this.createMarker(model, oldModel, isInit); }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit) { var _this = this; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } return this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, function(lModel, lModelKey) { var value; if (lModel === void 0) { return void 0; } value = lModelKey === 'self' ? lModel : lModel[lModelKey]; if (value === void 0) { return value = lModelKey === void 0 ? _this.defaults : _this.myScope.options; } else { return value; } }, isInit, this.setOptions); }; MarkerChildModel.prototype.evalModelHandle = function(model, modelKey) { if (model === void 0) { return void 0; } if (modelKey === 'self') { return model; } else { return model[modelKey]; } }; MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter) { var newValue, oldVal; if (gSetter == null) { gSetter = void 0; } if (oldModel === void 0) { this.myScope[scopePropName] = evaluate(model, modelKey); if (!isInit) { if (gSetter != null) { gSetter(this.myScope); } } return; } oldVal = evaluate(oldModel, modelKey); newValue = evaluate(model, modelKey); if (newValue !== oldVal && this.myScope[scopePropName] !== newValue) { this.myScope[scopePropName] = newValue; if (!isInit) { if (gSetter != null) { gSetter(this.myScope); } return this.gMarkerManager.draw(); } } }; MarkerChildModel.prototype.destroy = function() { return this.myScope.$destroy(); }; MarkerChildModel.prototype.setCoords = function(scope) { if (scope.$id !== this.myScope.$id || this.gMarker === void 0) { return; } if ((scope.coords != null)) { if ((this.scope.coords.latitude == null) || (this.scope.coords.longitude == null)) { this.$log.error("MarkerChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(this.model))); return; } this.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); this.gMarker.setVisible((scope.coords.latitude != null) && (scope.coords.longitude != null)); this.gMarkerManager.remove(this.gMarker); return this.gMarkerManager.add(this.gMarker); } else { return this.gMarkerManager.remove(this.gMarker); } }; MarkerChildModel.prototype.setIcon = function(scope) { if (scope.$id !== this.myScope.$id || this.gMarker === void 0) { return; } this.gMarkerManager.remove(this.gMarker); this.gMarker.setIcon(scope.icon); this.gMarkerManager.add(this.gMarker); this.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); return this.gMarker.setVisible(scope.coords.latitude && (scope.coords.longitude != null)); }; MarkerChildModel.prototype.setOptions = function(scope) { var _ref, _this = this; if (scope.$id !== this.myScope.$id) { return; } if (this.gMarker != null) { this.gMarkerManager.remove(this.gMarker); delete this.gMarker; } if (!((_ref = scope.coords) != null ? _ref : typeof scope.icon === "function" ? scope.icon(scope.options != null) : void 0)) { return; } this.opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options); delete this.gMarker; if (this.isLabelDefined(scope)) { this.gMarker = new MarkerWithLabel(this.setLabelOptions(this.opts, scope)); } else { this.gMarker = new google.maps.Marker(this.opts); } this.gMarkerManager.add(this.gMarker); return google.maps.event.addListener(this.gMarker, 'click', function() { if (_this.doClick && (_this.myScope.click != null)) { return _this.myScope.click(); } }); }; MarkerChildModel.prototype.isLabelDefined = function(scope) { return scope.labelContent != null; }; MarkerChildModel.prototype.setLabelOptions = function(opts, scope) { opts.labelAnchor = this.getLabelPositionPoint(scope.labelAnchor); opts.labelClass = scope.labelClass; opts.labelContent = scope.labelContent; return opts; }; MarkerChildModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { var self; if (_this.gMarker != null) { _this.gMarkerManager.remove(_this.gMarker); delete _this.gMarker; } return self = void 0; }); }; return MarkerChildModel; })(oo.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; }; this.ngGmapModule("directives.api.models.child", function() { return this.WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(directives.api.utils.GmapUtil); function WindowChildModel(scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, $http, $templateCache, $compile, element, needToManualDestroy) { this.element = element; if (needToManualDestroy == null) { needToManualDestroy = false; } this.destroy = __bind(this.destroy, this); this.hideWindow = __bind(this.hideWindow, this); this.getLatestPosition = __bind(this.getLatestPosition, this); this.showWindow = __bind(this.showWindow, this); this.handleClick = __bind(this.handleClick, this); this.watchCoords = __bind(this.watchCoords, this); this.watchShow = __bind(this.watchShow, this); this.createGWin = __bind(this.createGWin, this); this.scope = scope; this.opts = opts; this.mapCtrl = mapCtrl; this.markerCtrl = markerCtrl; this.isIconVisibleOnClick = isIconVisibleOnClick; this.initialMarkerVisibility = this.markerCtrl != null ? this.markerCtrl.getVisible() : false; this.$log = directives.api.utils.Logger; this.$http = $http; this.$templateCache = $templateCache; this.$compile = $compile; this.createGWin(); if (this.markerCtrl != null) { this.markerCtrl.setClickable(true); } this.handleClick(); this.watchShow(); this.watchCoords(); this.needToManualDestroy = needToManualDestroy; this.$log.info(this); } WindowChildModel.prototype.createGWin = function(createOpts) { var _this = this; if (createOpts == null) { createOpts = false; } if ((this.gWin == null) && createOpts) { this.opts = this.markerCtrl != null ? this.createWindowOptions(this.markerCtrl, this.scope, this.element.html(), {}) : {}; } if ((this.opts != null) && this.gWin === void 0) { this.gWin = new google.maps.InfoWindow(this.opts); return google.maps.event.addListener(this.gWin, 'closeclick', function() { if (_this.markerCtrl != null) { _this.markerCtrl.setVisible(_this.initialMarkerVisibility); } if (_this.scope.closeClick != null) { return _this.scope.closeClick(); } }); } }; WindowChildModel.prototype.watchShow = function() { var _this = this; return this.scope.$watch('show', function(newValue, oldValue) { if (newValue !== oldValue) { if (newValue) { return _this.showWindow(); } else { return _this.hideWindow(); } } else { if (_this.gWin != null) { if (newValue && !_this.gWin.getMap()) { return _this.showWindow(); } } } }, true); }; WindowChildModel.prototype.watchCoords = function() { var scope, _this = this; scope = this.markerCtrl != null ? this.scope.$parent : this.scope; return scope.$watch('coords', function(newValue, oldValue) { if (newValue !== oldValue) { if (newValue == null) { return _this.hideWindow(); } else { if ((newValue.latitude == null) || (newValue.longitude == null)) { _this.$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } return _this.gWin.setPosition(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } } }, true); }; WindowChildModel.prototype.handleClick = function() { var _this = this; if (this.markerCtrl != null) { return google.maps.event.addListener(this.markerCtrl, 'click', function() { var pos; if ((_this.gWin == null) && (_this.opts == null)) { _this.createGWin(true); } else { if (_this.gWin == null) { _this.createGWin(); } } pos = _this.markerCtrl.getPosition(); if (_this.gWin != null) { _this.gWin.setPosition(pos); _this.gWin.open(_this.mapCtrl); } _this.initialMarkerVisibility = _this.markerCtrl.getVisible(); return _this.markerCtrl.setVisible(_this.isIconVisibleOnClick); }); } }; WindowChildModel.prototype.showWindow = function() { var _this = this; if (this.scope.templateUrl) { if (this.gWin) { return this.$http.get(this.scope.templateUrl, { cache: this.$templateCache }).then(function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = _this.$compile(content.data)(templateScope); _this.gWin.setContent(compiled.get(0)); return _this.gWin.open(_this.mapCtrl); }); } } else { if (this.gWin != null) { return this.gWin.open(this.mapCtrl); } } }; WindowChildModel.prototype.getLatestPosition = function() { if ((this.gWin != null) && (this.markerCtrl != null)) { return this.gWin.setPosition(this.markerCtrl.getPosition()); } }; WindowChildModel.prototype.hideWindow = function() { if (this.gWin != null) { return this.gWin.close(); } }; WindowChildModel.prototype.destroy = function() { var self; this.hideWindow(this.gWin); if ((this.scope != null) && this.needToManualDestroy) { this.scope.$destroy(); } delete this.gWin; return self = void 0; }; return WindowChildModel; })(oo.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; }; this.ngGmapModule("directives.api.models.parent", function() { return this.IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; IMarkerParentModel.prototype.isFalse = function(value) { return ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO'].indexOf(value) !== -1; }; function IMarkerParentModel(scope, element, attrs, mapCtrl, $timeout) { var self, _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.mapCtrl = mapCtrl; this.$timeout = $timeout; this.linkInit = __bind(this.linkInit, this); this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.watch = __bind(this.watch, this); this.validateScope = __bind(this.validateScope, this); this.onTimeOut = __bind(this.onTimeOut, this); self = this; this.$log = directives.api.utils.Logger; if (!this.validateScope(scope)) { return; } this.doClick = angular.isDefined(attrs.click); if (scope.options != null) { this.DEFAULTS = scope.options; } this.$timeout(function() { _this.watch('coords', scope); _this.watch('icon', scope); _this.watch('options', scope); _this.onTimeOut(scope); return scope.$on("$destroy", function() { return _this.onDestroy(scope); }); }); } IMarkerParentModel.prototype.onTimeOut = function(scope) {}; IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope) { var _this = this; return scope.$watch(propNameToWatch, function(newValue, oldValue) { if (newValue !== oldValue) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }, true); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { throw new Exception("Not Implemented!!"); }; IMarkerParentModel.prototype.onDestroy = function(scope) { throw new Exception("Not Implemented!!"); }; IMarkerParentModel.prototype.linkInit = function(element, mapCtrl, scope, animate) { throw new Exception("Not Implemented!!"); }; return IMarkerParentModel; })(oo.BaseObject); }); }).call(this); /* - interface directive for all window(s) to derrive from */ (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; }; this.ngGmapModule("directives.api.models.parent", function() { return this.IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(directives.api.utils.GmapUtil); IWindowParentModel.prototype.DEFAULTS = {}; function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { var self; self = this; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; if (scope.options != null) { this.DEFAULTS = scope.options; } } return IWindowParentModel; })(oo.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; }; this.ngGmapModule("directives.api.models.parent", function() { return this.LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, mapCtrl, $timeout, onLayerCreated, $log) { var _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.mapCtrl = mapCtrl; this.$timeout = $timeout; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : directives.api.utils.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.gMap = void 0; this.doShow = true; this.$timeout(function() { _this.gMap = mapCtrl.getMap(); if (angular.isDefined(_this.attrs.show)) { _this.doShow = _this.scope.show; } if (_this.doShow !== null && _this.doShow && _this.Map !== null) { _this.layer.setMap(_this.gMap); } _this.scope.$watch("show", function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.layer.setMap(_this.gMap); } else { return _this.layer.setMap(null); } } }, true); _this.scope.$watch("options", function(newValue, oldValue) { if (newValue !== oldValue) { _this.layer.setMap(null); _this.layer = null; return _this.createGoogleLayer(); } }, true); return _this.scope.$on("$destroy", function() { return this.layer.setMap(null); }); }); } LayerParentModel.prototype.createGoogleLayer = function() { var _this = this; if (this.attrs.options != null) { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.layer = 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); } return this.$timeout(function() { var fn; if ((_this.layer != null) && (_this.onLayerCreated != null)) { fn = _this.onLayerCreated(_this.scope, _this.layer); if (fn) { return fn(_this.layer); } } }); }; return LayerParentModel; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a marker. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (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; }; this.ngGmapModule("directives.api.models.parent", function() { return this.MarkerParentModel = (function(_super) { __extends(MarkerParentModel, _super); MarkerParentModel.include(directives.api.utils.GmapUtil); function MarkerParentModel(scope, element, attrs, mapCtrl, $timeout) { this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.onTimeOut = __bind(this.onTimeOut, this); var self; MarkerParentModel.__super__.constructor.call(this, scope, element, attrs, mapCtrl, $timeout); self = this; } MarkerParentModel.prototype.onTimeOut = function(scope) { var opts, _this = this; opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.mapCtrl.getMap()); this.scope.gMarker = new google.maps.Marker(opts); google.maps.event.addListener(this.scope.gMarker, 'click', function() { if (_this.doClick && (scope.click != null)) { return _this.$timeout(function() { return _this.scope.click(); }); } }); this.setEvents(this.scope.gMarker, scope); return this.$log.info(this); }; MarkerParentModel.prototype.onWatch = function(propNameToWatch, scope) { switch (propNameToWatch) { case 'coords': if ((scope.coords != null) && (this.scope.gMarker != null)) { this.scope.gMarker.setMap(this.mapCtrl.getMap()); this.scope.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); this.scope.gMarker.setVisible((scope.coords.latitude != null) && (scope.coords.longitude != null)); return this.scope.gMarker.setOptions(scope.options); } else { return this.scope.gMarker.setMap(null); } break; case 'icon': if ((scope.icon != null) && (scope.coords != null) && (this.scope.gMarker != null)) { this.scope.gMarker.setOptions(scope.options); this.scope.gMarker.setIcon(scope.icon); this.scope.gMarker.setMap(null); this.scope.gMarker.setMap(this.mapCtrl.getMap()); this.scope.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); return this.scope.gMarker.setVisible(scope.coords.latitude && (scope.coords.longitude != null)); } break; case 'options': if ((scope.coords != null) && (scope.icon != null) && scope.options) { if (this.scope.gMarker != null) { this.scope.gMarker.setMap(null); } delete this.scope.gMarker; return this.scope.gMarker = new google.maps.Marker(this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.mapCtrl.getMap())); } } }; MarkerParentModel.prototype.onDestroy = function(scope) { var self; if (this.scope.gMarker === void 0) { self = void 0; return; } this.scope.gMarker.setMap(null); delete this.scope.gMarker; return self = void 0; }; MarkerParentModel.prototype.setEvents = function(marker, scope) { var eventHandler, eventName, _ref, _results; if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) { _ref = scope.events; _results = []; for (eventName in _ref) { eventHandler = _ref[eventName]; if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { _results.push(google.maps.event.addListener(marker, eventName, function() { return eventHandler.apply(scope, [marker, eventName, arguments]); })); } else { _results.push(void 0); } } return _results; } }; return MarkerParentModel; })(directives.api.models.parent.IMarkerParentModel); }); }).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; }; this.ngGmapModule("directives.api.models.parent", function() { return this.MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(directives.api.utils.ModelsWatcher); function MarkersParentModel(scope, element, attrs, mapCtrl, $timeout) { this.fit = __bind(this.fit, this); this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.reBuildMarkers = __bind(this.reBuildMarkers, this); this.createMarkers = __bind(this.createMarkers, this); this.validateScope = __bind(this.validateScope, this); this.onTimeOut = __bind(this.onTimeOut, this); var self; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, mapCtrl, $timeout); self = this; this.markersIndex = 0; this.gMarkerManager = void 0; this.scope = scope; this.scope.markerModels = []; this.bigGulp = directives.api.utils.AsyncProcessor; this.$timeout = $timeout; this.$log.info(this); } MarkersParentModel.prototype.onTimeOut = function(scope) { this.watch('models', scope); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('fit', scope); return this.createMarkers(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; }; MarkersParentModel.prototype.createMarkers = function(scope) { var markers, _this = this; if ((scope.doCluster != null) && scope.doCluster === true) { if (scope.clusterOptions != null) { if (this.gMarkerManager === void 0) { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap(), void 0, scope.clusterOptions); } else { if (this.gMarkerManager.opt_options !== scope.clusterOptions) { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap(), void 0, scope.clusterOptions); } } } else { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap()); } } else { this.gMarkerManager = new directives.api.managers.MarkerManager(this.mapCtrl.getMap()); } markers = []; scope.isMarkerModelsReady = false; return this.bigGulp.handleLargeArray(scope.models, function(model) { var child; scope.doRebuild = true; child = new directives.api.models.child.MarkerChildModel(_this.markersIndex, model, scope, _this.mapCtrl, _this.$timeout, _this.DEFAULTS, _this.doClick, _this.gMarkerManager); _this.$log.info('child', child, 'markers', markers); markers.push(child); return _this.markersIndex++; }, (function() {}), function() { _this.gMarkerManager.draw(); scope.markerModels = markers; if (angular.isDefined(_this.attrs.fit) && (scope.fit != null) && scope.fit) { _this.fit(); } scope.isMarkerModelsReady = true; if (scope.onMarkerModelsReady != null) { return scope.onMarkerModelsReady(scope); } }); }; MarkersParentModel.prototype.reBuildMarkers = function(scope) { var _this = this; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } _.each(scope.markerModels, function(oldM) { return oldM.destroy(); }); this.markersIndex = 0; if (this.gMarkerManager != null) { this.gMarkerManager.clear(); } return this.createMarkers(scope); }; MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === 'models') { if (!this.didModelsChange(newValue, oldValue)) { return; } } if (propNameToWatch === 'options' && (newValue != null)) { this.DEFAULTS = newValue; return; } return this.reBuildMarkers(scope); }; MarkersParentModel.prototype.onDestroy = function(scope) { var model, _i, _len, _ref; _ref = scope.markerModels; for (_i = 0, _len = _ref.length; _i < _len; _i++) { model = _ref[_i]; model.destroy(); } if (this.gMarkerManager != null) { return this.gMarkerManager.clear(); } }; MarkersParentModel.prototype.fit = function() { var bounds, everSet, _this = this; if (this.mapCtrl && (this.scope.markerModels != null) && this.scope.markerModels.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; _.each(this.scope.markerModels, function(childModelMarker) { if (childModelMarker.gMarker != null) { if (!everSet) { everSet = true; } return bounds.extend(childModelMarker.gMarker.getPosition()); } }); if (everSet) { return this.mapCtrl.getMap().fitBounds(bounds); } } }; return MarkersParentModel; })(directives.api.models.parent.IMarkerParentModel); }); }).call(this); /* Windows directive where many windows map to the models property */ (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; }; this.ngGmapModule("directives.api.models.parent", function() { return this.WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(directives.api.utils.ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate) { 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.createChildScopesWindows = __bind(this.createChildScopesWindows, this); this.onMarkerModelsReady = __bind(this.onMarkerModelsReady, this); this.watchOurScope = __bind(this.watchOurScope, this); this.destroy = __bind(this.destroy, this); this.watchDestroy = __bind(this.watchDestroy, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); var name, self, _i, _len, _ref, _this = this; WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate); self = this; this.$interpolate = $interpolate; this.windows = []; this.windwsIndex = 0; this.scopePropNames = ['show', 'coords', 'templateUrl', 'templateParameter', 'isIconVisibleOnClick', 'closeClick']; _ref = this.scopePropNames; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; this[name + 'Key'] = void 0; } this.linked = new directives.api.utils.Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.bigGulp = directives.api.utils.AsyncProcessor; this.$log.info(self); this.$timeout(function() { _this.watchOurScope(scope); return _this.createChildScopesWindows(); }, 50); } WindowsParentModel.prototype.watch = function(scope, name, nameKey) { var _this = this; return scope.$watch(name, function(newValue, oldValue) { var model, _i, _len, _ref, _results; if (newValue !== oldValue) { _this[nameKey] = typeof newValue === 'function' ? newValue() : newValue; _ref = _this.windows; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { model = _ref[_i]; _results.push((function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; })(model)); } return _results; } }, true); }; WindowsParentModel.prototype.watchModels = function(scope) { var _this = this; return scope.$watch('models', function(newValue, oldValue) { if (_this.didModelsChange(newValue, oldValue)) { _this.destroy(); return _this.createChildScopesWindows(); } }); }; WindowsParentModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { return _this.destroy(); }); }; WindowsParentModel.prototype.destroy = function() { var _this = this; _.each(this.windows, function(model) { return model.destroy(); }); delete this.windows; this.windows = []; return this.windowsIndex = 0; }; WindowsParentModel.prototype.watchOurScope = function(scope) { var _this = this; return _.each(this.scopePropNames, function(name) { var nameKey; nameKey = name + 'Key'; _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; return _this.watch(scope, name, nameKey); }); }; WindowsParentModel.prototype.onMarkerModelsReady = function(scope) { var _this = this; this.destroy(); this.models = scope.models; if (this.firstTime) { this.watchDestroy(scope); } this.setContentKeys(scope.models); return this.bigGulp.handleLargeArray(scope.markerModels, function(mm) { return _this.createWindow(mm.model, mm.gMarker, _this.gMap); }, (function() {}), function() { return _this.firstTime = false; }); }; WindowsParentModel.prototype.createChildScopesWindows = function() { /* 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. */ var markersScope, modelsNotDefined, _this = this; this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } this.gMap = this.linked.ctrls[0].getMap(); markersScope = this.linked.ctrls.length > 1 && (this.linked.ctrls[1] != null) ? this.linked.ctrls[1].getMarkersScope() : void 0; modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (markersScope === void 0 || (markersScope.markerModels === void 0 && markersScope.models === void 0))) { this.$log.info("No models to create windows from! Need direct models or models derrived from markers!"); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.models = this.linked.scope.models; if (this.firstTime) { this.watchModels(this.linked.scope); this.watchDestroy(this.linked.scope); } this.setContentKeys(this.linked.scope.models); return this.bigGulp.handleLargeArray(this.linked.scope.models, function(model) { return _this.createWindow(model, void 0, _this.gMap); }, (function() {}), function() { return _this.firstTime = false; }); } else { markersScope.onMarkerModelsReady = this.onMarkerModelsReady; if (markersScope.isMarkerModelsReady) { return this.onMarkerModelsReady(markersScope); } } } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (models.length > 0) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { /* Create ChildScope to Mimmick an ng-repeat created scope, must define the below scope scope= { coords: '=coords', show: '&show', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick' } */ var childScope, opts, parsedContent, _this = this; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }, true); parsedContent = this.interpolateContent(this.linked.element.html(), model); opts = this.createWindowOptions(gMarker, childScope, parsedContent, this.DEFAULTS); return this.windows.push(new directives.api.models.child.WindowChildModel(childScope, opts, this.isIconVisibleOnClick, gMap, gMarker, this.$http, this.$templateCache, this.$compile, true)); }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { var name, _fn, _i, _len, _ref, _this = this; _ref = this.scopePropNames; _fn = function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; _fn(name); } 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 = this.$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); }; return WindowsParentModel; })(directives.api.models.parent.IWindowParentModel); }); }).call(this); /* - interface for all labels to derrive from - to enforce a minimum set of requirements - attributes - content - anchor - 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; }; this.ngGmapModule("directives.api", function() { return this.ILabel = (function(_super) { __extends(ILabel, _super); function ILabel($timeout) { this.link = __bind(this.link, this); var self; self = this; this.restrict = 'ECMA'; this.replace = true; this.template = void 0; this.require = void 0; this.transclude = true; this.priority = -100; this.scope = { labelContent: '=content', labelAnchor: '@anchor', labelClass: '@class', labelStyle: '=style' }; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; } ILabel.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not Implemented!!"); }; return ILabel; })(oo.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; }; this.ngGmapModule("directives.api", function() { return this.IMarker = (function(_super) { __extends(IMarker, _super); function IMarker($timeout) { this.link = __bind(this.link, this); var self; self = this; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; this.restrict = 'ECMA'; this.require = '^googleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events' }; } IMarker.prototype.controller = [ '$scope', '$element', function($scope, $element) { throw new Exception("Not Implemented!!"); } ]; IMarker.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IMarker; })(oo.BaseObject); }); }).call(this); /* - interface directive for all window(s) to derrive from */ (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; }; this.ngGmapModule("directives.api", function() { return this.IWindow = (function(_super) { __extends(IWindow, _super); IWindow.include(directives.api.utils.ChildEvents); function IWindow($timeout, $compile, $http, $templateCache) { var self; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.link = __bind(this.link, this); self = this; this.restrict = 'ECMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = void 0; this.replace = true; this.scope = { coords: '=coords', show: '=show', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options' }; this.$log = directives.api.utils.Logger; } IWindow.prototype.link = function(scope, element, attrs, ctrls) { throw new Exception("Not Implemented!!"); }; return IWindow; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a label. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (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; }; this.ngGmapModule("directives.api", function() { return this.Label = (function(_super) { __extends(Label, _super); function Label($timeout) { this.link = __bind(this.link, this); var self; Label.__super__.constructor.call(this, $timeout); self = this; this.require = '^marker'; this.template = '<span class="angular-google-maps-marker-label" ng-transclude></span>'; this.$log.info(this); } Label.prototype.link = function(scope, element, attrs, ctrl) { var _this = this; return this.$timeout(function() { var label, markerCtrl; markerCtrl = ctrl.getMarkerScope().gMarker; if (markerCtrl != null) { label = new directives.api.models.child.MarkerLabelChildModel(markerCtrl, scope); } return scope.$on("$destroy", function() { return label.destroy(); }); }, directives.api.utils.GmapUtil.defaultDelay + 25); }; return Label; })(directives.api.ILabel); }); }).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; }; this.ngGmapModule("directives.api", function() { return this.Layer = (function(_super) { __extends(Layer, _super); function Layer($timeout) { this.$timeout = $timeout; this.link = __bind(this.link, this); this.$log = directives.api.utils.Logger; this.restrict = "ECMA"; this.require = "^googleMap"; 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) { if (attrs.oncreated != null) { return new directives.api.models.parent.LayerParentModel(scope, element, attrs, mapCtrl, this.$timeout, scope.onCreated); } else { return new directives.api.models.parent.LayerParentModel(scope, element, attrs, mapCtrl, this.$timeout); } }; return Layer; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a marker. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (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; }; this.ngGmapModule("directives.api", function() { return this.Marker = (function(_super) { __extends(Marker, _super); function Marker($timeout) { this.link = __bind(this.link, this); var self; Marker.__super__.constructor.call(this, $timeout); self = this; this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; this.$log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { return { getMarkerScope: function() { return $scope; } }; } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { return new directives.api.models.parent.MarkerParentModel(scope, element, attrs, ctrl, this.$timeout); }; return Marker; })(directives.api.IMarker); }); }).call(this); /* Markers will map icon and coords differently than directibes.api.Marker. This is because Scope and the model marker are not 1:1 in this setting. - icon - will be the iconKey to the marker value ie: to get the icon marker[iconKey] - coords - will be the coordsKey to the marker value ie: to get the icon marker[coordsKey] - watches from IMarker reflect that the look up key for a value has changed and not the actual icon or coords itself - actual changes to a model are tracked inside directives.api.model.MarkerModel */ (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; }; this.ngGmapModule("directives.api", function() { return this.Markers = (function(_super) { __extends(Markers, _super); function Markers($timeout) { this.link = __bind(this.link, this); var self; Markers.__super__.constructor.call(this, $timeout); self = this; this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; this.scope.models = '=models'; this.scope.doCluster = '=docluster'; this.scope.clusterOptions = '=clusteroptions'; this.scope.fit = '=fit'; this.scope.labelContent = '=labelcontent'; this.scope.labelAnchor = '@labelanchor'; this.scope.labelClass = '@labelclass'; this.$timeout = $timeout; this.$log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { return { getMarkersScope: function() { return $scope; } }; } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { return new directives.api.models.parent.MarkersParentModel(scope, element, attrs, ctrl, this.$timeout); }; return Markers; })(directives.api.IMarker); }); }).call(this); /* Window directive for GoogleMap Info Windows, where ng-repeat is being used.... Where Html DOM element is 1:1 on Scope and a Model */ (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; }; this.ngGmapModule("directives.api", function() { return this.Window = (function(_super) { __extends(Window, _super); Window.include(directives.api.utils.GmapUtil); function Window($timeout, $compile, $http, $templateCache) { this.link = __bind(this.link, this); var self; Window.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); self = this; this.require = ['^googleMap', '^?marker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; this.$log.info(self); } Window.prototype.link = function(scope, element, attrs, ctrls) { var _this = this; return this.$timeout(function() { var defaults, hasScopeCoords, isIconVisibleOnClick, mapCtrl, markerCtrl, markerScope, opts, window; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } mapCtrl = ctrls[0].getMap(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1].getMarkerScope().gMarker : void 0; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && (scope.coords != null) && (scope.coords.latitude != null) && (scope.coords.longitude != null); opts = hasScopeCoords ? _this.createWindowOptions(markerCtrl, scope, element.html(), defaults) : void 0; if (mapCtrl != null) { window = new directives.api.models.child.WindowChildModel(scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, _this.$http, _this.$templateCache, _this.$compile, element); } scope.$on("$destroy", function() { return window.destroy(); }); if (ctrls[1] != null) { markerScope = ctrls[1].getMarkerScope(); markerScope.$watch('coords', function(newValue, oldValue) { if (newValue == null) { return window.hideWindow(); } }); markerScope.$watch('coords.latitude', function(newValue, oldValue) { if (newValue !== oldValue) { return window.getLatestPosition(); } }); } if ((_this.onChildCreation != null) && (window != null)) { return _this.onChildCreation(window); } }, directives.api.utils.GmapUtil.defaultDelay + 25); }; return Window; })(directives.api.IWindow); }); }).call(this); /* Windows directive where many windows map to the models property */ (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; }; this.ngGmapModule("directives.api", function() { return this.Windows = (function(_super) { __extends(Windows, _super); function Windows($timeout, $compile, $http, $templateCache, $interpolate) { this.link = __bind(this.link, this); var self; Windows.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); self = this; this.$interpolate = $interpolate; this.require = ['^googleMap', '^?markers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; this.scope.models = '=models'; this.$log.info(self); } Windows.prototype.link = function(scope, element, attrs, ctrls) { return new directives.api.models.parent.WindowsParentModel(scope, element, attrs, ctrls, this.$timeout, this.$compile, this.$http, this.$templateCache, this.$interpolate); }; return Windows; })(directives.api.IWindow); }); }).call(this); /* ! 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/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ (function() { angular.module("google-maps").directive("googleMap", [ "$log", "$timeout", function($log, $timeout) { "use strict"; var DEFAULTS, isTrue; isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; directives.api.utils.Logger.logger = $log; DEFAULTS = { mapTypeId: google.maps.MapTypeId.ROADMAP }; return { self: this, restrict: "ECMA", transclude: true, replace: false, template: "<div class=\"angular-google-map\"><div class=\"angular-google-map-container\"></div><div ng-transclude style=\"display: none\"></div></div>", scope: { center: "=center", zoom: "=zoom", dragging: "=dragging", refresh: "&refresh", windows: "=windows", options: "=options", events: "=events", styles: "=styles", bounds: "=bounds" }, controller: [ "$scope", function($scope) { return { getMap: function() { return $scope.map; } }; } ], /* @param scope @param element @param attrs */ link: function(scope, element, attrs) { var dragging, el, eventName, getEventHandler, opts, settingCenterFromScope, type, _m, _this = this; if (!angular.isDefined(scope.center) || (!angular.isDefined(scope.center.latitude) || !angular.isDefined(scope.center.longitude))) { $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 + "\""); } } _m = new google.maps.Map(el.find("div")[1], angular.extend({}, DEFAULTS, opts, { center: new google.maps.LatLng(scope.center.latitude, scope.center.longitude), draggable: isTrue(attrs.draggable), zoom: scope.zoom, bounds: scope.bounds })); dragging = false; google.maps.event.addListener(_m, "dragstart", function() { dragging = true; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(_m, "dragend", function() { dragging = false; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(_m, "drag", function() { var c; c = _m.center; return _.defer(function() { return scope.$apply(function(s) { s.center.latitude = c.lat(); return s.center.longitude = c.lng(); }); }); }); google.maps.event.addListener(_m, "zoom_changed", function() { if (scope.zoom !== _m.zoom) { return _.defer(function() { return scope.$apply(function(s) { return s.zoom = _m.zoom; }); }); } }); settingCenterFromScope = false; google.maps.event.addListener(_m, "center_changed", function() { var c; c = _m.center; if (settingCenterFromScope) { return; } return _.defer(function() { return scope.$apply(function(s) { if (!_m.dragging) { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } }); }); }); google.maps.event.addListener(_m, "idle", function() { var b, ne, sw; b = _m.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); return _.defer(function() { return scope.$apply(function(s) { if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; return s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } }); }); }); if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_m, eventName, arguments]); }; }; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { google.maps.event.addListener(_m, eventName, getEventHandler(eventName)); } } } scope.map = _m; google.maps.event.trigger(_m, "resize"); if (!angular.isUndefined(scope.refresh())) { scope.$watch("refresh()", function(newValue, oldValue) { var coords; if (newValue && !oldValue) { coords = new google.maps.LatLng(newValue.latitude, newValue.longitude); if (isTrue(attrs.pan)) { return _m.panTo(coords); } else { return _m.setCenter(coords); } } }); } scope.$watch("center", (function(newValue, oldValue) { var coords; if (newValue === oldValue) { return; } settingCenterFromScope = true; if (!dragging) { if ((newValue.latitude == null) || (newValue.longitude == null)) { $log.error("Invalid center for newVa;ue: " + (JSON.stringify(newValue))); } coords = new google.maps.LatLng(newValue.latitude, newValue.longitude); if (isTrue(attrs.pan)) { _m.panTo(coords); } else { _m.setCenter(coords); } } return settingCenterFromScope = false; }), true); scope.$watch("zoom", function(newValue, oldValue) { if (newValue === oldValue) { return; } return _m.setZoom(newValue); }); scope.$watch("bounds", function(newValue, oldValue) { var bounds, ne, sw; if (newValue === oldValue) { return; } if ((newValue.northeast.latitude == null) || (newValue.northeast.longitude == null) || (newValue.southwest.latitude == null) || (newValue.southwest.longitude == 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 _m.fitBounds(bounds); }); scope.$watch("options", function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { opts.options = newValue; if (_m != null) { return _m.setOptions(opts); } } }, true); return scope.$watch("styles", function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { opts.styles = newValue; if (_m != null) { return _m.setOptions(opts); } } }, true); } }; } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @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("google-maps").directive("marker", [ "$timeout", function($timeout) { return new directives.api.Marker($timeout); } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @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("google-maps").directive("markers", [ "$timeout", function($timeout) { return new directives.api.Markers($timeout); } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @authors Bruno Queiroz, creativelikeadog@gmail.com */ /* Marker label directive This directive is used to create a marker label on an existing map. {attribute content required} content of the label {attribute anchor required} string that contains the x and y point position of the label {attribute class optional} class to DOM object {attribute style optional} style for the label */ (function() { angular.module("google-maps").directive("markerLabel", [ "$log", "$timeout", function($log, $timeout) { return new directives.api.Label($timeout); } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps").directive("polygon", [ "$log", "$timeout", function($log, $timeout) { var DEFAULTS, convertPathPoints, extendMapBounds, isTrue, validatePathPoints; validatePathPoints = function(path) { var i; i = 0; while (i < path.length) { if (angular.isUndefined(path[i].latitude) || angular.isUndefined(path[i].longitude)) { return false; } i++; } return true; }; convertPathPoints = function(path) { var i, result; result = new google.maps.MVCArray(); i = 0; while (i < path.length) { result.push(new google.maps.LatLng(path[i].latitude, path[i].longitude)); 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); }; /* Check if a value is true */ isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "ECA", require: "^googleMap", replace: true, scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || scope.path.length < 2 || !validatePathPoints(scope.path)) { $log.error("polyline: no valid path attribute found"); return; } return $timeout(function() { var map, opts, pathInsertAtListener, pathPoints, pathRemoveAtListener, pathSetAtListener, polyPath, polyline; map = mapCtrl.getMap(); pathPoints = convertPathPoints(scope.path); opts = angular.extend({}, DEFAULTS, { map: map, path: pathPoints, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); polyline = new google.maps.Polyline(opts); if (isTrue(attrs.fit)) { extendMapBounds(map, pathPoints); } if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return polyline.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return polyline.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return polyline.setVisible(newValue); }); } pathSetAtListener = void 0; pathInsertAtListener = void 0; pathRemoveAtListener = void 0; polyPath = polyline.getPath(); pathSetAtListener = google.maps.event.addListener(polyPath, "set_at", function(index) { var value; value = polyPath.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scope.path[index].latitude = value.lat(); scope.path[index].longitude = value.lng(); return scope.$apply(); }); pathInsertAtListener = google.maps.event.addListener(polyPath, "insert_at", function(index) { var value; value = polyPath.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scope.path.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); return scope.$apply(); }); pathRemoveAtListener = google.maps.event.addListener(polyPath, "remove_at", function(index) { scope.path.splice(index, 1); return scope.$apply(); }); scope.$watch("path", (function(newArray) { var i, l, newLength, newValue, oldArray, oldLength, oldValue; oldArray = polyline.getPath(); if (newArray !== oldArray) { if (newArray) { polyline.setMap(map); i = 0; oldLength = oldArray.getLength(); newLength = newArray.length; l = Math.min(oldLength, newLength); while (i < l) { oldValue = oldArray.getAt(i); newValue = newArray[i]; if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); } i++; } while (i < newLength) { newValue = newArray[i]; oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); i++; } while (i < oldLength) { oldArray.pop(); i++; } if (isTrue(attrs.fit)) { return extendMapBounds(map, oldArray); } } else { return polyline.setMap(null); } } }), true); return scope.$on("$destroy", function() { polyline.setMap(null); pathSetAtListener(); pathSetAtListener = null; pathInsertAtListener(); pathInsertAtListener = null; pathRemoveAtListener(); return pathRemoveAtListener = null; }); }); } }; } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps").directive("polyline", [ "$log", "$timeout", "array-sync", function($log, $timeout, arraySync) { var DEFAULTS, convertPathPoints, extendMapBounds, isTrue, validatePathPoints; validatePathPoints = function(path) { var i; i = 0; while (i < path.length) { if (angular.isUndefined(path[i].latitude) || angular.isUndefined(path[i].longitude)) { return false; } i++; } return true; }; convertPathPoints = function(path) { var i, result; result = new google.maps.MVCArray(); i = 0; while (i < path.length) { result.push(new google.maps.LatLng(path[i].latitude, path[i].longitude)); 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); }; /* Check if a value is true */ isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "ECA", replace: true, require: "^googleMap", scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || scope.path.length < 2 || !validatePathPoints(scope.path)) { $log.error("polyline: no valid path attribute found"); return; } return $timeout(function() { var arraySyncer, buildOpts, map, polyline; buildOpts = function(pathPoints) { var opts; opts = angular.extend({}, DEFAULTS, { map: map, path: pathPoints, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); return opts; }; map = mapCtrl.getMap(); polyline = new google.maps.Polyline(buildOpts(convertPathPoints(scope.path))); if (isTrue(attrs.fit)) { extendMapBounds(map, pathPoints); } if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return polyline.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return polyline.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return polyline.setVisible(newValue); }); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } arraySyncer = arraySync(polyline.getPath(), scope, "path"); return scope.$on("$destroy", function() { polyline.setMap(null); if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }); }); } }; } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @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("google-maps").directive("window", [ "$timeout", "$compile", "$http", "$templateCache", function($timeout, $compile, $http, $templateCache) { return new directives.api.Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @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("google-maps").directive("windows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", function($timeout, $compile, $http, $templateCache, $interpolate) { return new directives.api.Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); /* ! 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/nlaplante/angular-google-maps @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() { angular.module("google-maps").directive("layer", [ "$timeout", function($timeout) { return new directives.api.Layer($timeout); } ]); }).call(this); ;/** * @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]; if (typeof String.prototype.trim !== 'function') { /** * IE hack since trim() doesn't exist in all browsers * @return {string} The string with removed whitespace */ String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } ;/** * 1.1.9-patched * @name MarkerWithLabel for V3 * @version 1.1.8 [February 26, 2013] * @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. */ 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; if (this.labelDiv_.parentNode !== null) this.labelDiv_.parentNode.removeChild(this.labelDiv_); if (this.eventDiv_.parentNode !== null) 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_.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); };
src/browser/me/Profile.react.js
marekv69/twitterTestApp
import Component from 'react-pure-render/component'; import Helmet from 'react-helmet'; import React, {PropTypes} from 'react'; export default class Profile extends Component { static propTypes = { msg: PropTypes.object }; render() { const {msg} = this.props; return ( <div className="profile-page"> <Helmet title={msg.profile.title} /> <p> {msg.profile.title} </p> </div> ); } }
node_modules/react-icons/ti/messages.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const TiMessages = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m35 11.7h-5c0-2.8-2.2-5-5-5h-20c-2.7 0-5 2.2-5 5v11.6c0 2.8 2.3 5 5 5v5l5-5c0 2.8 2.3 5 5 5h13.3l5 5v-5h1.7c2.8 0 5-2.2 5-5v-11.6c0-2.8-2.2-5-5-5z m-30 13.3c-0.9 0-1.7-0.8-1.7-1.7v-11.6c0-0.9 0.8-1.7 1.7-1.7h20c0.9 0 1.7 0.8 1.7 1.7v1.6h-10.9c-2.3 0-4.1 1.9-4.1 4.2v7.5h-6.7z m31.7 3.3c0 0.9-0.8 1.7-1.7 1.7h-20c-0.9 0-1.7-0.8-1.7-1.7v-10.8c0-1.4 1.2-2.5 2.5-2.5h19.2c0.9 0 1.7 0.8 1.7 1.7v11.6z"/></g> </Icon> ) export default TiMessages
tests/routes/Home/components/HomeView.spec.js
kolyaka006/imaginarium
import React from 'react' import { HomeView } from 'routes/Home/components/HomeView' import { render } from 'enzyme' describe('(View) Home', () => { let _component beforeEach(() => { _component = render(<HomeView />) }) it('Renders a welcome message', () => { const welcome = _component.find('h4') expect(welcome).to.exist() expect(welcome.text()).to.match(/Welcome!/) }) it('Renders an awesome duck image', () => { const duck = _component.find('img') expect(duck).to.exist() expect(duck.attr('alt')).to.match(/This is a duck, because Redux!/) }) })
src/routes/private/layerExample.js
nambawan/g-old
import React from 'react'; import PropTypes from 'prop-types'; import Button from '../../components/Button/Button'; import Layer from '../../components/Layer'; import Box from '../../components/Box'; class LayerExample extends React.Component { constructor() { super(); this.state = { openA: false, openB: false, openFill: false }; } render() { const { children } = this.props; const { openA, openB, openFill } = this.state; return ( <Box> <Button onClick={() => this.setState({ openA: true })}> openA Layer </Button> {openA && ( <Layer onClose={() => this.setState({ openA: false })}> {children} </Layer> )} <Button onClick={() => this.setState({ openB: true })}> openB Layer </Button> {openB && ( <Layer hidden onClose={() => this.setState({ openB: false })}> <Box align> {children} {children} </Box> </Layer> )} <Button onClick={() => this.setState({ openFill: true })}> openFill Layer </Button> {openFill && ( <Layer fill onClose={() => this.setState({ openFill: false })}> {children} </Layer> )} </Box> ); } } LayerExample.propTypes = { children: PropTypes.element.isRequired }; export default LayerExample;
node_modules/styled-components/lib/primitives/index.js
ryotsuchiya/react_card_app
'use strict'; exports.__esModule = true; exports.withTheme = exports.ThemeProvider = exports.css = undefined; var _reactPrimitives = require('react-primitives'); var _reactPrimitives2 = _interopRequireDefault(_reactPrimitives); var _InlineStyle2 = require('../models/InlineStyle'); var _InlineStyle3 = _interopRequireDefault(_InlineStyle2); var _StyledNativeComponent2 = require('../models/StyledNativeComponent'); var _StyledNativeComponent3 = _interopRequireDefault(_StyledNativeComponent2); var _constructWithOptions2 = require('../constructors/constructWithOptions'); var _constructWithOptions3 = _interopRequireDefault(_constructWithOptions2); var _css = require('../constructors/css'); var _css2 = _interopRequireDefault(_css); var _ThemeProvider = require('../models/ThemeProvider'); var _ThemeProvider2 = _interopRequireDefault(_ThemeProvider); var _withTheme = require('../hoc/withTheme'); var _withTheme2 = _interopRequireDefault(_withTheme); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var babelPluginFlowReactPropTypes_proptype_Target = require('../types').babelPluginFlowReactPropTypes_proptype_Target || require('prop-types').any; /* eslint-disable import/no-unresolved */ var constructWithOptions = (0, _constructWithOptions3.default)(_css2.default); var InlineStyle = (0, _InlineStyle3.default)(_reactPrimitives2.default.StyleSheet); var StyledNativeComponent = (0, _StyledNativeComponent3.default)(constructWithOptions, InlineStyle); var styled = function styled(tag) { return constructWithOptions(StyledNativeComponent, tag); }; /* React native lazy-requires each of these modules for some reason, so let's * assume it's for a good reason and not eagerly load them all */ var aliases = 'Image Text Touchable View '; /* Define a getter for each alias which simply gets the reactNative component * and passes it to styled */ aliases.split(/\s+/m).forEach(function (alias) { return Object.defineProperty(styled, alias, { enumerable: true, configurable: false, get: function get() { return styled(_reactPrimitives2.default[alias]); } }); }); exports.css = _css2.default; exports.ThemeProvider = _ThemeProvider2.default; exports.withTheme = _withTheme2.default; exports.default = styled;
src/components/fields/DateField.js
shrimpliu/shradmin
import React from 'react'; import get from 'lodash/get'; import isNull from 'lodash/isNull'; import PropTypes from 'prop-types'; import moment from 'moment'; const DateField = (props) => { const { source, record = {}, elStyle, dateFormat } = props; const value = get(record, source); if(isNull(value)){ return null; }else if(!moment(value).isValid()){ throw new Error(`moment(${value}) is not valid.`); }else{ return <span style={elStyle}>{moment(value).format(dateFormat)}</span>; } }; DateField.propTypes = { elStyle: PropTypes.object, record: PropTypes.object, source: PropTypes.string.isRequired, dateFormat: PropTypes.string }; DateField.defaultProps = { dateFormat: "YYYY-MM-DD HH:mm:ss", }; export default DateField;
src/widgets/PageInfo/PageInfo.js
sussol/mobile
import React from 'react'; import PropTypes from 'prop-types'; import { FlexRow } from '../FlexRow'; import { PageInfoColumn } from './PageInfoColumn'; import { SUSSOL_ORANGE, DARK_GREY } from '../../globalStyles'; /** * A component to display info in a generic way at the top of a page. * @prop {string} titleTextAlign The text align of the title component. * @prop {number} numberOfLines Max number of text lines per row. * @prop {bool} isEditingDisabled Indicator whether all editing is disabled * @prop {string} infoColor Colour of all info components * @prop {string} titleColor Colour of all title components * @prop {array} columns An array containing columns of information to be * displayed, with an entry in the array representing * a column, which is an array of info objects * containing a title and info. * * E.g.: * * [[{title: 'col1:', info: 'row1'}, * {title: 'col1:', info: 'row2'}] * [{title: 'col2:', info: 'row1', * editableType: 'selectable'}, * {title: 'col2:', info: 'row2', * editableType: 'text'}]] * * would display: * * col1: row1 col2: row1 * col1: row2 col2: row2 */ export const PageInfo = React.memo( ({ columns, isEditingDisabled, titleColor, infoColor, numberOfLines, titleTextAlign }) => ( <FlexRow> {columns.map((column, index) => ( <PageInfoColumn // eslint-disable-next-line react/no-array-index-key key={index} titleTextAlign={titleTextAlign} isEditingDisabled={isEditingDisabled} titleColor={titleColor} infoColor={infoColor} columnData={column} numberOfLines={numberOfLines} /> ))} </FlexRow> ) ); PageInfo.defaultProps = { isEditingDisabled: false, titleColor: DARK_GREY, infoColor: SUSSOL_ORANGE, numberOfLines: 1, titleTextAlign: 'left', }; PageInfo.propTypes = { // eslint-disable-next-line react/forbid-prop-types columns: PropTypes.array.isRequired, isEditingDisabled: PropTypes.bool, titleColor: PropTypes.string, infoColor: PropTypes.string, numberOfLines: PropTypes.number, titleTextAlign: PropTypes.string, };
node_modules/react-overlays/lib/Portal.js
vitorgomateus/NotifyMe
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _componentOrElement = require('react-prop-types/lib/componentOrElement'); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _ownerDocument = require('./utils/ownerDocument'); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _getContainer = require('./utils/getContainer'); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ var Portal = _react2.default.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: _react2.default.PropTypes.oneOfType([_componentOrElement2.default, _react2.default.PropTypes.func]) }, componentDidMount: function componentDidMount() { this._renderOverlay(); }, componentDidUpdate: function componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = (0, _getContainer2.default)(nextProps.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount: function componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget: function _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this._portalContainerNode = (0, _getContainer2.default)(this.props.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget: function _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay: function _renderOverlay() { var overlay = !this.props.children ? null : _react2.default.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = _reactDom2.default.unstable_renderSubtreeIntoContainer(this, overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay: function _unrenderOverlay() { if (this._overlayTarget) { _reactDom2.default.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render: function render() { return null; }, getMountNode: function getMountNode() { return this._overlayTarget; }, getOverlayDOMNode: function getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return _reactDom2.default.findDOMNode(this._overlayInstance); } return null; } }); exports.default = Portal; module.exports = exports['default'];
ajax/libs/react/0.12.2/react-with-addons.js
tomsoir/cdnjs
/** * React (with addons) v0.12.2 */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.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);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){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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 = _dereq_("./LinkedStateMixin"); var React = _dereq_("./React"); var ReactComponentWithPureRenderMixin = _dereq_("./ReactComponentWithPureRenderMixin"); var ReactCSSTransitionGroup = _dereq_("./ReactCSSTransitionGroup"); var ReactTransitionGroup = _dereq_("./ReactTransitionGroup"); var ReactUpdates = _dereq_("./ReactUpdates"); var cx = _dereq_("./cx"); var cloneWithProps = _dereq_("./cloneWithProps"); var update = _dereq_("./update"); React.addons = { CSSTransitionGroup: ReactCSSTransitionGroup, LinkedStateMixin: LinkedStateMixin, PureRenderMixin: ReactComponentWithPureRenderMixin, TransitionGroup: ReactTransitionGroup, batchedUpdates: ReactUpdates.batchedUpdates, classSet: cx, cloneWithProps: cloneWithProps, update: update }; if ("production" !== "development") { React.addons.Perf = _dereq_("./ReactDefaultPerf"); React.addons.TestUtils = _dereq_("./ReactTestUtils"); } module.exports = React; },{"./LinkedStateMixin":25,"./React":31,"./ReactCSSTransitionGroup":34,"./ReactComponentWithPureRenderMixin":39,"./ReactDefaultPerf":56,"./ReactTestUtils":86,"./ReactTransitionGroup":90,"./ReactUpdates":91,"./cloneWithProps":113,"./cx":118,"./update":159}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusMixin * @typechecks static-only */ "use strict"; var focusNode = _dereq_("./focusNode"); var AutoFocusMixin = { componentDidMount: function() { if (this.props.autoFocus) { focusNode(this.getDOMNode()); } } }; module.exports = AutoFocusMixin; },{"./focusNode":125}],3:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var SyntheticInputEvent = _dereq_("./SyntheticInputEvent"); var keyOf = _dereq_("./keyOf"); var canUseTextInputEvent = ( ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !('documentMode' in document || isPresto()) ); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return ( typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12 ); } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({onBeforeInput: null}), captured: keyOf({onBeforeInputCapture: null}) }, dependencies: [ topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste ] } }; // Track characters inserted via keypress and composition events. var fallbackChars = null; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return ( (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey) ); } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. */ var BeforeInputEventPlugin = { 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 chars; if (canUseTextInputEvent) { switch (topLevelType) { case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return; } hasSpaceKeypress = true; chars = SPACEBAR_CHAR; break; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return; } // Otherwise, carry on. break; default: // For other native event types, do nothing. return; } } else { switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. fallbackChars = null; break; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { fallbackChars = String.fromCharCode(nativeEvent.which); } break; case topLevelTypes.topCompositionEnd: fallbackChars = nativeEvent.data; break; } // If no changes have occurred to the fallback string, no relevant // event has fired and we're done. if (fallbackChars === null) { return; } chars = fallbackChars; } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return; } var event = SyntheticInputEvent.getPooled( eventTypes.beforeInput, topLevelTargetID, nativeEvent ); event.data = chars; fallbackChars = null; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = BeforeInputEventPlugin; },{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./SyntheticInputEvent":101,"./keyOf":147}],4:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSCore * @typechecks */ var invariant = _dereq_("./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 * @return {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":140}],5:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ "use strict"; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { columnCount: 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, // SVG-related properties fillOpacity: true, strokeOpacity: 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; },{}],6:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations * @typechecks static-only */ "use strict"; var CSSProperty = _dereq_("./CSSProperty"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var camelizeStyleName = _dereq_("./camelizeStyleName"); var dangerousStyleValue = _dereq_("./dangerousStyleValue"); var hyphenateStyleName = _dereq_("./hyphenateStyleName"); var memoizeStringOnly = _dereq_("./memoizeStringOnly"); var warning = _dereq_("./warning"); var processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }); var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("production" !== "development") { var warnedStyleNames = {}; var warnHyphenatedStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; ("production" !== "development" ? warning( false, 'Unsupported style property ' + name + '. Did you mean ' + camelizeStyleName(name) + '?' ) : null); }; } /** * 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. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function(styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("production" !== "development") { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } } 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; } if ("production" !== "development") { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } 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":5,"./ExecutionEnvironment":23,"./camelizeStyleName":112,"./dangerousStyleValue":119,"./hyphenateStyleName":138,"./memoizeStringOnly":149,"./warning":160}],7:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var assign = _dereq_("./Object.assign"); var invariant = _dereq_("./invariant"); /** * 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 `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function(callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * 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 callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { ("production" !== "development" ? invariant( callbacks.length === contexts.length, "Mismatched list of contexts in callback queue" ) : invariant(callbacks.length === contexts.length)); this._callbacks = null; this._contexts = null; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; },{"./Object.assign":29,"./PooledClass":30,"./invariant":140}],8:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var EventPropagators = _dereq_("./EventPropagators"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var ReactUpdates = _dereq_("./ReactUpdates"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var isEventSupported = _dereq_("./isEventSupported"); var isTextInputElement = _dereq_("./isTextInputElement"); var keyOf = _dereq_("./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 ReactBrowserEventEmitter. 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":17,"./EventPluginHub":19,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactUpdates":91,"./SyntheticEvent":99,"./isEventSupported":141,"./isTextInputElement":143,"./keyOf":147}],9:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ "use strict"; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function() { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],10:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CompositionEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var ReactInputSelection = _dereq_("./ReactInputSelection"); var SyntheticCompositionEvent = _dereq_("./SyntheticCompositionEvent"); var getTextContentAccessor = _dereq_("./getTextContentAccessor"); var keyOf = _dereq_("./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 && document.documentMode <= 11 ) ); 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":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactInputSelection":65,"./SyntheticCompositionEvent":97,"./getTextContentAccessor":135,"./keyOf":147}],11:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations * @typechecks static-only */ "use strict"; var Danger = _dereq_("./Danger"); var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes"); var getTextContentAccessor = _dereq_("./getTextContentAccessor"); var invariant = _dereq_("./invariant"); /** * 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) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. parentNode.insertBefore( childNode, parentNode.childNodes[index] || null ); } var updateTextContent; if (textContentAccessor === 'textContent') { /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ updateTextContent = function(node, text) { node.textContent = text; }; } else { /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ 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; ("production" !== "development" ? invariant( updatedChild, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements '+ 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID ) : invariant(updatedChild)); 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":14,"./ReactMultiChildUpdateTypes":72,"./getTextContentAccessor":135,"./invariant":140}],12:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ "use strict"; var invariant = _dereq_("./invariant"); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } 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_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * 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.hasOwnProperty(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.hasOwnProperty(propName))); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; DOMProperty.getPossibleStandardName[attributeName] = propName; DOMProperty.getAttributeName[propName] = attributeName; } else { DOMProperty.getAttributeName[propName] = lowerCased; } DOMProperty.getPropertyName[propName] = DOMPropertyNames.hasOwnProperty(propName) ? DOMPropertyNames[propName] : propName; if (DOMMutationMethods.hasOwnProperty(propName)) { DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; } else { DOMProperty.getMutationMethod[propName] = null; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); DOMProperty.mustUseProperty[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); DOMProperty.hasSideEffects[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); DOMProperty.hasBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); DOMProperty.hasNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); DOMProperty.hasPositiveNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); DOMProperty.hasOverloadedBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_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.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName ) : invariant(!!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1)); } } }; 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 numeric or parse as a * numeric and should be removed when set to a falsey value. * @type {Object} */ hasNumericValue: {}, /** * 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: {}, /** * Whether the property can be used as a flag as well as with a value. Removed * when strictly equal to false; present without a value when strictly equal * to true; present with a value otherwise. * @type {Object} */ hasOverloadedBooleanValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * 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":140}],13:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations * @typechecks static-only */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); var memoizeStringOnly = _dereq_("./memoizeStringOnly"); var warning = _dereq_("./warning"); function shouldIgnoreValue(name, value) { return value == null || (DOMProperty.hasBooleanValue[name] && !value) || (DOMProperty.hasNumericValue[name] && isNaN(value)) || (DOMProperty.hasPositiveNumericValue[name] && (value < 1)) || (DOMProperty.hasOverloadedBooleanValue[name] && value === false); } 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.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(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.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null ); // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. ("production" !== "development" ? warning( standardName == null, 'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?' ) : null); }; } /** * 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.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { if (shouldIgnoreValue(name, value)) { return ''; } var attributeName = DOMProperty.getAttributeName[name]; if (DOMProperty.hasBooleanValue[name] || (DOMProperty.hasOverloadedBooleanValue[name] && value === true)) { 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.hasOwnProperty(name) && 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]) { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. node.setAttribute(DOMProperty.getAttributeName[name], '' + value); } else { var propName = DOMProperty.getPropertyName[name]; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== ('' + value)) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { node.removeAttribute(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.hasOwnProperty(name) && 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, propName ); 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":12,"./escapeTextForBrowser":123,"./memoizeStringOnly":149,"./warning":160}],14:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger * @typechecks static-only */ /*jslint evil: true, sub: true */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var createNodesFromMarkup = _dereq_("./createNodesFromMarkup"); var emptyFunction = _dereq_("./emptyFunction"); var getMarkupWrap = _dereq_("./getMarkupWrap"); var invariant = _dereq_("./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. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : 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. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : 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":23,"./createNodesFromMarkup":117,"./emptyFunction":121,"./getMarkupWrap":132,"./invariant":140}],15:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ "use strict"; var keyOf = _dereq_("./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({BeforeInputEventPlugin: null}), keyOf({AnalyticsEventPlugin: null}), keyOf({MobileSafariClickEventPlugin: null}) ]; module.exports = DefaultEventPluginOrder; },{"./keyOf":147}],16:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent"); var ReactMount = _dereq_("./ReactMount"); var keyOf = _dereq_("./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":17,"./EventPropagators":22,"./ReactMount":70,"./SyntheticMouseEvent":103,"./keyOf":147}],17:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ "use strict"; var keyMirror = _dereq_("./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, topTextInput: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"./keyMirror":146}],18:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventListener * @typechecks */ var emptyFunction = _dereq_("./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('on' + 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); } }; } }, registerDefault: function() {} }; module.exports = EventListener; },{"./emptyFunction":121}],19:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ "use strict"; var EventPluginRegistry = _dereq_("./EventPluginRegistry"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var accumulateInto = _dereq_("./accumulateInto"); var forEachAccumulated = _dereq_("./forEachAccumulated"); var invariant = _dereq_("./invariant"); /** * 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( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); 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 = accumulateInto(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 = accumulateInto(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":20,"./EventPluginUtils":21,"./accumulateInto":109,"./forEachAccumulated":126,"./invariant":140}],20:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry * @typechecks static-only */ "use strict"; var invariant = _dereq_("./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.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(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. You are likely trying to load more than one copy of React.' ) : 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.hasOwnProperty(pluginName) || 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":140}],21:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var invariant = _dereq_("./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 executeDispatchesInOrderStopAtTrueImpl(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; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * 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":17,"./invariant":140}],22:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var accumulateInto = _dereq_("./accumulateInto"); var forEachAccumulated = _dereq_("./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 = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(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 = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(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":17,"./EventPluginHub":19,"./accumulateInto":109,"./forEachAccumulated":126}],23:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); /** * 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), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],24:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); 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_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var hasSVG; if (ExecutionEnvironment.canUseDOM) { var implementation = document.implementation; hasSVG = ( implementation && implementation.hasFeature && implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1' ) ); } var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, acceptCharset: 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, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : 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, coords: null, 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: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formAction: MUST_USE_ATTRIBUTE, formEncType: MUST_USE_ATTRIBUTE, formMethod: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: MUST_USE_ATTRIBUTE, 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: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, manifest: MUST_USE_ATTRIBUTE, marginHeight: null, marginWidth: null, max: null, maxLength: MUST_USE_ATTRIBUTE, media: 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, open: null, 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, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, tabIndex: null, target: null, title: null, type: null, useMap: 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 itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html property: null // Supports OG in meta tags }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', encType: 'enctype', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; },{"./DOMProperty":12,"./ExecutionEnvironment":23}],25:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedStateMixin * @typechecks static-only */ "use strict"; var ReactLink = _dereq_("./ReactLink"); var ReactStateSetters = _dereq_("./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":68,"./ReactStateSetters":85}],26:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils * @typechecks static-only */ "use strict"; var ReactPropTypes = _dereq_("./ReactPropTypes"); var invariant = _dereq_("./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 (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return; } return new Error( 'You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); }, checked: function(props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return; } return new Error( 'You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); }, onChange: 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":79,"./invariant":140}],27:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LocalEventTrapMixin */ "use strict"; var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var accumulateInto = _dereq_("./accumulateInto"); var forEachAccumulated = _dereq_("./forEachAccumulated"); var invariant = _dereq_("./invariant"); function remove(event) { event.remove(); } var LocalEventTrapMixin = { trapBubbledEvent:function(topLevelType, handlerBaseName) { ("production" !== "development" ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted())); var listener = ReactBrowserEventEmitter.trapBubbledEvent( topLevelType, handlerBaseName, this.getDOMNode() ); this._localEventListeners = accumulateInto(this._localEventListeners, listener); }, // trapCapturedEvent would look nearly identical. We don't implement that // method because it isn't currently needed. componentWillUnmount:function() { if (this._localEventListeners) { forEachAccumulated(this._localEventListeners, remove); } } }; module.exports = LocalEventTrapMixin; },{"./ReactBrowserEventEmitter":33,"./accumulateInto":109,"./forEachAccumulated":126,"./invariant":140}],28:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule MobileSafariClickEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var emptyFunction = _dereq_("./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":17,"./emptyFunction":121}],29:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; }; module.exports = assign; },{}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ "use strict"; var invariant = _dereq_("./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":140}],31:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ "use strict"; var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var ReactChildren = _dereq_("./ReactChildren"); var ReactComponent = _dereq_("./ReactComponent"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactContext = _dereq_("./ReactContext"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactElement = _dereq_("./ReactElement"); var ReactElementValidator = _dereq_("./ReactElementValidator"); var ReactDOM = _dereq_("./ReactDOM"); var ReactDOMComponent = _dereq_("./ReactDOMComponent"); var ReactDefaultInjection = _dereq_("./ReactDefaultInjection"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactLegacyElement = _dereq_("./ReactLegacyElement"); var ReactMount = _dereq_("./ReactMount"); var ReactMultiChild = _dereq_("./ReactMultiChild"); var ReactPerf = _dereq_("./ReactPerf"); var ReactPropTypes = _dereq_("./ReactPropTypes"); var ReactServerRendering = _dereq_("./ReactServerRendering"); var ReactTextComponent = _dereq_("./ReactTextComponent"); var assign = _dereq_("./Object.assign"); var deprecated = _dereq_("./deprecated"); var onlyChild = _dereq_("./onlyChild"); ReactDefaultInjection.inject(); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; if ("production" !== "development") { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; } // TODO: Drop legacy elements once classes no longer export these factories createElement = ReactLegacyElement.wrapCreateElement( createElement ); createFactory = ReactLegacyElement.wrapCreateFactory( createFactory ); var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, only: onlyChild }, DOM: ReactDOM, PropTypes: ReactPropTypes, initializeTouchEvents: function(shouldUseTouch) { EventPluginUtils.useTouchEvents = shouldUseTouch; }, createClass: ReactCompositeComponent.createClass, createElement: createElement, createFactory: createFactory, constructAndRenderComponent: ReactMount.constructAndRenderComponent, constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID, render: render, renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, unmountComponentAtNode: ReactMount.unmountComponentAtNode, isValidClass: ReactLegacyElement.isValidClass, isValidElement: ReactElement.isValidElement, withContext: ReactContext.withContext, // Hook for JSX spread, don't use this for anything else. __spread: assign, // Deprecations (remove for 0.13) renderComponent: deprecated( 'React', 'renderComponent', 'render', this, render ), renderComponentToString: deprecated( 'React', 'renderComponentToString', 'renderToString', this, ReactServerRendering.renderToString ), renderComponentToStaticMarkup: deprecated( 'React', 'renderComponentToStaticMarkup', 'renderToStaticMarkup', this, ReactServerRendering.renderToStaticMarkup ), isValidComponent: deprecated( 'React', 'isValidComponent', 'isValidElement', this, ReactElement.isValidElement ) }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ Component: ReactComponent, CurrentOwner: ReactCurrentOwner, DOMComponent: ReactDOMComponent, DOMPropertyOperations: DOMPropertyOperations, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, MultiChild: ReactMultiChild, TextComponent: ReactTextComponent }); } if ("production" !== "development") { var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // If we're in Chrome, look for the devtools marker and provide a download // link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { console.debug( 'Download the React DevTools for a better development experience: ' + 'http://fb.me/react-devtools' ); } } var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze ]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error( 'One or more ES5 shim/shams expected by React are not available: ' + 'http://fb.me/react-warning-polyfills' ); break; } } } } // Version exists only in the open-source version of React, not in Facebook's // internal version. React.version = '0.12.2'; module.exports = React; },{"./DOMPropertyOperations":13,"./EventPluginUtils":21,"./ExecutionEnvironment":23,"./Object.assign":29,"./ReactChildren":36,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactDOM":43,"./ReactDOMComponent":45,"./ReactDefaultInjection":55,"./ReactElement":58,"./ReactElementValidator":59,"./ReactInstanceHandles":66,"./ReactLegacyElement":67,"./ReactMount":70,"./ReactMultiChild":71,"./ReactPerf":75,"./ReactPropTypes":79,"./ReactServerRendering":83,"./ReactTextComponent":87,"./deprecated":120,"./onlyChild":151}],32:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserComponentMixin */ "use strict"; var ReactEmptyComponent = _dereq_("./ReactEmptyComponent"); var ReactMount = _dereq_("./ReactMount"); var invariant = _dereq_("./invariant"); var ReactBrowserComponentMixin = { /** * 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())); if (ReactEmptyComponent.isNullComponentID(this._rootNodeID)) { return null; } return ReactMount.getNode(this._rootNodeID); } }; module.exports = ReactBrowserComponentMixin; },{"./ReactEmptyComponent":60,"./ReactMount":70,"./invariant":140}],33:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var EventPluginRegistry = _dereq_("./EventPluginRegistry"); var ReactEventEmitterMixin = _dereq_("./ReactEventEmitterMixin"); var ViewportMetrics = _dereq_("./ViewportMetrics"); var assign = _dereq_("./Object.assign"); var isEventSupported = _dereq_("./isEventSupported"); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - 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 | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|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', topTextInput: 'textInput', 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) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.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 {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; 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.hasOwnProperty(dependency) && isListening[dependency] )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.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 ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.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 ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.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.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * 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; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter; },{"./EventConstants":17,"./EventPluginHub":19,"./EventPluginRegistry":20,"./Object.assign":29,"./ReactEventEmitterMixin":62,"./ViewportMetrics":108,"./isEventSupported":141}],34:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, 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. * * @typechecks * @providesModule ReactCSSTransitionGroup */ "use strict"; var React = _dereq_("./React"); var assign = _dereq_("./Object.assign"); var ReactTransitionGroup = React.createFactory( _dereq_("./ReactTransitionGroup") ); var ReactCSSTransitionGroupChild = React.createFactory( _dereq_("./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 ( ReactTransitionGroup( assign({}, this.props, {childFactory: this._wrapChild}) ) ); } }); module.exports = ReactCSSTransitionGroup; },{"./Object.assign":29,"./React":31,"./ReactCSSTransitionGroupChild":35,"./ReactTransitionGroup":90}],35:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, 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. * * @typechecks * @providesModule ReactCSSTransitionGroupChild */ "use strict"; var React = _dereq_("./React"); var CSSCore = _dereq_("./CSSCore"); var ReactTransitionEvents = _dereq_("./ReactTransitionEvents"); var onlyChild = _dereq_("./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({ displayName: 'ReactCSSTransitionGroupChild', transition: function(animationType, finishCallback) { var node = this.getDOMNode(); var className = this.props.name + '-' + animationType; var activeClassName = className + '-active'; var noEventTimeout = null; var endListener = function(e) { if (e && e.target !== node) { return; } 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.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":4,"./React":31,"./ReactTransitionEvents":89,"./onlyChild":151}],36:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var traverseAllChildren = _dereq_("./traverseAllChildren"); var warning = _dereq_("./warning"); 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 keyUnique = !mapResult.hasOwnProperty(name); ("production" !== "development" ? warning( keyUnique, 'ReactChildren.map(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); if (keyUnique) { var mappedChild = mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i); 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; } function forEachSingleChildDummy(traverseContext, child, name, i) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } var ReactChildren = { forEach: forEachChildren, map: mapChildren, count: countChildren }; module.exports = ReactChildren; },{"./PooledClass":30,"./traverseAllChildren":158,"./warning":160}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactOwner = _dereq_("./ReactOwner"); var ReactUpdates = _dereq_("./ReactUpdates"); var assign = _dereq_("./Object.assign"); var invariant = _dereq_("./invariant"); var keyMirror = _dereq_("./keyMirror"); /** * 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 }); var injected = false; /** * 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 */ var unmountIDFromEnvironment = null; /** * 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 */ var mountImageIntoNode = null; /** * 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 = { injection: { injectEnvironment: function(ReactComponentEnvironment) { ("production" !== "development" ? invariant( !injected, 'ReactComponent: injectEnvironment() can only be called once.' ) : invariant(!injected)); mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode; unmountIDFromEnvironment = ReactComponentEnvironment.unmountIDFromEnvironment; ReactComponent.BackendIDOperations = ReactComponentEnvironment.BackendIDOperations; injected = true; } }, /** * @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: null, /** * Base functionality for every ReactComponent constructor. Mixed into the * `ReactComponent` prototype, but exposed statically for easy access. * * @lends {ReactComponent.prototype} */ 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 the pending element if it exists, otherwise with existing // element props. var element = this._pendingElement || this._currentElement; this.replaceProps( assign({}, element.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 is a deoptimized path. We optimize for always having a element. // This creates an extra internal element. this._pendingElement = ReactElement.cloneAndReplaceProps( this._pendingElement || this._currentElement, props ); ReactUpdates.enqueueUpdate(this, callback); }, /** * Schedule a partial update to the props. Only used for internal testing. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @internal */ _setPropsInternal: function(partialProps, callback) { // This is a deoptimized path. We optimize for always having a element. // This creates an extra internal element. var element = this._pendingElement || this._currentElement; this._pendingElement = ReactElement.cloneAndReplaceProps( element, assign({}, element.props, partialProps) ); 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 {ReactElement} element * @internal */ construct: function(element) { // This is the public exposed props object after it has been processed // with default props. The element's props represents the true internal // state of the props. this.props = element.props; // Record the component responsible for creating this component. // This is accessible through the element but we maintain an extra // field for compatibility with devtools and as a way to make an // incremental update. TODO: Consider deprecating this field. this._owner = element._owner; // All components start unmounted. this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; // See ReactUpdates. this._pendingCallbacks = null; // We keep the old element and a reference to the pending element // to track updates. this._currentElement = element; this._pendingElement = null; }, /** * 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|ReactServerRenderingTransaction} 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 ref = this._currentElement.ref; if (ref != null) { var owner = this._currentElement._owner; ReactOwner.addComponentAsRefTo(this, ref, 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 ref = this._currentElement.ref; if (ref != null) { ReactOwner.removeComponentAsRefFrom(this, ref, this._owner); } 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(nextElement, transaction) { ("production" !== "development" ? invariant( this.isMounted(), 'receiveComponent(...): Can only update a mounted component.' ) : invariant(this.isMounted())); this._pendingElement = nextElement; this.performUpdateIfNecessary(transaction); }, /** * If `_pendingElement` is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { if (this._pendingElement == null) { return; } var prevElement = this._currentElement; var nextElement = this._pendingElement; this._currentElement = nextElement; this.props = nextElement.props; this._owner = nextElement._owner; this._pendingElement = null; this.updateComponent(transaction, prevElement); }, /** * Updates the component's currently mounted representation. * * @param {ReactReconcileTransaction} transaction * @param {object} prevElement * @internal */ updateComponent: function(transaction, prevElement) { var nextElement = this._currentElement; // 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`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. if (nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref) { if (prevElement.ref != null) { ReactOwner.removeComponentAsRefFrom( this, prevElement.ref, prevElement._owner ); } // Correct, even if the owner is the same, and only the ref has changed. if (nextElement.ref != null) { ReactOwner.addComponentAsRefTo( this, nextElement.ref, nextElement._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.render} */ mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( this._mountComponentIntoNode, this, rootID, container, transaction, shouldReuseMarkup ); ReactUpdates.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); 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; },{"./Object.assign":29,"./ReactElement":58,"./ReactOwner":74,"./ReactUpdates":91,"./invariant":140,"./keyMirror":146}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ /*jslint evil: true */ "use strict"; var ReactDOMIDOperations = _dereq_("./ReactDOMIDOperations"); var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum"); var ReactMount = _dereq_("./ReactMount"); var ReactPerf = _dereq_("./ReactPerf"); var ReactReconcileTransaction = _dereq_("./ReactReconcileTransaction"); var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer"); var invariant = _dereq_("./invariant"); var setInnerHTML = _dereq_("./setInnerHTML"); var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** * Abstracts away all functionality of `ReactComponent` requires knowledge of * the browser context. */ var ReactComponentBrowserEnvironment = { 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)); setInnerHTML(container, markup); } ) }; module.exports = ReactComponentBrowserEnvironment; },{"./ReactDOMIDOperations":47,"./ReactMarkupChecksum":69,"./ReactMount":70,"./ReactPerf":75,"./ReactReconcileTransaction":81,"./getReactRootElementInContainer":134,"./invariant":140,"./setInnerHTML":154}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ "use strict"; var shallowEqual = _dereq_("./shallowEqual"); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this Mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; },{"./shallowEqual":155}],40:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var ReactContext = _dereq_("./ReactContext"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactElement = _dereq_("./ReactElement"); var ReactElementValidator = _dereq_("./ReactElementValidator"); var ReactEmptyComponent = _dereq_("./ReactEmptyComponent"); var ReactErrorUtils = _dereq_("./ReactErrorUtils"); var ReactLegacyElement = _dereq_("./ReactLegacyElement"); var ReactOwner = _dereq_("./ReactOwner"); var ReactPerf = _dereq_("./ReactPerf"); var ReactPropTransferer = _dereq_("./ReactPropTransferer"); var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames"); var ReactUpdates = _dereq_("./ReactUpdates"); var assign = _dereq_("./Object.assign"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var invariant = _dereq_("./invariant"); var keyMirror = _dereq_("./keyMirror"); var keyOf = _dereq_("./keyOf"); var monitorCodeUse = _dereq_("./monitorCodeUse"); var mapObject = _dereq_("./mapObject"); var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent"); var warning = _dereq_("./warning"); var MIXINS_KEY = keyOf({mixins: null}); /** * 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 }); var injectedMixins = []; /** * 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(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) { validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); Constructor.childContextTypes = assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.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) { validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); Constructor.propTypes = assign( {}, Constructor.propTypes, propTypes ); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); } }; function getDeclarationErrorAddendum(component) { var owner = component._owner || null; if (owner && owner.constructor && owner.constructor.displayName) { return ' Check the render method of `' + owner.constructor.displayName + '`.'; } return ''; } 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.hasOwnProperty(name) ? ReactCompositeComponentInterface[name] : null; // 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( ReactCurrentOwner.current == null, 'replaceState(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.' ) : invariant(ReactCurrentOwner.current == null)); ("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)); } /** * Mixin helper which handles policy validation and reserved * specification keys when building `ReactCompositeComponent` classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } ("production" !== "development" ? invariant( !ReactLegacyElement.isValidFactory(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(!ReactLegacyElement.isValidFactory(spec))); ("production" !== "development" ? invariant( !ReactElement.isValidElement(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactElement.isValidElement(spec))); var proto = Constructor.prototype; // 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]; validateMethodOverride(proto, 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 ReactCompositeComponent methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isCompositeComponentMethod = ReactCompositeComponentInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isCompositeComponentMethod && !isAlreadyDefined && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactCompositeComponentInterface[name]; // These cases should already be caught by validateMethodOverride ("production" !== "development" ? invariant( isCompositeComponentMethod && ( specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY ), 'ReactCompositeComponent: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ) : invariant(isCompositeComponentMethod && ( specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY ))); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("production" !== "development") { // 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; ("production" !== "development" ? invariant( !isReserved, 'ReactCompositeComponent: 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 ) : invariant(!isReserved)); var isInherited = name in Constructor; ("production" !== "development" ? invariant( !isInherited, 'ReactCompositeComponent: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ) : invariant(!isInherited)); 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 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')); mapObject(two, function(value, key) { ("production" !== "development" ? invariant( one[key] === undefined, 'mergeObjectsWithNoDuplicateKeys(): ' + '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 ) : 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); }; } /** * `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-|RECEIVE|-0-| UN |--->0 | * | | | |PROPS | |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 }); /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function(element) { // Children can be either an array or more than one argument ReactComponent.Mixin.construct.apply(this, arguments); ReactOwner.Mixin.construct.apply(this, arguments); this.state = null; this._pendingState = null; // This is the public post-processed context. The real context and pending // context lives on the element. this.context = 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|ReactServerRenderingTransaction} 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; if (this.__reactAutoBindMap) { this._bindAutoBindMethods(); } this.context = this._processContext(this._currentElement._context); this.props = this._processProps(this.props); 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 = instantiateReactComponent( this._renderValidatedComponent(), this._currentElement.type // The wrapping type ); // 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.componentDidMount, this); } 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._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); // 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"){ ("production" !== "development" ? warning( partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ) : null); } // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( assign({}, 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; if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) { // If we're in a componentWillMount handler, don't enqueue a rerender // because ReactUpdates assumes we're in a browser context (which is wrong // for server rendering) and we're about to do a render anyway. // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. 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 assign({}, 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) { if ("production" !== "development") { var propTypes = this.constructor.propTypes; if (propTypes) { this._checkPropTypes(propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * 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) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.constructor.displayName; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName, location); if (error instanceof Error) { // We may want to extend this logic for similar errors in // renderComponent calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); ("production" !== "development" ? warning(false, error.message + addendum) : null); } } } }, /** * If any of `_pendingElement`, `_pendingState`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { 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; } if (this._pendingElement == null && this._pendingState == null && !this._pendingForceUpdate) { return; } var nextContext = this.context; var nextProps = this.props; var nextElement = this._currentElement; if (this._pendingElement != null) { nextElement = this._pendingElement; nextContext = this._processContext(nextElement._context); nextProps = this._processProps(nextElement.props); this._pendingElement = null; this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS; if (this.componentWillReceiveProps) { this.componentWillReceiveProps(nextProps, nextContext); } } this._compositeLifeCycleState = null; var nextState = this._pendingState || this.state; this._pendingState = null; var shouldUpdate = this._pendingForceUpdate || !this.shouldComponentUpdate || this.shouldComponentUpdate(nextProps, nextState, nextContext); if ("production" !== "development") { if (typeof shouldUpdate === "undefined") { console.warn( (this.constructor.displayName || 'ReactCompositeComponent') + '.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.' ); } } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( nextElement, nextProps, nextState, nextContext, transaction ); } else { // If it's determined that a component should not update, we still want // to set props and state. this._currentElement = nextElement; this.props = nextProps; this.state = nextState; this.context = nextContext; // Owner cannot change because shouldUpdateReactComponent doesn't allow // it. TODO: Remove this._owner completely. this._owner = nextElement._owner; } }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @private */ _performComponentUpdate: function( nextElement, nextProps, nextState, nextContext, transaction ) { var prevElement = this._currentElement; var prevProps = this.props; var prevState = this.state; var prevContext = this.context; if (this.componentWillUpdate) { this.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this.props = nextProps; this.state = nextState; this.context = nextContext; // Owner cannot change because shouldUpdateReactComponent doesn't allow // it. TODO: Remove this._owner completely. this._owner = nextElement._owner; this.updateComponent( transaction, prevElement ); if (this.componentDidUpdate) { transaction.getReactMountReady().enqueue( this.componentDidUpdate.bind(this, prevProps, prevState, prevContext), this ); } }, receiveComponent: function(nextElement, transaction) { if (nextElement === this._currentElement && nextElement._owner != null) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for a element created outside a composite to be // deeply mutated and reused. return; } ReactComponent.Mixin.receiveComponent.call( this, nextElement, 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 {ReactElement} prevElement * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactCompositeComponent', 'updateComponent', function(transaction, prevParentElement) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevParentElement ); var prevComponentInstance = this._renderedComponent; var prevElement = prevComponentInstance._currentElement; var nextElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevElement, nextElement)) { prevComponentInstance.receiveComponent(nextElement, transaction); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; prevComponentInstance.unmountComponent(); this._renderedComponent = instantiateReactComponent( nextElement, this._currentElement.type ); var nextMarkup = this._renderedComponent.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.UNMOUNTING && ReactCurrentOwner.current == null, 'forceUpdate(...): Cannot force an update while unmounting component ' + 'or within a `render` function.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING && ReactCurrentOwner.current == null)); 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._currentElement._context ); ReactCurrentOwner.current = this; try { renderedComponent = this.render(); if (renderedComponent === null || renderedComponent === false) { renderedComponent = ReactEmptyComponent.getEmptyComponent(); ReactEmptyComponent.registerNullComponentID(this._rootNodeID); } else { ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID); } } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== "development" ? invariant( ReactElement.isValidElement(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(ReactElement.isValidElement(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 = method.bind(component); 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 ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); // 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) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): React component methods may only be bound to the ' + 'component instance. See ' + componentName ); } else if (!args.length) { monitorCodeUse('react_bind_warning', { component: componentName }); 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() {}; assign( ReactCompositeComponentBase.prototype, ReactComponent.Mixin, ReactOwner.Mixin, ReactPropTransferer.Mixin, ReactCompositeComponentMixin ); /** * 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(props) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. This will later be used // by the stand-alone class implementation. }; Constructor.prototype = new ReactCompositeComponentBase(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } ("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) { monitorCodeUse( 'react_component_should_update_warning', { component: spec.displayName } ); 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.' ); } } // 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") { return ReactLegacyElement.wrapFactory( ReactElementValidator.createFactory(Constructor) ); } return ReactLegacyElement.wrapFactory( ReactElement.createFactory(Constructor) ); }, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactCompositeComponent; },{"./Object.assign":29,"./ReactComponent":37,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactElement":58,"./ReactElementValidator":59,"./ReactEmptyComponent":60,"./ReactErrorUtils":61,"./ReactLegacyElement":67,"./ReactOwner":74,"./ReactPerf":75,"./ReactPropTransferer":76,"./ReactPropTypeLocationNames":77,"./ReactPropTypeLocations":78,"./ReactUpdates":91,"./instantiateReactComponent":139,"./invariant":140,"./keyMirror":146,"./keyOf":147,"./mapObject":148,"./monitorCodeUse":150,"./shouldUpdateReactComponent":156,"./warning":160}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ "use strict"; var assign = _dereq_("./Object.assign"); /** * 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 = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; },{"./Object.assign":29}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM * @typechecks static-only */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactElementValidator = _dereq_("./ReactElementValidator"); var ReactLegacyElement = _dereq_("./ReactLegacyElement"); var mapObject = _dereq_("./mapObject"); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if ("production" !== "development") { return ReactLegacyElement.markNonLegacyFactory( ReactElementValidator.createFactory(tag) ); } return ReactLegacyElement.markNonLegacyFactory( ReactElement.createFactory(tag) ); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOM = mapObject({ 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', 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', // SVG circle: 'circle', defs: 'defs', ellipse: 'ellipse', g: 'g', 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' }, createDOMFactory); module.exports = ReactDOM; },{"./ReactElement":58,"./ReactElementValidator":59,"./ReactLegacyElement":67,"./mapObject":148}],44:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); var keyMirror = _dereq_("./keyMirror"); // Store a reference to the <button> `ReactDOMComponent`. TODO: use string var button = ReactElement.createFactory(ReactDOM.button.type); 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, ReactBrowserComponentMixin], 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":2,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./keyMirror":146}],45:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent * @typechecks static-only */ "use strict"; var CSSPropertyOperations = _dereq_("./CSSPropertyOperations"); var DOMProperty = _dereq_("./DOMProperty"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactComponent = _dereq_("./ReactComponent"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var ReactMount = _dereq_("./ReactMount"); var ReactMultiChild = _dereq_("./ReactMultiChild"); var ReactPerf = _dereq_("./ReactPerf"); var assign = _dereq_("./Object.assign"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); var invariant = _dereq_("./invariant"); var isEventSupported = _dereq_("./isEventSupported"); var keyOf = _dereq_("./keyOf"); var monitorCodeUse = _dereq_("./monitorCodeUse"); var deleteListener = ReactBrowserEventEmitter.deleteListener; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = ReactBrowserEventEmitter.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)); if ("production" !== "development") { if (props.contentEditable && props.children != null) { console.warn( 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of those '+ 'nodes are unexpectedly modified or duplicated. This is probably not ' + 'intentional.' ); } } ("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) { if ("production" !== "development") { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. if (registrationName === 'onScroll' && !isEventSupported('scroll', true)) { monitorCodeUse('react_no_scroll_event'); console.warn('This browser doesn\'t support the `onScroll` event'); } } 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 ); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // We accept any tag to be rendered but since this gets injected into abitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { ("production" !== "development" ? invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag) : invariant(VALID_TAG_REGEX.test(tag))); validatedTagCache[tag] = true; } } /** * 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. * * @constructor ReactDOMComponent * @extends ReactComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag; this.tagName = tag.toUpperCase(); } ReactDOMComponent.displayName = 'ReactDOMComponent'; 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|ReactServerRenderingTransaction} 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); var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>'; return ( this._createOpenTagMarkupAndPutListeners(transaction) + this._createContentMarkup(transaction) + closeTag ); } ), /** * 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|ReactServerRenderingTransaction} transaction * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction) { var props = this.props; var ret = '<' + this._tag; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { putListener(this._rootNodeID, propKey, propValue, transaction); } else { if (propKey === STYLE) { if (propValue) { propValue = props.style = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret + '>'; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID + '>'; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} 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(nextElement, transaction) { if (nextElement === this._currentElement && nextElement._owner != null) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for a element created outside a composite to be // deeply mutated and reused. return; } ReactComponent.Mixin.receiveComponent.call( this, nextElement, 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 {ReactElement} prevElement * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactDOMComponent', 'updateComponent', function(transaction, prevElement) { assertValidProps(this._currentElement.props); ReactComponent.Mixin.updateComponent.call( this, transaction, prevElement ); this._updateDOMProperties(prevElement.props, transaction); this._updateDOMChildren(prevElement.props, 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.hasOwnProperty(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 = assign({}, nextProp); } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !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.hasOwnProperty(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(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponent.Mixin.unmountComponent.call(this); } }; assign( ReactDOMComponent.prototype, ReactComponent.Mixin, ReactDOMComponent.Mixin, ReactMultiChild.Mixin, ReactBrowserComponentMixin ); module.exports = ReactDOMComponent; },{"./CSSPropertyOperations":6,"./DOMProperty":12,"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactMount":70,"./ReactMultiChild":71,"./ReactPerf":75,"./escapeTextForBrowser":123,"./invariant":140,"./isEventSupported":141,"./keyOf":147,"./monitorCodeUse":150}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMForm */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); // Store a reference to the <form> `ReactDOMComponent`. TODO: use string var form = ReactElement.createFactory(ReactDOM.form.type); /** * 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', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], 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 form(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset'); this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit'); } }); module.exports = ReactDOMForm; },{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58}],47:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ /*jslint evil: true */ "use strict"; var CSSPropertyOperations = _dereq_("./CSSPropertyOperations"); var DOMChildrenOperations = _dereq_("./DOMChildrenOperations"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var ReactMount = _dereq_("./ReactMount"); var ReactPerf = _dereq_("./ReactPerf"); var invariant = _dereq_("./invariant"); var setInnerHTML = _dereq_("./setInnerHTML"); /** * 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()`.' }; /** * 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); setInnerHTML(node, 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":6,"./DOMChildrenOperations":11,"./DOMPropertyOperations":13,"./ReactMount":70,"./ReactPerf":75,"./invariant":140,"./setInnerHTML":154}],48:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMImg */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); // Store a reference to the <img> `ReactDOMComponent`. TODO: use string var img = ReactElement.createFactory(ReactDOM.img.type); /** * 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', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { return img(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load'); this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error'); } }); module.exports = ReactDOMImg; },{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var LinkedValueUtils = _dereq_("./LinkedValueUtils"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); var ReactMount = _dereq_("./ReactMount"); var ReactUpdates = _dereq_("./ReactUpdates"); var assign = _dereq_("./Object.assign"); var invariant = _dereq_("./invariant"); // Store a reference to the <input> `ReactDOMComponent`. TODO: use string var input = ReactElement.createFactory(ReactDOM.input.type); var instancesByReactID = {}; function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * 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, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; return { initialChecked: this.props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.defaultChecked = null; props.defaultValue = null; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.initialValue; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.initialChecked; 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) { returnValue = onChange.call(this, event); } // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); 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)); // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } }); module.exports = ReactDOMInput; },{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./ReactMount":70,"./ReactUpdates":91,"./invariant":140}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ "use strict"; var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); var warning = _dereq_("./warning"); // Store a reference to the <option> `ReactDOMComponent`. TODO: use string var option = ReactElement.createFactory(ReactDOM.option.type); /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = ReactCompositeComponent.createClass({ displayName: 'ReactDOMOption', mixins: [ReactBrowserComponentMixin], componentWillMount: function() { // TODO (yungsters): Remove support for `selected` in <option>. if ("production" !== "development") { ("production" !== "development" ? warning( this.props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ) : null); } }, render: function() { return option(this.props, this.props.children); } }); module.exports = ReactDOMOption; },{"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./warning":160}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var LinkedValueUtils = _dereq_("./LinkedValueUtils"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); var ReactUpdates = _dereq_("./ReactUpdates"); var assign = _dereq_("./Object.assign"); // Store a reference to the <select> `ReactDOMComponent`. TODO: use string var select = ReactElement.createFactory(ReactDOM.select.type); function updateWithPendingValueIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.setState({value: this._pendingValue}); this._pendingValue = 0; } } /** * Validation function for `value` and `defaultValue`. * @private */ function selectValueType(props, propName, componentName) { if (props[propName] == null) { return; } if (props.multiple) { if (!Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be an array if ") + ("`multiple` is true.") ); } } else { if (Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be a scalar ") + ("value if `multiple` is false.") ); } } } /** * 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, ReactBrowserComponentMixin], propTypes: { defaultValue: selectValueType, value: selectValueType }, getInitialState: function() { return {value: this.props.defaultValue || (this.props.multiple ? [] : '')}; }, componentWillMount: function() { this._pendingValue = null; }, 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]}); } }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.onChange = this._handleChange; props.value = null; return select(props, this.props.children); }, componentDidMount: function() { updateOptions(this, LinkedValueUtils.getValue(this)); }, componentDidUpdate: function(prevProps) { var value = LinkedValueUtils.getValue(this); var prevMultiple = !!prevProps.multiple; var multiple = !!this.props.multiple; if (value != null || prevMultiple !== multiple) { updateOptions(this, value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } 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._pendingValue = selectedValue; ReactUpdates.asap(updateWithPendingValueIfMounted, this); return returnValue; } }); module.exports = ReactDOMSelect; },{"./AutoFocusMixin":2,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./ReactUpdates":91}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var getNodeForCharacterOffset = _dereq_("./getNodeForCharacterOffset"); var getTextContentAccessor = _dereq_("./getTextContentAccessor"); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * 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 && window.getSelection(); if (!selection || 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); // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed( selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset ); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed( tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset ); var start = isTempRangeCollapsed ? 0 : 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; 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) { if (!window.getSelection) { return; } 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); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && document.selection; var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"./ExecutionEnvironment":23,"./getNodeForCharacterOffset":133,"./getTextContentAccessor":135}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var LinkedValueUtils = _dereq_("./LinkedValueUtils"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var ReactDOM = _dereq_("./ReactDOM"); var ReactUpdates = _dereq_("./ReactUpdates"); var assign = _dereq_("./Object.assign"); var invariant = _dereq_("./invariant"); var warning = _dereq_("./warning"); // Store a reference to the <textarea> `ReactDOMComponent`. TODO: use string var textarea = ReactElement.createFactory(ReactDOM.textarea.type); function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * 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, ReactBrowserComponentMixin], 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") { ("production" !== "development" ? warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.' ) : null); } ("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) }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); ("production" !== "development" ? invariant( props.dangerouslySetInnerHTML == null, '`dangerouslySetInnerHTML` does not make sense on <textarea>.' ) : invariant(props.dangerouslySetInnerHTML == null)); props.defaultValue = null; props.value = null; 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) { returnValue = onChange.call(this, event); } ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } }); module.exports = ReactDOMTextarea; },{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./ReactUpdates":91,"./invariant":140,"./warning":160}],54:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ "use strict"; var ReactUpdates = _dereq_("./ReactUpdates"); var Transaction = _dereq_("./Transaction"); var assign = _dereq_("./Object.assign"); var emptyFunction = _dereq_("./emptyFunction"); 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(); } assign( ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { 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, a, b) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b); } else { transaction.perform(callback, null, a, b); } } }; module.exports = ReactDefaultBatchingStrategy; },{"./Object.assign":29,"./ReactUpdates":91,"./Transaction":107,"./emptyFunction":121}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ "use strict"; var BeforeInputEventPlugin = _dereq_("./BeforeInputEventPlugin"); var ChangeEventPlugin = _dereq_("./ChangeEventPlugin"); var ClientReactRootIndex = _dereq_("./ClientReactRootIndex"); var CompositionEventPlugin = _dereq_("./CompositionEventPlugin"); var DefaultEventPluginOrder = _dereq_("./DefaultEventPluginOrder"); var EnterLeaveEventPlugin = _dereq_("./EnterLeaveEventPlugin"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var HTMLDOMPropertyConfig = _dereq_("./HTMLDOMPropertyConfig"); var MobileSafariClickEventPlugin = _dereq_("./MobileSafariClickEventPlugin"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactComponentBrowserEnvironment = _dereq_("./ReactComponentBrowserEnvironment"); var ReactDefaultBatchingStrategy = _dereq_("./ReactDefaultBatchingStrategy"); var ReactDOMComponent = _dereq_("./ReactDOMComponent"); var ReactDOMButton = _dereq_("./ReactDOMButton"); var ReactDOMForm = _dereq_("./ReactDOMForm"); var ReactDOMImg = _dereq_("./ReactDOMImg"); var ReactDOMInput = _dereq_("./ReactDOMInput"); var ReactDOMOption = _dereq_("./ReactDOMOption"); var ReactDOMSelect = _dereq_("./ReactDOMSelect"); var ReactDOMTextarea = _dereq_("./ReactDOMTextarea"); var ReactEventListener = _dereq_("./ReactEventListener"); var ReactInjection = _dereq_("./ReactInjection"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMount = _dereq_("./ReactMount"); var SelectEventPlugin = _dereq_("./SelectEventPlugin"); var ServerReactRootIndex = _dereq_("./ServerReactRootIndex"); var SimpleEventPlugin = _dereq_("./SimpleEventPlugin"); var SVGDOMPropertyConfig = _dereq_("./SVGDOMPropertyConfig"); var createFullPageComponent = _dereq_("./createFullPageComponent"); function inject() { ReactInjection.EventEmitter.injectReactEventListener( ReactEventListener ); /** * 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, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass( ReactDOMComponent ); ReactInjection.NativeComponent.injectComponentClasses({ 'button': ReactDOMButton, 'form': ReactDOMForm, 'img': ReactDOMImg, 'input': ReactDOMInput, 'option': ReactDOMOption, 'select': ReactDOMSelect, 'textarea': ReactDOMTextarea, 'html': createFullPageComponent('html'), 'head': createFullPageComponent('head'), 'body': createFullPageComponent('body') }); // This needs to happen after createFullPageComponent() otherwise the mixin // gets double injected. ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction( ReactComponentBrowserEnvironment.ReactReconcileTransaction ); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if ("production" !== "development") { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = _dereq_("./ReactDefaultPerf"); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; },{"./BeforeInputEventPlugin":3,"./ChangeEventPlugin":8,"./ClientReactRootIndex":9,"./CompositionEventPlugin":10,"./DefaultEventPluginOrder":15,"./EnterLeaveEventPlugin":16,"./ExecutionEnvironment":23,"./HTMLDOMPropertyConfig":24,"./MobileSafariClickEventPlugin":28,"./ReactBrowserComponentMixin":32,"./ReactComponentBrowserEnvironment":38,"./ReactDOMButton":44,"./ReactDOMComponent":45,"./ReactDOMForm":46,"./ReactDOMImg":48,"./ReactDOMInput":49,"./ReactDOMOption":50,"./ReactDOMSelect":51,"./ReactDOMTextarea":53,"./ReactDefaultBatchingStrategy":54,"./ReactDefaultPerf":56,"./ReactEventListener":63,"./ReactInjection":64,"./ReactInstanceHandles":66,"./ReactMount":70,"./SVGDOMPropertyConfig":92,"./SelectEventPlugin":93,"./ServerReactRootIndex":94,"./SimpleEventPlugin":95,"./createFullPageComponent":116}],56:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf * @typechecks static-only */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var ReactDefaultPerfAnalysis = _dereq_("./ReactDefaultPerfAnalysis"); var ReactMount = _dereq_("./ReactMount"); var ReactPerf = _dereq_("./ReactPerf"); var performanceNow = _dereq_("./performanceNow"); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _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), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, 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' ); }, getMeasurementsSummaryMap: function(measurements) { var summary = ReactDefaultPerfAnalysis.getInclusiveSummary( measurements, true ); return summary.map(function(item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); 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() {for (var args=[],$__0=0,$__1=arguments.length;$__0<$__1;$__0++) args.push(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: {}, render: {}, 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 isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, 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":12,"./ReactDefaultPerfAnalysis":57,"./ReactMount":70,"./ReactPerf":75,"./performanceNow":153}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ var assign = _dereq_("./Object.assign"); // 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 = assign( {}, measurement.exclusive, measurement.inclusive ); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } 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 = assign( {}, 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 = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // 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; },{"./Object.assign":29}],58:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ "use strict"; var ReactContext = _dereq_("./ReactContext"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var warning = _dereq_("./warning"); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== "development" ? warning( false, 'Don\'t set the ' + key + ' property of the component. ' + 'Mutate the existing props object instead.' ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== "development") { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = { validated: false, props: props }; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== "development") { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; if ("production" !== "development") { ("production" !== "development" ? warning( config.key !== null, 'createElement(...): Encountered component with a `key` of null. In ' + 'a future version, this will be treated as equivalent to the string ' + '\'null\'; instead, provide an explicit key or use undefined.' ) : null); } // TODO: Change this back to `config.key === undefined` key = config.key == null ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== "development") { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; },{"./ReactContext":41,"./ReactCurrentOwner":42,"./warning":160}],59:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var monitorCodeUse = _dereq_("./monitorCodeUse"); var warning = _dereq_("./warning"); /** * 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 ownerHasKeyUseWarning = { 'react_key_warning': {}, 'react_numeric_key_warning': {} }; var ownerHasMonitoredObjectMap = {}; var loggedTypeFailures = {}; var NUMERIC_PROPERTY_REGEX = /^\d+$/; /** * Gets the current owner's displayName for use in warnings. * * @internal * @return {?string} Display name or undefined */ function getCurrentOwnerDisplayName() { var current = ReactCurrentOwner.current; return current && current.constructor.displayName || undefined; } /** * 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. * @param {*} parentType component's parent's type. */ function validateExplicitKey(component, parentType) { if (component._store.validated || component.key != null) { return; } component._store.validated = true; warnAndMonitorForKeyUse( 'react_key_warning', 'Each child in an array should have a unique "key" prop.', component, parentType ); } /** * 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. * @param {*} parentType component's parent's type. */ function validatePropertyKey(name, component, parentType) { if (!NUMERIC_PROPERTY_REGEX.test(name)) { return; } warnAndMonitorForKeyUse( 'react_numeric_key_warning', 'Child objects should have non-numeric keys so ordering is preserved.', component, parentType ); } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} warningID The id used when logging. * @param {string} message The base warning that gets output. * @param {ReactComponent} component Component that requires a key. * @param {*} parentType component's parent's type. */ function warnAndMonitorForKeyUse(warningID, message, component, parentType) { var ownerName = getCurrentOwnerDisplayName(); var parentName = parentType.displayName; var useName = ownerName || parentName; var memoizer = ownerHasKeyUseWarning[warningID]; if (memoizer.hasOwnProperty(useName)) { return; } memoizer[useName] = true; message += ownerName ? (" Check the render method of " + ownerName + ".") : (" Check the renderComponent call using <" + parentName + ">."); // 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. var childOwnerName = null; if (component._owner && component._owner !== ReactCurrentOwner.current) { // Name of the component that originally created this child. childOwnerName = component._owner.constructor.displayName; message += (" It was passed a child from " + childOwnerName + "."); } message += ' See http://fb.me/react-warning-keys for more information.'; monitorCodeUse(warningID, { component: useName, componentOwner: childOwnerName }); console.warn(message); } /** * Log that we're using an object map. We're considering deprecating this * feature and replace it with proper Map and ImmutableMap data structures. * * @internal */ function monitorUseOfObjectMap() { var currentName = getCurrentOwnerDisplayName() || ''; if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) { return; } ownerHasMonitoredObjectMap[currentName] = true; monitorCodeUse('react_object_map_children'); } /** * 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. * @param {*} parentType component's parent's type. * @return {boolean} */ function validateChildKeys(component, parentType) { if (Array.isArray(component)) { for (var i = 0; i < component.length; i++) { var child = component[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(component)) { // This component was passed in a valid location. component._store.validated = true; } else if (component && typeof component === 'object') { monitorUseOfObjectMap(); for (var name in component) { validatePropertyKey(name, component[name], parentType); } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { 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 { error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } 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; // This will soon use the warning module monitorCodeUse( 'react_failed_descriptor_type_check', { message: error.message } ); } } } } var ReactElementValidator = { createElement: function(type, props, children) { // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. ("production" !== "development" ? warning( type != null, 'React.createElement: type should not be null or undefined. It should ' + 'be a string (for DOM elements) or a ReactClass (for composite ' + 'components).' ) : null); var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } if (type) { var name = type.displayName; if (type.propTypes) { checkPropTypes( name, type.propTypes, element.props, ReactPropTypeLocations.prop ); } if (type.contextTypes) { checkPropTypes( name, type.contextTypes, element._context, ReactPropTypeLocations.context ); } } return element; }, createFactory: function(type) { var validatedFactory = ReactElementValidator.createElement.bind( null, type ); validatedFactory.type = type; return validatedFactory; } }; module.exports = ReactElementValidator; },{"./ReactCurrentOwner":42,"./ReactElement":58,"./ReactPropTypeLocations":78,"./monitorCodeUse":150,"./warning":160}],60:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var invariant = _dereq_("./invariant"); var component; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIdsRegistry = {}; var ReactEmptyComponentInjection = { injectEmptyComponent: function(emptyComponent) { component = ReactElement.createFactory(emptyComponent); } }; /** * @return {ReactComponent} component The injected empty component. */ function getEmptyComponent() { ("production" !== "development" ? invariant( component, 'Trying to return null from a render, but no null placeholder component ' + 'was injected.' ) : invariant(component)); return component(); } /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIdsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIdsRegistry[id]; } /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return nullComponentIdsRegistry[id]; } var ReactEmptyComponent = { deregisterNullComponentID: deregisterNullComponentID, getEmptyComponent: getEmptyComponent, injection: ReactEmptyComponentInjection, isNullComponentID: isNullComponentID, registerNullComponentID: registerNullComponentID }; module.exports = ReactEmptyComponent; },{"./ReactElement":58,"./invariant":140}],61:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],62:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ "use strict"; var EventPluginHub = _dereq_("./EventPluginHub"); 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 ); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":19}],63:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener * @typechecks static-only */ "use strict"; var EventListener = _dereq_("./EventListener"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var PooledClass = _dereq_("./PooledClass"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMount = _dereq_("./ReactMount"); var ReactUpdates = _dereq_("./ReactUpdates"); var assign = _dereq_("./Object.assign"); var getEventTarget = _dereq_("./getEventTarget"); var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition"); /** * 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; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function() { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo( TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler ); function handleTopLevelImpl(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM( getEventTarget(bookKeeping.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) || ''; ReactEventListener._handleTopLevel( bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent ); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function(handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function(enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function() { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return; } return EventListener.listen( element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, 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 {object} handle Element on which to attach listener. * @return {object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return; } return EventListener.capture( element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType) ); }, monitorScrollValue: function(refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); EventListener.listen(window, 'resize', callback); }, dispatchEvent: function(topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled( topLevelType, nativeEvent ); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"./EventListener":18,"./ExecutionEnvironment":23,"./Object.assign":29,"./PooledClass":30,"./ReactInstanceHandles":66,"./ReactMount":70,"./ReactUpdates":91,"./getEventTarget":131,"./getUnboundedScrollPosition":136}],64:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var EventPluginHub = _dereq_("./EventPluginHub"); var ReactComponent = _dereq_("./ReactComponent"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactEmptyComponent = _dereq_("./ReactEmptyComponent"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var ReactNativeComponent = _dereq_("./ReactNativeComponent"); var ReactPerf = _dereq_("./ReactPerf"); var ReactRootIndex = _dereq_("./ReactRootIndex"); var ReactUpdates = _dereq_("./ReactUpdates"); var ReactInjection = { Component: ReactComponent.injection, CompositeComponent: ReactCompositeComponent.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"./DOMProperty":12,"./EventPluginHub":19,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactEmptyComponent":60,"./ReactNativeComponent":73,"./ReactPerf":75,"./ReactRootIndex":82,"./ReactUpdates":91}],65:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ "use strict"; var ReactDOMSelection = _dereq_("./ReactDOMSelection"); var containsNode = _dereq_("./containsNode"); var focusNode = _dereq_("./focusNode"); var getActiveElement = _dereq_("./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 ); } focusNode(priorFocusedElem); } }, /** * @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":52,"./containsNode":114,"./focusNode":125,"./getActiveElement":127}],66:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceHandles * @typechecks static-only */ "use strict"; var ReactRootIndex = _dereq_("./ReactRootIndex"); var invariant = _dereq_("./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":82,"./invariant":140}],67:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLegacyElement */ "use strict"; var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var invariant = _dereq_("./invariant"); var monitorCodeUse = _dereq_("./monitorCodeUse"); var warning = _dereq_("./warning"); var legacyFactoryLogs = {}; function warnForLegacyFactoryCall() { if (!ReactLegacyElementFactory._isLegacyCallWarningEnabled) { return; } var owner = ReactCurrentOwner.current; var name = owner && owner.constructor ? owner.constructor.displayName : ''; if (!name) { name = 'Something'; } if (legacyFactoryLogs.hasOwnProperty(name)) { return; } legacyFactoryLogs[name] = true; ("production" !== "development" ? warning( false, name + ' is calling a React component directly. ' + 'Use a factory or JSX instead. See: http://fb.me/react-legacyfactory' ) : null); monitorCodeUse('react_legacy_factory_call', { version: 3, name: name }); } function warnForPlainFunctionType(type) { var isReactClass = type.prototype && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; if (isReactClass) { ("production" !== "development" ? warning( false, 'Did not expect to get a React class here. Use `Component` instead ' + 'of `Component.type` or `this.constructor`.' ) : null); } else { if (!type._reactWarnedForThisType) { try { type._reactWarnedForThisType = true; } catch (x) { // just incase this is a frozen object or some special object } monitorCodeUse( 'react_non_component_in_jsx', { version: 3, name: type.name } ); } ("production" !== "development" ? warning( false, 'This JSX uses a plain function. Only React components are ' + 'valid in React\'s JSX transform.' ) : null); } } function warnForNonLegacyFactory(type) { ("production" !== "development" ? warning( false, 'Do not pass React.DOM.' + type.type + ' to JSX or createFactory. ' + 'Use the string "' + type.type + '" instead.' ) : null); } /** * Transfer static properties from the source to the target. Functions are * rebound to have this reflect the original source. */ function proxyStaticMethods(target, source) { if (typeof source !== 'function') { return; } for (var key in source) { if (source.hasOwnProperty(key)) { var value = source[key]; if (typeof value === 'function') { var bound = value.bind(source); // Copy any properties defined on the function, such as `isRequired` on // a PropTypes validator. for (var k in value) { if (value.hasOwnProperty(k)) { bound[k] = value[k]; } } target[key] = bound; } else { target[key] = value; } } } } // We use an object instead of a boolean because booleans are ignored by our // mocking libraries when these factories gets mocked. var LEGACY_MARKER = {}; var NON_LEGACY_MARKER = {}; var ReactLegacyElementFactory = {}; ReactLegacyElementFactory.wrapCreateFactory = function(createFactory) { var legacyCreateFactory = function(type) { if (typeof type !== 'function') { // Non-function types cannot be legacy factories return createFactory(type); } if (type.isReactNonLegacyFactory) { // This is probably a factory created by ReactDOM we unwrap it to get to // the underlying string type. It shouldn't have been passed here so we // warn. if ("production" !== "development") { warnForNonLegacyFactory(type); } return createFactory(type.type); } if (type.isReactLegacyFactory) { // This is probably a legacy factory created by ReactCompositeComponent. // We unwrap it to get to the underlying class. return createFactory(type.type); } if ("production" !== "development") { warnForPlainFunctionType(type); } // Unless it's a legacy factory, then this is probably a plain function, // that is expecting to be invoked by JSX. We can just return it as is. return type; }; return legacyCreateFactory; }; ReactLegacyElementFactory.wrapCreateElement = function(createElement) { var legacyCreateElement = function(type, props, children) { if (typeof type !== 'function') { // Non-function types cannot be legacy factories return createElement.apply(this, arguments); } var args; if (type.isReactNonLegacyFactory) { // This is probably a factory created by ReactDOM we unwrap it to get to // the underlying string type. It shouldn't have been passed here so we // warn. if ("production" !== "development") { warnForNonLegacyFactory(type); } args = Array.prototype.slice.call(arguments, 0); args[0] = type.type; return createElement.apply(this, args); } if (type.isReactLegacyFactory) { // This is probably a legacy factory created by ReactCompositeComponent. // We unwrap it to get to the underlying class. if (type._isMockFunction) { // If this is a mock function, people will expect it to be called. We // will actually call the original mock factory function instead. This // future proofs unit testing that assume that these are classes. type.type._mockedReactClassConstructor = type; } args = Array.prototype.slice.call(arguments, 0); args[0] = type.type; return createElement.apply(this, args); } if ("production" !== "development") { warnForPlainFunctionType(type); } // This is being called with a plain function we should invoke it // immediately as if this was used with legacy JSX. return type.apply(null, Array.prototype.slice.call(arguments, 1)); }; return legacyCreateElement; }; ReactLegacyElementFactory.wrapFactory = function(factory) { ("production" !== "development" ? invariant( typeof factory === 'function', 'This is suppose to accept a element factory' ) : invariant(typeof factory === 'function')); var legacyElementFactory = function(config, children) { // This factory should not be called when JSX is used. Use JSX instead. if ("production" !== "development") { warnForLegacyFactoryCall(); } return factory.apply(this, arguments); }; proxyStaticMethods(legacyElementFactory, factory.type); legacyElementFactory.isReactLegacyFactory = LEGACY_MARKER; legacyElementFactory.type = factory.type; return legacyElementFactory; }; // This is used to mark a factory that will remain. E.g. we're allowed to call // it as a function. However, you're not suppose to pass it to createElement // or createFactory, so it will warn you if you do. ReactLegacyElementFactory.markNonLegacyFactory = function(factory) { factory.isReactNonLegacyFactory = NON_LEGACY_MARKER; return factory; }; // Checks if a factory function is actually a legacy factory pretending to // be a class. ReactLegacyElementFactory.isValidFactory = function(factory) { // TODO: This will be removed and moved into a class validator or something. return typeof factory === 'function' && factory.isReactLegacyFactory === LEGACY_MARKER; }; ReactLegacyElementFactory.isValidClass = function(factory) { if ("production" !== "development") { ("production" !== "development" ? warning( false, 'isValidClass is deprecated and will be removed in a future release. ' + 'Use a more specific validator instead.' ) : null); } return ReactLegacyElementFactory.isValidFactory(factory); }; ReactLegacyElementFactory._isLegacyCallWarningEnabled = true; module.exports = ReactLegacyElementFactory; },{"./ReactCurrentOwner":42,"./invariant":140,"./monitorCodeUse":150,"./warning":160}],68:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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. */ var React = _dereq_("./React"); /** * @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; } /** * Creates a PropType that enforces the ReactLink API and optionally checks the * type of the value being passed inside the link. Example: * * MyComponent.propTypes = { * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) * } */ function createLinkTypeChecker(linkType) { var shapes = { value: typeof linkType === 'undefined' ? React.PropTypes.any.isRequired : linkType.isRequired, requestChange: React.PropTypes.func.isRequired }; return React.PropTypes.shape(shapes); } ReactLink.PropTypes = { link: createLinkTypeChecker }; module.exports = ReactLink; },{"./React":31}],69:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ "use strict"; var adler32 = _dereq_("./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":110}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactElement = _dereq_("./ReactElement"); var ReactLegacyElement = _dereq_("./ReactLegacyElement"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactPerf = _dereq_("./ReactPerf"); var containsNode = _dereq_("./containsNode"); var deprecated = _dereq_("./deprecated"); var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var invariant = _dereq_("./invariant"); var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent"); var warning = _dereq_("./warning"); var createElement = ReactLegacyElement.wrapCreateElement( ReactElement.createElement ); 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.render( * 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 = { /** 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 ))); ReactBrowserEventEmitter.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) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. ("production" !== "development" ? warning( ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); var componentInstance = instantiateReactComponent(nextComponent, null); var reactRootID = ReactMount._registerComponent( componentInstance, container ); componentInstance.mountComponentIntoNode( reactRootID, container, shouldReuseMarkup ); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; } ), /** * 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 {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function(nextElement, container, callback) { ("production" !== "development" ? invariant( ReactElement.isValidElement(nextElement), 'renderComponent(): Invalid component element.%s', ( typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : ReactLegacyElement.isValidFactory(nextElement) ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like a element typeof nextElement.props !== "undefined" ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '' ) ) : invariant(ReactElement.isValidElement(nextElement))); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevElement = prevComponent._currentElement; if (shouldUpdateReactComponent(prevElement, nextElement)) { return ReactMount._updateRootComponent( prevComponent, nextElement, container, callback ); } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && ReactMount.isRenderedByReact(reactRootElement); var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent( nextElement, 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) { var element = createElement(constructor, props); return ReactMount.render(element, 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) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) ("production" !== "development" ? warning( ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function of ' + 'props and state; triggering nested component updates from render is ' + 'not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); 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), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + '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 }; // Deprecations (remove for 0.13) ReactMount.renderComponent = deprecated( 'ReactMount', 'renderComponent', 'render', this, ReactMount.render ); module.exports = ReactMount; },{"./DOMProperty":12,"./ReactBrowserEventEmitter":33,"./ReactCurrentOwner":42,"./ReactElement":58,"./ReactInstanceHandles":66,"./ReactLegacyElement":67,"./ReactPerf":75,"./containsNode":114,"./deprecated":120,"./getReactRootElementInContainer":134,"./instantiateReactComponent":139,"./invariant":140,"./shouldUpdateReactComponent":156,"./warning":160}],71:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild * @typechecks static-only */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes"); var flattenChildren = _dereq_("./flattenChildren"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var shouldUpdateReactComponent = _dereq_("./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)) { // The rendered children must be turned into instances as they're // mounted. var childInstance = instantiateReactComponent(child, null); children[name] = childInstance; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = childInstance.mountComponent( rootID, transaction, this._mountDepth + 1 ); childInstance._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 prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (shouldUpdateReactComponent(prevElement, nextElement)) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild.receiveComponent(nextElement, 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); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent( nextElement, null ); this._mountChildByNameAtIndex( nextChildInstance, 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) { this.removeChild(child); child._mountIndex = null; child.unmountComponent(); delete this._renderedChildren[name]; } } }; module.exports = ReactMultiChild; },{"./ReactComponent":37,"./ReactMultiChildUpdateTypes":72,"./flattenChildren":124,"./instantiateReactComponent":139,"./shouldUpdateReactComponent":156}],72:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ "use strict"; var keyMirror = _dereq_("./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":146}],73:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ "use strict"; var assign = _dereq_("./Object.assign"); var invariant = _dereq_("./invariant"); var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags var tagToComponentClass = {}; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function(componentClass) { genericComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function(componentClasses) { assign(tagToComponentClass, componentClasses); } }; /** * Create an internal class for a specific tag. * * @param {string} tag The tag for which to create an internal instance. * @param {any} props The props passed to the instance constructor. * @return {ReactComponent} component The injected empty component. */ function createInstanceForTag(tag, props, parentType) { var componentClass = tagToComponentClass[tag]; if (componentClass == null) { ("production" !== "development" ? invariant( genericComponentClass, 'There is no registered component for the tag %s', tag ) : invariant(genericComponentClass)); return new genericComponentClass(tag, props); } if (parentType === tag) { // Avoid recursion ("production" !== "development" ? invariant( genericComponentClass, 'There is no registered component for the tag %s', tag ) : invariant(genericComponentClass)); return new genericComponentClass(tag, props); } // Unwrap legacy factories return new componentClass.type(props); } var ReactNativeComponent = { createInstanceForTag: createInstanceForTag, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; },{"./Object.assign":29,"./invariant":140}],74:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ "use strict"; var emptyObject = _dereq_("./emptyObject"); var invariant = _dereq_("./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: { construct: function() { this.refs = emptyObject; }, /** * 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 === emptyObject ? (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; },{"./emptyObject":122,"./invariant":140}],75:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; var wrapper = function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } 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; },{}],76:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ "use strict"; var assign = _dereq_("./Object.assign"); var emptyFunction = _dereq_("./emptyFunction"); var invariant = _dereq_("./invariant"); var joinClasses = _dereq_("./joinClasses"); var warning = _dereq_("./warning"); var didWarn = false; /** * 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); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * 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), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * 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) { return transferInto(assign({}, oldProps), newProps); }, /** * @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 {ReactElement} element Component receiving the properties. * @return {ReactElement} The supplied `component`. * @final * @protected */ transferPropsTo: function(element) { ("production" !== "development" ? invariant( element._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, typeof element.type === 'string' ? element.type : element.type.displayName ) : invariant(element._owner === this)); if ("production" !== "development") { if (!didWarn) { didWarn = true; ("production" !== "development" ? warning( false, 'transferPropsTo is deprecated. ' + 'See http://fb.me/react-transferpropsto for more information.' ) : null); } } // Because elements are immutable we have to merge into the existing // props object rather than clone it. transferInto(element.props, this.props); return element; } } }; module.exports = ReactPropTransferer; },{"./Object.assign":29,"./emptyFunction":121,"./invariant":140,"./joinClasses":145,"./warning":160}],77:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ "use strict"; var ReactPropTypeLocationNames = {}; if ("production" !== "development") { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],78:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ "use strict"; var keyMirror = _dereq_("./keyMirror"); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"./keyMirror":146}],79:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames"); var deprecated = _dereq_("./deprecated"); var emptyFunction = _dereq_("./emptyFunction"); /** * 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>>'; var elementTypeChecker = createElementTypeChecker(); var nodeTypeChecker = createNodeChecker(); var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: elementTypeChecker, instanceOf: createInstanceTypeChecker, node: nodeTypeChecker, objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, component: deprecated( 'React.PropTypes', 'component', 'element', this, elementTypeChecker ), renderable: deprecated( 'React.PropTypes', 'renderable', 'node', this, nodeTypeChecker ) }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error( ("Required " + locationName + " `" + propName + "` was not specified in ")+ ("`" + componentName + "`.") ); } } else { return validate(props, propName, componentName, location); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `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 Error( ("Invalid " + locationName + " `" + propName + "` of type `" + preciseType + "` ") + ("supplied to `" + componentName + "`, expected `" + expectedType + "`.") ); } } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns()); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error( ("Invalid " + locationName + " `" + propName + "` of type ") + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.") ); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location); if (error instanceof Error) { return error; } } } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactElement.") ); } } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected instance of `" + expectedClassName + "`.") ); } } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { function validate(props, propName, componentName, location) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error( ("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".") ); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` 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); if (error instanceof Error) { return error; } } } } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { function validate(props, propName, componentName, location) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location) == null) { return; } } var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`.") ); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactNode.") ); } } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` 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); if (error) { return error; } } } return createChainableTypeChecker(validate, 'expected `object`'); } function isNode(propValue) { switch(typeof propValue) { case 'number': case 'string': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (ReactElement.isValidElement(propValue)) { return true; } for (var k in propValue) { if (!isNode(propValue[k])) { return false; } } return true; default: 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'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } module.exports = ReactPropTypes; },{"./ReactElement":58,"./ReactPropTypeLocationNames":77,"./deprecated":120,"./emptyFunction":121}],80:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPutListenerQueue */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var assign = _dereq_("./Object.assign"); function ReactPutListenerQueue() { this.listenersToPut = []; } assign(ReactPutListenerQueue.prototype, { 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]; ReactBrowserEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33}],81:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ "use strict"; var CallbackQueue = _dereq_("./CallbackQueue"); var PooledClass = _dereq_("./PooledClass"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var ReactInputSelection = _dereq_("./ReactInputSelection"); var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue"); var Transaction = _dereq_("./Transaction"); var assign = _dereq_("./Object.assign"); /** * 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 `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function() { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occured. `close` * restores the previous value. */ close: function(previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the 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(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.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() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ 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() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33,"./ReactInputSelection":65,"./ReactPutListenerQueue":80,"./Transaction":107}],82:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRootIndex * @typechecks */ "use strict"; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],83:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, 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. * * @typechecks static-only * @providesModule ReactServerRendering */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum"); var ReactServerRenderingTransaction = _dereq_("./ReactServerRenderingTransaction"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var invariant = _dereq_("./invariant"); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { ("production" !== "development" ? invariant( ReactElement.isValidElement(element), 'renderToString(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, 0); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { ("production" !== "development" ? invariant( ReactElement.isValidElement(element), 'renderToStaticMarkup(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, 0); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; },{"./ReactElement":58,"./ReactInstanceHandles":66,"./ReactMarkupChecksum":69,"./ReactServerRenderingTransaction":84,"./instantiateReactComponent":139,"./invariant":140}],84:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction * @typechecks */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var CallbackQueue = _dereq_("./CallbackQueue"); var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue"); var Transaction = _dereq_("./Transaction"); var assign = _dereq_("./Object.assign"); var emptyFunction = _dereq_("./emptyFunction"); /** * Provides a `CallbackQueue` 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(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * 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, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ 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() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign( ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin ); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactPutListenerQueue":80,"./Transaction":107,"./emptyFunction":121}],85:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],86:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTestUtils */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var EventPropagators = _dereq_("./EventPropagators"); var React = _dereq_("./React"); var ReactElement = _dereq_("./ReactElement"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var ReactMount = _dereq_("./ReactMount"); var ReactTextComponent = _dereq_("./ReactTextComponent"); var ReactUpdates = _dereq_("./ReactUpdates"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var assign = _dereq_("./Object.assign"); 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.render(instance, div); }, isElement: function(element) { return ReactElement.isValidElement(element); }, isElementOfType: function(inst, convenienceConstructor) { return ( ReactElement.isValidElement(inst) && inst.type === convenienceConstructor.type ); }, isDOMComponent: function(inst) { return !!(inst && inst.mountComponent && inst.tagName); }, isDOMComponentElement: function(inst) { return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName); }, isCompositeComponent: function(inst) { return typeof inst.render === 'function' && typeof inst.setState === 'function'; }, isCompositeComponentWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponent(inst) && (inst.constructor === type.type)); }, isCompositeComponentElement: function(inst) { if (!ReactElement.isValidElement(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' ); }, isCompositeComponentElementWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponentElement(inst) && (inst.constructor === type)); }, isTextComponent: function(inst) { return inst instanceof ReactTextComponent.type; }, 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) { mockTagName = mockTagName || module.mockTagName || "div"; var ConvenienceConstructor = React.createClass({displayName: "ConvenienceConstructor", render: function() { return React.createElement( mockTagName, null, this.props.children ); } }); module.mockImplementation(ConvenienceConstructor); module.type = ConvenienceConstructor.type; module.isReactLegacyFactory = true; 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) { fakeNativeEvent.target = node; ReactBrowserEventEmitter.ReactEventListener.dispatchEvent( topLevelType, 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( ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType], ReactMount.getID(node), fakeNativeEvent ); assign(event, eventData); EventPropagators.accumulateTwoPhaseDispatches(event); ReactUpdates.batchedUpdates(function() { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); }); }; } function buildSimulators() { ReactTestUtils.Simulate = {}; var eventType; for (eventType in ReactBrowserEventEmitter.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); assign(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":17,"./EventPluginHub":19,"./EventPropagators":22,"./Object.assign":29,"./React":31,"./ReactBrowserEventEmitter":33,"./ReactElement":58,"./ReactMount":70,"./ReactTextComponent":87,"./ReactUpdates":91,"./SyntheticEvent":99}],87:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTextComponent * @typechecks static-only */ "use strict"; var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var ReactComponent = _dereq_("./ReactComponent"); var ReactElement = _dereq_("./ReactElement"); var assign = _dereq_("./Object.assign"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); /** * 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(props) { // This constructor and it's argument is currently used by mocks. }; assign(ReactTextComponent.prototype, ReactComponent.Mixin, { /** * 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|ReactServerRenderingTransaction} 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 ); var escapedText = escapeTextForBrowser(this.props); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return ( '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</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 !== this.props) { this.props = nextProps; ReactComponent.BackendIDOperations.updateTextContentByID( this._rootNodeID, nextProps ); } } }); var ReactTextComponentFactory = function(text) { // Bypass validation and configuration return new ReactElement(ReactTextComponent, null, null, null, null, text); }; ReactTextComponentFactory.type = ReactTextComponent; module.exports = ReactTextComponentFactory; },{"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactComponent":37,"./ReactElement":58,"./escapeTextForBrowser":123}],88:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, 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. * * @typechecks static-only * @providesModule ReactTransitionChildMapping */ "use strict"; var ReactChildren = _dereq_("./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 to 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.hasOwnProperty(prevKey)) { if (pendingKeys.length) { nextKeysPending[prevKey] = pendingKeys; pendingKeys = []; } } else { pendingKeys.push(prevKey); } } var i; var childMapping = {}; for (var nextKey in next) { if (nextKeysPending.hasOwnProperty(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":36}],89:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ 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; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } 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":23}],90:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionGroup */ "use strict"; var React = _dereq_("./React"); var ReactTransitionChildMapping = _dereq_("./ReactTransitionChildMapping"); var assign = _dereq_("./Object.assign"); var cloneWithProps = _dereq_("./cloneWithProps"); var emptyFunction = _dereq_("./emptyFunction"); var ReactTransitionGroup = React.createClass({ displayName: 'ReactTransitionGroup', propTypes: { component: React.PropTypes.any, childFactory: React.PropTypes.func }, getDefaultProps: function() { return { component: '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) { var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) { this.keysToEnter.push(key); } } for (key in prevChildMapping) { var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key); if (prevChildMapping[key] && !hasNext && !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 || !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 && currentChildMapping.hasOwnProperty(key)) { // This entered again before it fully left. Add it again. this.performEnter(key); } else { var newChildren = assign({}, 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 React.createElement( this.props.component, this.props, childrenToRender ); } }); module.exports = ReactTransitionGroup; },{"./Object.assign":29,"./React":31,"./ReactTransitionChildMapping":88,"./cloneWithProps":113,"./emptyFunction":121}],91:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ "use strict"; var CallbackQueue = _dereq_("./CallbackQueue"); var PooledClass = _dereq_("./PooledClass"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactPerf = _dereq_("./ReactPerf"); var Transaction = _dereq_("./Transaction"); var assign = _dereq_("./Object.assign"); var invariant = _dereq_("./invariant"); var warning = _dereq_("./warning"); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { ("production" !== "development" ? invariant( ReactUpdates.ReactReconcileTransaction && batchingStrategy, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy' ) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy)); } var NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function() { this.callbackQueue.reset(); }, close: function() { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(); } assign( ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a ); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b); } /** * 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(transaction) { var len = transaction.dirtyComponentsLength; ("production" !== "development" ? invariant( len === dirtyComponents.length, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ) : invariant(len === dirtyComponents.length)); // 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 < len; 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(transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue( callbacks[j], component ); } } } } } var flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', function() { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } } ); /** * 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")); ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) ("production" !== "development" ? warning( ReactCurrentOwner.current == null, 'enqueueUpdate(): Render methods should be a pure function of props ' + 'and state; triggering nested component updates from render is not ' + 'allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component, callback); return; } dirtyComponents.push(component); if (callback) { if (component._pendingCallbacks) { component._pendingCallbacks.push(callback); } else { component._pendingCallbacks = [callback]; } } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { ("production" !== "development" ? invariant( batchingStrategy.isBatchingUpdates, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.' ) : invariant(batchingStrategy.isBatchingUpdates)); asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function(ReconcileTransaction) { ("production" !== "development" ? invariant( ReconcileTransaction, 'ReactUpdates: must provide a reconcile transaction class' ) : invariant(ReconcileTransaction)); ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, 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 = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; },{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactCurrentOwner":42,"./ReactPerf":75,"./Transaction":107,"./invariant":140,"./warning":160}],92:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var SVGDOMPropertyConfig = { Properties: { cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: 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, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: 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: { fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox' } }; module.exports = SVGDOMPropertyConfig; },{"./DOMProperty":12}],93:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var ReactInputSelection = _dereq_("./ReactInputSelection"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var getActiveElement = _dereq_("./getActiveElement"); var isTextInputElement = _dereq_("./isTextInputElement"); var keyOf = _dereq_("./keyOf"); var shallowEqual = _dereq_("./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 (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * 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":17,"./EventPropagators":22,"./ReactInputSelection":65,"./SyntheticEvent":99,"./getActiveElement":127,"./isTextInputElement":143,"./keyOf":147,"./shallowEqual":155}],94:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],95:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var EventPropagators = _dereq_("./EventPropagators"); var SyntheticClipboardEvent = _dereq_("./SyntheticClipboardEvent"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var SyntheticFocusEvent = _dereq_("./SyntheticFocusEvent"); var SyntheticKeyboardEvent = _dereq_("./SyntheticKeyboardEvent"); var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent"); var SyntheticDragEvent = _dereq_("./SyntheticDragEvent"); var SyntheticTouchEvent = _dereq_("./SyntheticTouchEvent"); var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var SyntheticWheelEvent = _dereq_("./SyntheticWheelEvent"); var getEventCharCode = _dereq_("./getEventCharCode"); var invariant = _dereq_("./invariant"); var keyOf = _dereq_("./keyOf"); var warning = _dereq_("./warning"); 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. This behavior will be disabled in a future release. * * @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); ("production" !== "development" ? warning( typeof returnValue !== 'boolean', 'Returning `false` from an event handler is deprecated and will be ' + 'ignored in a future release. Instead, manually call ' + 'e.stopPropagation() or e.preventDefault(), as appropriate.' ) : null); 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.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: 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":17,"./EventPluginUtils":21,"./EventPropagators":22,"./SyntheticClipboardEvent":96,"./SyntheticDragEvent":98,"./SyntheticEvent":99,"./SyntheticFocusEvent":100,"./SyntheticKeyboardEvent":102,"./SyntheticMouseEvent":103,"./SyntheticTouchEvent":104,"./SyntheticUIEvent":105,"./SyntheticWheelEvent":106,"./getEventCharCode":128,"./invariant":140,"./keyOf":147,"./warning":160}],96:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./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":99}],97:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./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":99}],98:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = _dereq_("./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":103}],99:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent * @typechecks static-only */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var assign = _dereq_("./Object.assign"); var emptyFunction = _dereq_("./emptyFunction"); var getEventTarget = _dereq_("./getEventTarget"); /** * @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; } assign(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); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler); module.exports = SyntheticEvent; },{"./Object.assign":29,"./PooledClass":30,"./emptyFunction":121,"./getEventTarget":131}],100:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./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":105}],101:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./SyntheticEvent"); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { 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 SyntheticInputEvent( dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticInputEvent, InputEventInterface ); module.exports = SyntheticInputEvent; },{"./SyntheticEvent":99}],102:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var getEventCharCode = _dereq_("./getEventCharCode"); var getEventKey = _dereq_("./getEventKey"); var getEventModifierState = _dereq_("./getEventModifierState"); /** * @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, getModifierState: getEventModifierState, // Legacy Interface charCode: function(event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function(event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function(event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @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":105,"./getEventCharCode":128,"./getEventKey":129,"./getEventModifierState":130}],103:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var ViewportMetrics = _dereq_("./ViewportMetrics"); var getEventModifierState = _dereq_("./getEventModifierState"); /** * @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, getModifierState: getEventModifierState, 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":105,"./ViewportMetrics":108,"./getEventModifierState":130}],104:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var getEventModifierState = _dereq_("./getEventModifierState"); /** * @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, getModifierState: getEventModifierState }; /** * @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":105,"./getEventModifierState":130}],105:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./SyntheticEvent"); var getEventTarget = _dereq_("./getEventTarget"); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function(event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function(event) { return event.detail || 0; } }; /** * @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":99,"./getEventTarget":131}],106:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = _dereq_("./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":103}],107:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ "use strict"; var invariant = _dereq_("./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> * * 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; } 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 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 { 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; for (var i = startIndex; i < transactionWrappers.length; i++) { 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 { 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; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; 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 { 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":140}],108:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ "use strict"; var getUnboundedScrollPosition = _dereq_("./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":136}],109:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ "use strict"; var invariant = _dereq_("./invariant"); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { ("production" !== "development" ? invariant( next != null, 'accumulateInto(...): Accumulated items must not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } // 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 && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; },{"./invariant":140}],110:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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 reasonably 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; },{}],111:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function(_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],112:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelizeStyleName * @typechecks */ "use strict"; var camelize = _dereq_("./camelize"); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; },{"./camelize":111}],113:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, 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. * * @typechecks * @providesModule cloneWithProps */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactPropTransferer = _dereq_("./ReactPropTransferer"); var keyOf = _dereq_("./keyOf"); var warning = _dereq_("./warning"); 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") { ("production" !== "development" ? warning( !child.ref, '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.' ) : null); } 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; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; },{"./ReactElement":58,"./ReactPropTransferer":76,"./keyOf":147,"./warning":160}],114:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule containsNode * @typechecks */ var isTextNode = _dereq_("./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":144}],115:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createArrayFrom * @typechecks */ var toArray = _dereq_("./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":157}],116:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createFullPageComponent * @typechecks */ "use strict"; // Defeat circular references by requiring this directly. var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactElement = _dereq_("./ReactElement"); var invariant = _dereq_("./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 {string} tag The tag to wrap * @return {function} convenience constructor of new component */ function createFullPageComponent(tag) { var elementFactory = ReactElement.createFactory(tag); var FullPageComponent = ReactCompositeComponent.createClass({ displayName: 'ReactFullPageComponent' + tag, 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 elementFactory(this.props); } }); return FullPageComponent; } module.exports = createFullPageComponent; },{"./ReactCompositeComponent":40,"./ReactElement":58,"./invariant":140}],117:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createNodesFromMarkup * @typechecks */ /*jslint evil: true, sub: true */ var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var createArrayFrom = _dereq_("./createArrayFrom"); var getMarkupWrap = _dereq_("./getMarkupWrap"); var invariant = _dereq_("./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":23,"./createArrayFrom":115,"./getMarkupWrap":132,"./invariant":140}],118:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],119:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue * @typechecks static-only */ "use strict"; var CSSProperty = _dereq_("./CSSProperty"); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, 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 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"./CSSProperty":5}],120:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule deprecated */ var assign = _dereq_("./Object.assign"); var warning = _dereq_("./warning"); /** * This will log a single deprecation notice per function and forward the call * on to the new API. * * @param {string} namespace The namespace of the call, eg 'React' * @param {string} oldName The old function name, eg 'renderComponent' * @param {string} newName The new function name, eg 'render' * @param {*} ctx The context this forwarded call should run in * @param {function} fn The function to forward on to * @return {*} Will be the value as returned from `fn` */ function deprecated(namespace, oldName, newName, ctx, fn) { var warned = false; if ("production" !== "development") { var newFn = function() { ("production" !== "development" ? warning( warned, (namespace + "." + oldName + " will be deprecated in a future version. ") + ("Use " + namespace + "." + newName + " instead.") ) : null); warned = true; return fn.apply(ctx, arguments); }; newFn.displayName = (namespace + "_" + oldName); // We need to make sure all properties of the original fn are copied over. // In particular, this is needed to support PropTypes return assign(newFn, fn); } return fn; } module.exports = deprecated; },{"./Object.assign":29,"./warning":160}],121:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ 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() {} 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; },{}],122:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== "development") { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],123:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextForBrowser * @typechecks static-only */ "use strict"; var ESCAPE_LOOKUP = { "&": "&amp;", ">": "&gt;", "<": "&lt;", "\"": "&quot;", "'": "&#x27;" }; 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; },{}],124:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ "use strict"; var ReactTextComponent = _dereq_("./ReactTextComponent"); var traverseAllChildren = _dereq_("./traverseAllChildren"); var warning = _dereq_("./warning"); /** * @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; var keyUnique = !result.hasOwnProperty(name); ("production" !== "development" ? warning( keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); if (keyUnique && child != null) { var type = typeof child; var normalizedValue; if (type === 'string') { normalizedValue = ReactTextComponent(child); } else if (type === 'number') { normalizedValue = ReactTextComponent('' + child); } else { normalizedValue = child; } result[name] = normalizedValue; } } /** * 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; },{"./ReactTextComponent":87,"./traverseAllChildren":158,"./warning":160}],125:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule focusNode */ "use strict"; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch(e) { } } module.exports = focusNode; },{}],126:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],127:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],128:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode * @typechecks static-only */ "use strict"; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {string} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],129:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey * @typechecks static-only */ "use strict"; var getEventCharCode = _dereq_("./getEventCharCode"); /** * 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 `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) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"./getEventCharCode":128}],130:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState * @typechecks static-only */ "use strict"; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { /*jshint validthis:true */ var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],131:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],132:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getMarkupWrap */ var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var invariant = _dereq_("./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, 'ellipse': 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, 'ellipse': 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":23,"./invariant":140}],133:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],134:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],135:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ "use strict"; var ExecutionEnvironment = _dereq_("./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.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"./ExecutionEnvironment":23}],136:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],137:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenate * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],138:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenateStyleName * @typechecks */ "use strict"; var hyphenate = _dereq_("./hyphenate"); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; },{"./hyphenate":137}],139:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent * @typechecks static-only */ "use strict"; var warning = _dereq_("./warning"); var ReactElement = _dereq_("./ReactElement"); var ReactLegacyElement = _dereq_("./ReactLegacyElement"); var ReactNativeComponent = _dereq_("./ReactNativeComponent"); var ReactEmptyComponent = _dereq_("./ReactEmptyComponent"); /** * Given an `element` create an instance that will actually be mounted. * * @param {object} element * @param {*} parentCompositeType The composite type that resolved this. * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(element, parentCompositeType) { var instance; if ("production" !== "development") { ("production" !== "development" ? warning( element && (typeof element.type === 'function' || typeof element.type === 'string'), 'Only functions or strings can be mounted as React components.' ) : null); // Resolve mock instances if (element.type._mockedReactClassConstructor) { // If this is a mocked class, we treat the legacy factory as if it was the // class constructor for future proofing unit tests. Because this might // be mocked as a legacy factory, we ignore any warnings triggerd by // this temporary hack. ReactLegacyElement._isLegacyCallWarningEnabled = false; try { instance = new element.type._mockedReactClassConstructor( element.props ); } finally { ReactLegacyElement._isLegacyCallWarningEnabled = true; } // If the mock implementation was a legacy factory, then it returns a // element. We need to turn this into a real component instance. if (ReactElement.isValidElement(instance)) { instance = new instance.type(instance.props); } var render = instance.render; if (!render) { // For auto-mocked factories, the prototype isn't shimmed and therefore // there is no render function on the instance. We replace the whole // component with an empty component instance instead. element = ReactEmptyComponent.getEmptyComponent(); } else { if (render._isMockFunction && !render._getMockImplementation()) { // Auto-mocked components may have a prototype with a mocked render // function. For those, we'll need to mock the result of the render // since we consider undefined to be invalid results from render. render.mockImplementation( ReactEmptyComponent.getEmptyComponent ); } instance.construct(element); return instance; } } } // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInstanceForTag( element.type, element.props, parentCompositeType ); } else { // Normal case for non-mocks and non-strings instance = new element.type(element.props); } if ("production" !== "development") { ("production" !== "development" ? warning( typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function', 'Only React Components can be mounted.' ) : null); } // This actually sets up the internal instance. This will become decoupled // from the public instance in a future diff. instance.construct(element); return instance; } module.exports = instantiateReactComponent; },{"./ReactElement":58,"./ReactEmptyComponent":60,"./ReactLegacyElement":67,"./ReactNativeComponent":73,"./warning":160}],140:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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, format, a, b, c, d, e, f) { if ("production" !== "development") { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } 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( '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; },{}],141:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ "use strict"; var ExecutionEnvironment = _dereq_("./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":23}],142:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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 === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string' )); } module.exports = isNode; },{}],143:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],144:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextNode * @typechecks */ var isNode = _dereq_("./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":142}],145:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; },{}],146:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ "use strict"; var invariant = _dereq_("./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":140}],147:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],148:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mapObject */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; },{}],149:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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; },{}],150:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule monitorCodeUse */ "use strict"; var invariant = _dereq_("./invariant"); /** * Provides open-source compatible instrumentation for monitoring certain API * uses before we're ready to issue a warning or refactor. It accepts an event * name which may only contain the characters [a-z0-9_] and an optional data * object with further information. */ function monitorCodeUse(eventName, data) { ("production" !== "development" ? invariant( eventName && !/[^a-z0-9_]/.test(eventName), 'You must provide an eventName using only the characters [a-z0-9_]' ) : invariant(eventName && !/[^a-z0-9_]/.test(eventName))); } module.exports = monitorCodeUse; },{"./invariant":140}],151:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var invariant = _dereq_("./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( ReactElement.isValidElement(children), 'onlyChild must be passed a children with exactly one child.' ) : invariant(ReactElement.isValidElement(children))); return children; } module.exports = onlyChild; },{"./ReactElement":58,"./invariant":140}],152:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performance * @typechecks */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"./ExecutionEnvironment":23}],153:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performanceNow * @typechecks */ var performance = _dereq_("./performance"); /** * 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 * because of Facebook's testing infrastructure. */ if (!performance || !performance.now) { performance = Date; } var performanceNow = performance.now.bind(performance); module.exports = performanceNow; },{"./performance":152}],154:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = function(node, html) { node.innerHTML = html; }; if (ExecutionEnvironment.canUseDOM) { // 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 // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function(node, html) { // 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. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. node.innerHTML = '\uFEFF' + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; },{"./ExecutionEnvironment":23}],155:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule 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's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; },{}],156:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ "use strict"; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { if (prevElement && nextElement && prevElement.type === nextElement.type && prevElement.key === nextElement.key && prevElement._owner === nextElement._owner) { return true; } return false; } module.exports = shouldUpdateReactComponent; },{}],157:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule toArray * @typechecks */ var invariant = _dereq_("./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|filelist} 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":140}],158:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ "use strict"; var ReactElement = _dereq_("./ReactElement"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var invariant = _dereq_("./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.key != null) { // Explicit key return wrapUserProvidedKey(component.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 nextName, nextIndex; 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]; nextName = ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + getComponentKey(child, i) ); 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 (type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { 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)) { nextName = ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(key) + SUBSEPARATOR + getComponentKey(children[key], 0) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( children[key], nextName, nextIndex, callback, traverseContext ); } } } } 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. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', 0, callback, traverseContext); } module.exports = traverseAllChildren; },{"./ReactElement":58,"./ReactInstanceHandles":66,"./invariant":140}],159:[function(_dereq_,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ "use strict"; var assign = _dereq_("./Object.assign"); var keyOf = _dereq_("./keyOf"); var invariant = _dereq_("./invariant"); function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({$push: null}); var COMMAND_UNSHIFT = keyOf({$unshift: null}); var COMMAND_SPLICE = keyOf({$splice: null}); var COMMAND_SET = keyOf({$set: null}); var COMMAND_MERGE = keyOf({$merge: null}); var COMMAND_APPLY = keyOf({$apply: null}); var ALL_COMMANDS_LIST = [ COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY ]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function(command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { ("production" !== "development" ? invariant( Array.isArray(value), 'update(): expected target of %s to be an array; got %s.', command, value ) : invariant(Array.isArray(value))); var specValue = spec[command]; ("production" !== "development" ? invariant( Array.isArray(specValue), 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue ) : invariant(Array.isArray(specValue))); } function update(value, spec) { ("production" !== "development" ? invariant( typeof spec === 'object', 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET ) : invariant(typeof spec === 'object')); if (spec.hasOwnProperty(COMMAND_SET)) { ("production" !== "development" ? invariant( Object.keys(spec).length === 1, 'Cannot have more than one key in an object with %s', COMMAND_SET ) : invariant(Object.keys(spec).length === 1)); return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (spec.hasOwnProperty(COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; ("production" !== "development" ? invariant( mergeObj && typeof mergeObj === 'object', 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj ) : invariant(mergeObj && typeof mergeObj === 'object')); ("production" !== "development" ? invariant( nextValue && typeof nextValue === 'object', 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue ) : invariant(nextValue && typeof nextValue === 'object')); assign(nextValue, spec[COMMAND_MERGE]); } if (spec.hasOwnProperty(COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function(item) { nextValue.push(item); }); } if (spec.hasOwnProperty(COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function(item) { nextValue.unshift(item); }); } if (spec.hasOwnProperty(COMMAND_SPLICE)) { ("production" !== "development" ? invariant( Array.isArray(value), 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value ) : invariant(Array.isArray(value))); ("production" !== "development" ? invariant( Array.isArray(spec[COMMAND_SPLICE]), 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE] ) : invariant(Array.isArray(spec[COMMAND_SPLICE]))); spec[COMMAND_SPLICE].forEach(function(args) { ("production" !== "development" ? invariant( Array.isArray(args), 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE] ) : invariant(Array.isArray(args))); nextValue.splice.apply(nextValue, args); }); } if (spec.hasOwnProperty(COMMAND_APPLY)) { ("production" !== "development" ? invariant( typeof spec[COMMAND_APPLY] === 'function', 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY] ) : invariant(typeof spec[COMMAND_APPLY] === 'function')); nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; },{"./Object.assign":29,"./invariant":140,"./keyOf":147}],160:[function(_dereq_,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = _dereq_("./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 ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); 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":121}]},{},[1])(1) });
src/components/DeveloperMenu.android.js
jpkontreras/e-waste
import React from 'react'; import * as snapshot from '../utils/snapshot'; import * as auth0 from '../services/auth0'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; /** * Simple developer menu, which allows e.g. to clear the app state. * It can be accessed through a tiny button in the bottom right corner of the screen. * ONLY FOR DEVELOPMENT MODE! */ const DeveloperMenu = React.createClass({ displayName: 'DeveloperMenu', getInitialState() { return {visible: false}; }, showDeveloperMenu() { this.setState({isVisible: true}); }, async clearState() { await snapshot.clearSnapshot(); console.warn('(╯°□°)╯︵ ┻━┻ \nState cleared, Cmd+R to reload the application now'); this.closeMenu(); }, async showLogin() { await auth0.showLogin(); console.log('Show auth0 login screen'); this.closeMenu(); }, closeMenu() { this.setState({isVisible: false}); }, renderMenuItem(text, onPress) { return ( <TouchableOpacity key={text} onPress={onPress} style={styles.menuItem} > <Text style={styles.menuItemText}>{text}</Text> </TouchableOpacity> ); }, render() { if (!__DEV__) { return null; } if (!this.state.isVisible) { return ( <TouchableOpacity style={styles.circle} onPress={this.showDeveloperMenu} /> ); } const buttons = [ this.renderMenuItem('Clear state', this.clearState), this.renderMenuItem('Show login', this.showLogin), this.renderMenuItem('Cancel', this.closeMenu) ]; return ( <View style={styles.menu}> {buttons} </View> ); } }); const styles = StyleSheet.create({ circle: { position: 'absolute', bottom: 5, right: 5, width: 10, height: 10, borderRadius: 5, backgroundColor: '#fff' }, menu: { backgroundColor: 'white', position: 'absolute', left: 0, right: 0, bottom: 0 }, menuItem: { flex: 1, flexDirection: 'row', alignItems: 'center', borderTopWidth: 1, borderTopColor: '#eee', padding: 10, height: 60 }, menuItemText: { fontSize: 20 } }); export default DeveloperMenu;
packages/material-ui-icons/src/SignalWifi1Bar.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z" /><path d="M6.67 14.86L12 21.49v.01l.01-.01 5.33-6.63C17.06 14.65 15.03 13 12 13s-5.06 1.65-5.33 1.86z" /></React.Fragment> , 'SignalWifi1Bar');
src/Well.js
bvasko/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Well = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'well' }; }, render() { let classes = this.getBsClassSet(); return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </div> ); } }); export default Well;
ajax/libs/rxjs/2.4.1/rx.compat.js
Olical/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 }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { 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) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { 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](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, 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 }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ 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, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); if (!item.isCancelled()) { !item.isCancelled() && item.invoke(); } } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var 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, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { 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 localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * 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 = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * 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 observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (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; }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; /** * 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) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { //deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).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.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * 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 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * 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 (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([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.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @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 args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an 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.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * 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 (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * 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 (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); /*try { var result = this.selector(x, this.i++, this.source); } catch (e) { return this.observer.onError(e); } this.observer.onNext(result);*/ }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
template/src/layouts/CoreLayout/Sider/index.js
likun7981/react-template-router
import React from 'react' import { NavLink } from 'react-router-dom' import './Sider.less' export default () => ( <div className="sider-container"> <NavLink exact to="/" activeClassName="sider-active"> Home </NavLink> {' · '} <NavLink to="/other" activeClassName="sider-active"> Other </NavLink> </div> )
src/Main/AppBackgroundImage.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import BackgroundOverlay from './Images/background-overlay.png'; import Backgrounds from './Backgrounds'; const styles = { container: { position: 'fixed', top: 0, bottom: 0, left: 0, right: 0, opacity: 0, zIndex: -10, transition: 'opacity 1s', }, active: { opacity: 1, }, image: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 0, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', backgroundAttachment: 'fixed', }, overlay: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 1, backgroundImage: `url(${BackgroundOverlay})`, }, }; class AppBackgroundImage extends React.PureComponent { static propTypes = { bossId: PropTypes.number, }; //url ? `url(${url})` : null /* */ constructor() { super(); this.state = { image: null, show: false, }; } componentWillReceiveProps(newProps) { if (newProps.bossId !== this.props.bossId) { const bossId = newProps.bossId; if (Backgrounds[bossId] && Backgrounds[bossId].length > 0) { const imageIndex = Math.floor(Math.random() * Backgrounds[bossId].length); this.setState({ image: Backgrounds[bossId][imageIndex], }); } } this.setState({ show: !!newProps.bossId && Backgrounds[newProps.bossId] && Backgrounds[newProps.bossId].length > 0, }); } render() { let containerStyle = styles.container; if (this.state.show) { containerStyle = { ...containerStyle, ...styles.active, }; } return ( <div style={containerStyle}> <div style={{ ...styles.image, backgroundImage: this.state.image ? `url(${this.state.image})` : null, }} /> <div style={styles.overlay} /> </div> ); } } export default AppBackgroundImage;
example/__tests__/index.android.js
tielan/react-native-form
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
packages/material-ui-icons/src/SdStorageOutlined.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M18 4v16H6V8.83L10.83 4H18m0-2h-8L4 8v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z" /><path d="M9 7h2v4H9zM12 7h2v4h-2zM15 7h2v4h-2z" /></g></React.Fragment> , 'SdStorageOutlined');
ajax/libs/react-cookie/0.1.4/react-cookie.js
dakshshah96/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(require,module,exports){ var cookie = require('cookie'); var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : ''); for (var key in _cookies) { try { _cookies[key] = JSON.parse(_cookies[key]); } catch(e) { // Not serialized object } } function load(name) { return _cookies[name]; } function save(name, val, opt) { _cookies[name] = val; // Cookies only work in the browser if (typeof document === 'undefined') return; document.cookie = cookie.serialize(name, val, opt); } var reactCookie = { load: load, save: save }; if (typeof module !== 'undefined') { module.exports = reactCookie } if (typeof window !== 'undefined') { window['reactCookie'] = reactCookie; } },{"cookie":2}],2:[function(require,module,exports){ /// Serialize the a name value pair into a cookie string suitable for /// http headers. An optional options object specified cookie parameters /// /// serialize('foo', 'bar', { httpOnly: true }) /// => "foo=bar; httpOnly" /// /// @param {String} name /// @param {String} val /// @param {Object} options /// @return {String} var serialize = function(name, val, opt){ opt = opt || {}; var enc = opt.encode || encode; var pairs = [name + '=' + enc(val)]; if (null != opt.maxAge) { var maxAge = opt.maxAge - 0; if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); pairs.push('Max-Age=' + maxAge); } if (opt.domain) pairs.push('Domain=' + opt.domain); if (opt.path) pairs.push('Path=' + opt.path); if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); if (opt.httpOnly) pairs.push('HttpOnly'); if (opt.secure) pairs.push('Secure'); return pairs.join('; '); }; /// Parse the given cookie header string into an object /// The object has the various cookies as keys(names) => values /// @param {String} str /// @return {Object} var parse = function(str, opt) { opt = opt || {}; var obj = {} var pairs = str.split(/; */); var dec = opt.decode || decode; pairs.forEach(function(pair) { var eq_idx = pair.indexOf('=') // skip things that don't look like key=value if (eq_idx < 0) { return; } var key = pair.substr(0, eq_idx).trim() var val = pair.substr(++eq_idx, pair.length).trim(); // quoted values if ('"' == val[0]) { val = val.slice(1, -1); } // only assign once if (undefined == obj[key]) { try { obj[key] = dec(val); } catch (e) { obj[key] = val; } } }); return obj; }; var encode = encodeURIComponent; var decode = decodeURIComponent; module.exports.serialize = serialize; module.exports.parse = parse; },{}]},{},[1]);
src/client/components/SemiCircleDonutChart.js
Viestinta/viestinta
import React from 'react' import Highcharts from 'highcharts' const chartOptions = { chart: { plotBackgroundColor: null, plotBorderWidth: 0, plotShadow: false }, title: { text: 'Tempo<br>(nåverdi)', align: 'center', verticalAlign: 'middle', y: 40 }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { dataLabels: { enabled: true, distance: -30, style: { fontWeight: 'bold', color: 'white' } }, startAngle: -90, endAngle: 90, center: ['50%', '75%'], colors: ['#428ce0', '#ec9d5b'] } }, series: [{ type: 'pie', name: 'Andel', id: 'votes', innerSize: '50%', data: [ ['Sakte: 0', 50.00], ['Fort: 0', 50.00] ] }] } const styles = { chart: { minWidth: '300px', height: '300px', margin: '0px' } } export default class SemiCircleDonutChart extends React.Component { constructor (props) { super(props) this.state = { chart: undefined, serie: undefined } this.setData = this.setData.bind(this) } componentDidMount() { var chart = new Highcharts[this.props.type || "Chart"]( this.refs.chart, chartOptions ) this.setState({ chart: chart, serie: chart.get('votes') }) } componentWillUnmount() { this.state.chart.destroy() } /* [['Sakte: <num>', %], ['Fort: <num>', %]] */ setData(data){ this.state.serie.setData(data) } render() { return ( <div ref="chart" style={styles.chart}></div> ) } }
src/player/Player.js
petertrotman/critrolemoments
import React from 'react'; import styled from 'styled-components'; import YouTube from 'react-youtube'; const Container = styled.div` // From http://webdesignerwall.com/tutorials/css-elastic-videos > * { display: block; position: relative; padding-bottom: 56.25%; padding-top: 30px; height: 0; overflow: hidden; } iframe, object, embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } `; const Player = props => ( <Container> <YouTube {...props} /> </Container> ); export default Player;
app/containers/TrackPreview/index.js
belongapp/belong
import React from 'react'; import Relay from 'react-relay'; import NavLink from 'components/NavLink'; import styles from './styles.css'; import previewCardStyles from 'components/PreviewCard/styles.css'; class Track extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { track: React.PropTypes.shape({ id: React.PropTypes.string.isRequired, title: React.PropTypes.string.isRequired, }).isRequired, }; render() { return ( <NavLink to={`/track/${this.props.track.id}`} className={`${previewCardStyles.PreviewCard} ${styles.Wrapper}`} > <p className={styles.PlayButton}>▶</p> <p>{this.props.track.title}</p> </NavLink> ); } } export default Relay.createContainer(Track, { fragments: { track: () => Relay.QL`fragment on Track { id title }`, }, });
client/src/pages/dashboard/FeedItem.js
ccwukong/lfcommerce-react
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardTitle, } from 'reactstrap'; const FeedItem = props => { const { backgroundColor, fontColor, title, content, datetime } = props; return ( <Card body style={{ marginTop: 10, background: backgroundColor || '#fff' }}> <CardTitle style={{ color: fontColor || '#000', fontWeight: 200 }}> {title} </CardTitle> <div className="text-muted">{datetime}</div> <div className="text-muted">{content}</div> </Card> ); }; FeedItem.propTypes = { backgroundColor: PropTypes.string.isRequired, title: PropTypes.string.isRequired, fontColor: PropTypes.string.isRequired, content: PropTypes.string.isRequired, datetime: PropTypes.string.isRequired, }; export default FeedItem;
src/components/pages/UserProfile/panels/FeedsEmptyPanel.js
PulseTile/PulseTile-React
import React from 'react'; const FeedsEmptyPanel = props => { return null; }; export default FeedsEmptyPanel;
ui/src/containers/BasicQueryBuilder/Discrete/Criteria.js
LearningLocker/learninglocker
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Map } from 'immutable'; import Criterion from './Criterion'; import TempCriterion from './TempCriterion'; export default class Criteria extends Component { static propTypes = { section: PropTypes.instanceOf(Map), criteria: PropTypes.instanceOf(Map), onCriteriaChange: PropTypes.func, onDeleteCriterion: PropTypes.func, onAddCriterion: PropTypes.func, } shouldComponentUpdate = nextProps => !( this.props.section.equals(nextProps.section) && this.props.criteria.equals(nextProps.criteria) ); changeCriteria = (key, criterion) => { this.props.onCriteriaChange(this.props.criteria.set(key, criterion)); } addCriterion = () => { this.props.onAddCriterion(new Map({ $or: [], }), this.props.section); } createCriterion = (criterion) => { this.props.onAddCriterion(criterion, this.props.section); } deleteCriterion = (key) => { this.props.onDeleteCriterion(key); } renderCriterion = (criterion, key) => ( <Criterion section={this.props.section} criterion={criterion} onCriterionChange={this.changeCriteria.bind(this, key)} onDeleteCriterion={this.deleteCriterion.bind(this, key)} key={key} /> ); renderCriteria = () => ( <div> {this.props.criteria.map(this.renderCriterion.bind(this)).valueSeq()} </div> ); renderEmptyCriteria = () => ( <TempCriterion section={this.props.section} onCriterionChange={this.createCriterion} /> ); render = () => ( <div> {( this.props.criteria.count() > 0 ? this.renderCriteria() : this.renderEmptyCriteria() )} </div> ); }
ajax/libs/react-router/0.10.1/react-router.min.js
contolini/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&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}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){var LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:position?window.scrollTo(position.x,position.y):window.scrollTo(0,0)}}};module.exports=ImitateBrowserBehavior},{"../actions/LocationActions":1}],3:[function(_dereq_,module){var ScrollToTopBehavior={updateScrollPosition:function(){window.scrollTo(0,0)}};module.exports=ScrollToTopBehavior},{}],4:[function(_dereq_,module){function DefaultRoute(props){return Route(merge(props,{path:null,isDefault:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=DefaultRoute},{"./Route":8,"react/lib/merge":75}],5:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,classSet=_dereq_("react/lib/cx"),merge=_dereq_("react/lib/merge"),ActiveState=_dereq_("../mixins/ActiveState"),Navigation=_dereq_("../mixins/Navigation"),Link=React.createClass({displayName:"Link",mixins:[ActiveState,Navigation],propTypes:{activeClassName:React.PropTypes.string.isRequired,to:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(event){var clickResult,allowTransition=!0;this.props.onClick&&(clickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((clickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var classNames={};return this.props.className&&(classNames[this.props.className]=!0),this.isActive(this.props.to,this.props.params,this.props.query)&&(classNames[this.props.activeClassName]=!0),classSet(classNames)},render:function(){var props=merge(this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/ActiveState":15,"../mixins/Navigation":18,"react/lib/cx":65,"react/lib/merge":75}],6:[function(_dereq_,module){function NotFoundRoute(props){return Route(merge(props,{path:null,catchAll:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=NotFoundRoute},{"./Route":8,"react/lib/merge":75}],7:[function(_dereq_,module){function createRedirectHandler(to,_params,_query){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,_params||params,_query||query)}},render:function(){return null}})}function Redirect(props){return Route({name:props.name,path:props.from||props.path||"*",handler:createRedirectHandler(props.to,props.params,props.query)})}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Route=_dereq_("./Route");module.exports=Redirect},{"./Route":8}],8:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,withoutProperties=_dereq_("../utils/withoutProperties"),RESERVED_PROPS={handler:!0,path:!0,defaultRoute:!0,notFoundRoute:!0,paramNames:!0,children:!0},Route=React.createClass({displayName:"Route",statics:{getUnreservedProps:function(props){return withoutProperties(props,RESERVED_PROPS)}},propTypes:{handler:React.PropTypes.any.isRequired,path:React.PropTypes.string,name:React.PropTypes.string,ignoreScrollBehavior:React.PropTypes.bool},render:function(){throw new Error("The <Route> component should not be rendered directly. You may be missing a <Routes> wrapper around your list of routes.")}});module.exports=Route},{"../utils/withoutProperties":30}],9:[function(_dereq_,module){function makeMatch(route,params){return{route:route,params:params}}function getRootMatch(matches){return matches[matches.length-1]}function findMatches(path,routes,defaultRoute,notFoundRoute){for(var route,params,matches=null,i=0,len=routes.length;len>i;++i){if(route=routes[i],matches=findMatches(path,route.props.children,route.props.defaultRoute,route.props.notFoundRoute),null!=matches){var rootParams=getRootMatch(matches).params;return params=route.props.paramNames.reduce(function(params,paramName){return params[paramName]=rootParams[paramName],params},{}),matches.unshift(makeMatch(route,params)),matches}if(params=Path.extractParams(route.props.path,path))return[makeMatch(route,params)]}return defaultRoute&&(params=Path.extractParams(defaultRoute.props.path,path))?[makeMatch(defaultRoute,params)]:notFoundRoute&&(params=Path.extractParams(notFoundRoute.props.path,path))?[makeMatch(notFoundRoute,params)]:matches}function hasMatch(matches,match){return matches.some(function(m){if(m.route!==match.route)return!1;for(var property in m.params)if(m.params[property]!==match.params[property])return!1;return!0})}function runTransitionFromHooks(matches,transition,callback){var hooks=reversedArray(matches).map(function(match){return function(){var handler=match.route.props.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,match.component);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runTransitionToHooks(matches,transition,query,callback){var hooks=matches.map(function(match){return function(){var handler=match.route.props.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,match.params,query);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runHooks(hooks,callback){try{var promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function updateMatchComponents(matches,refs){for(var match,i=0,len=matches.length;len>i&&(match=matches[i],match.component=refs.__activeRoute__,null!=match.component);++i)refs=match.component.refs}function shouldUpdateScroll(currentMatches,previousMatches){var commonMatches=currentMatches.filter(function(match){return-1!==previousMatches.indexOf(match)});return!commonMatches.some(function(match){return match.route.props.ignoreScrollBehavior})}function returnNull(){return null}function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.props.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}function defaultTransitionErrorHandler(error){throw error}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),copyProperties=_dereq_("react/lib/copyProperties"),HashLocation=_dereq_("../locations/HashLocation"),ActiveContext=_dereq_("../mixins/ActiveContext"),LocationContext=_dereq_("../mixins/LocationContext"),RouteContext=_dereq_("../mixins/RouteContext"),ScrollContext=_dereq_("../mixins/ScrollContext"),reversedArray=_dereq_("../utils/reversedArray"),Transition=_dereq_("../utils/Transition"),Redirect=_dereq_("../utils/Redirect"),Path=_dereq_("../utils/Path"),Route=_dereq_("./Route"),Routes=React.createClass({displayName:"Routes",mixins:[RouteContext,ActiveContext,LocationContext,ScrollContext],propTypes:{initialPath:React.PropTypes.string,initialMatches:React.PropTypes.array,onChange:React.PropTypes.func,onError:React.PropTypes.func.isRequired},getDefaultProps:function(){return{initialPath:null,initialMatches:[],onError:defaultTransitionErrorHandler}},getInitialState:function(){return{path:this.props.initialPath,matches:this.props.initialMatches}},componentDidMount:function(){warning(null==this._owner,"<Routes> should be rendered directly using React.renderComponent, not inside some other component's render method"),this._handleStateChange()},componentDidUpdate:function(){this._handleStateChange()},match:function(path){var routes=this.getRoutes();return findMatches(Path.withoutQuery(path),routes,this.props.defaultRoute,this.props.notFoundRoute)},updateLocation:function(path,actionType){this.state.path!==path&&(this.state.path&&this.recordScroll(this.state.path),this.dispatch(path,function(error,abortReason,nextState){error?this.props.onError.call(this,error):abortReason instanceof Redirect?this.replaceWith(abortReason.to,abortReason.params,abortReason.query):abortReason?this.goBack():(this._nextStateChangeHandler=this._finishTransitionTo.bind(this,path,actionType,this.state.matches),this.setState(nextState))}))},_handleStateChange:function(){this._nextStateChangeHandler&&(this._nextStateChangeHandler(),delete this._nextStateChangeHandler)},_finishTransitionTo:function(path,actionType,previousMatches){var currentMatches=this.state.matches;updateMatchComponents(currentMatches,this.refs),shouldUpdateScroll(currentMatches,previousMatches)&&this.updateScroll(path,actionType),this.props.onChange&&this.props.onChange.call(this)},dispatch:function(path,callback){var transition=new Transition(this,path),currentMatches=this.state?this.state.matches:[],nextMatches=this.match(path)||[];warning(nextMatches.length,'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your <Routes>',path,path);var fromMatches,toMatches;currentMatches.length?(fromMatches=currentMatches.filter(function(match){return!hasMatch(nextMatches,match)}),toMatches=nextMatches.filter(function(match){return!hasMatch(currentMatches,match)})):(fromMatches=[],toMatches=nextMatches);var callbackScope=this,query=Path.extractQuery(path)||{};runTransitionFromHooks(fromMatches,transition,function(error){return error||transition.isAborted?callback.call(callbackScope,error,transition.abortReason):void runTransitionToHooks(toMatches,transition,query,function(error){if(error||transition.isAborted)return callback.call(callbackScope,error,transition.abortReason);var matches=currentMatches.slice(0,currentMatches.length-fromMatches.length).concat(toMatches),rootMatch=getRootMatch(matches),params=rootMatch&&rootMatch.params||{},routes=matches.map(function(match){return match.route});callback.call(callbackScope,null,null,{path:path,matches:matches,activeRoutes:routes,activeParams:params,activeQuery:query})})})},getHandlerProps:function(){var matches=this.state.matches,query=this.state.activeQuery,handler=returnNull,props={ref:null,params:null,query:null,activeRouteHandler:handler,key:null};return reversedArray(matches).forEach(function(match){var route=match.route;props=Route.getUnreservedProps(route.props),props.ref="__activeRoute__",props.params=match.params,props.query=query,props.activeRouteHandler=handler,route.props.addHandlerKey&&(props.key=Path.injectParams(route.props.path,match.params)),handler=function(props,addedProps){if(arguments.length>2&&"undefined"!=typeof arguments[2])throw new Error("Passing children to a route handler is not supported");return route.props.handler(copyProperties(props,addedProps))}.bind(this,props)}),props},getActiveComponent:function(){return this.refs.__activeRoute__},getCurrentPath:function(){return this.state.path},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var namedRoutes=this.getNamedRoutes(),route=namedRoutes[to];invariant(route,'Unable to find a route named "%s". Make sure you have <Route name="%s"> somewhere in your <Routes>',to,to),path=route.props.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return this.getLocation()===HashLocation?"#"+path:path},transitionTo:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use transitionTo without a location"),location.push(this.makePath(to,params,query))},replaceWith:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use replaceWith without a location"),location.replace(this.makePath(to,params,query))},goBack:function(){var location=this.getLocation();invariant(location,"You cannot use goBack without a location"),location.pop()},isActive:function(to,params,query){return Path.isAbsolute(to)?to===this.getCurrentPath():routeIsActive(this.getActiveRoutes(),to)&&paramsAreActive(this.getActiveParams(),params)&&(null==query||queryIsActive(this.getActiveQuery(),query))},render:function(){var match=this.state.matches[0];return null==match?null:match.route.props.handler(this.getHandlerProps())},childContextTypes:{currentPath:React.PropTypes.string,makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired,isActive:React.PropTypes.func.isRequired},getChildContext:function(){return{currentPath:this.getCurrentPath(),makePath:this.makePath,makeHref:this.makeHref,transitionTo:this.transitionTo,replaceWith:this.replaceWith,goBack:this.goBack,isActive:this.isActive}}});module.exports=Routes},{"../locations/HashLocation":11,"../mixins/ActiveContext":14,"../mixins/LocationContext":17,"../mixins/RouteContext":19,"../mixins/ScrollContext":20,"../utils/Path":22,"../utils/Redirect":24,"../utils/Transition":26,"../utils/reversedArray":28,"./Route":8,"react/lib/copyProperties":64,"react/lib/invariant":70,"react/lib/warning":77}],10:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.Routes=_dereq_("./components/Routes"),exports.ActiveState=_dereq_("./mixins/ActiveState"),exports.CurrentPath=_dereq_("./mixins/CurrentPath"),exports.Navigation=_dereq_("./mixins/Navigation"),exports.renderRoutesToString=_dereq_("./utils/ServerRendering").renderRoutesToString,exports.renderRoutesToStaticMarkup=_dereq_("./utils/ServerRendering").renderRoutesToStaticMarkup},{"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/Routes":9,"./mixins/ActiveState":15,"./mixins/CurrentPath":16,"./mixins/Navigation":18,"./utils/ServerRendering":25}],11:[function(_dereq_,module){function getHashPath(){return window.location.hash.substr(1)}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function onHashChange(){if(ensureSlash()){{getHashPath()}_onChange({type:_actionType||LocationActions.POP,path:getHashPath()}),_actionType=null}}var _actionType,_onChange,LocationActions=_dereq_("../actions/LocationActions"),getWindowPath=_dereq_("../utils/getWindowPath"),HashLocation={setup:function(onChange){_onChange=onChange,ensureSlash(),window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange)},teardown:function(){window.removeEventListener?window.removeEventListener("hashchange",onHashChange,!1):window.detachEvent("onhashchange",onHashChange)},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=path},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(getWindowPath()+"#"+path)},pop:function(){_actionType=LocationActions.POP,window.history.back()},getCurrentPath:getHashPath,toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../utils/getWindowPath":27}],12:[function(_dereq_,module){function onPopState(){_onChange({type:LocationActions.POP,path:getWindowPath()})}var _onChange,LocationActions=_dereq_("../actions/LocationActions"),getWindowPath=_dereq_("../utils/getWindowPath"),HistoryLocation={setup:function(onChange){_onChange=onChange,window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState)},teardown:function(){window.removeEventListener?window.removeEventListener("popstate",onPopState,!1):window.detachEvent("popstate",onPopState)},push:function(path){window.history.pushState({path:path},"",path),_onChange({type:LocationActions.PUSH,path:getWindowPath()})},replace:function(path){window.history.replaceState({path:path},"",path),_onChange({type:LocationActions.REPLACE,path:getWindowPath()})},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../utils/getWindowPath":27}],13:[function(_dereq_,module){var getWindowPath=_dereq_("../utils/getWindowPath"),RefreshLocation={push:function(path){window.location=path},replace:function(path){window.location.replace(path)},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../utils/getWindowPath":27}],14:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,copyProperties=_dereq_("react/lib/copyProperties"),ActiveContext={propTypes:{initialActiveRoutes:React.PropTypes.array.isRequired,initialActiveParams:React.PropTypes.object.isRequired,initialActiveQuery:React.PropTypes.object.isRequired},getDefaultProps:function(){return{initialActiveRoutes:[],initialActiveParams:{},initialActiveQuery:{}}},getInitialState:function(){return{activeRoutes:this.props.initialActiveRoutes,activeParams:this.props.initialActiveParams,activeQuery:this.props.initialActiveQuery}},getActiveRoutes:function(){return this.state.activeRoutes.slice(0)},getActiveParams:function(){return copyProperties({},this.state.activeParams)},getActiveQuery:function(){return copyProperties({},this.state.activeQuery)},childContextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired},getChildContext:function(){return{activeRoutes:this.getActiveRoutes(),activeParams:this.getActiveParams(),activeQuery:this.getActiveQuery()}}};module.exports=ActiveContext},{"react/lib/copyProperties":64}],15:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,ActiveState={contextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired,isActive:React.PropTypes.func.isRequired},getActiveRoutes:function(){return this.context.activeRoutes},getActiveParams:function(){return this.context.activeParams},getActiveQuery:function(){return this.context.activeQuery},isActive:function(to,params,query){return this.context.isActive(to,params,query)}};module.exports=ActiveState},{}],16:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,CurrentPath={contextTypes:{currentPath:React.PropTypes.string.isRequired},getCurrentPath:function(){return this.context.currentPath}};module.exports=CurrentPath},{}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),RefreshLocation=_dereq_("../locations/RefreshLocation"),PathStore=_dereq_("../stores/PathStore"),supportsHistory=_dereq_("../utils/supportsHistory"),NAMED_LOCATIONS={none:null,hash:HashLocation,history:HistoryLocation,refresh:RefreshLocation},LocationContext={propTypes:{location:function(props,propName,componentName){var location=props[propName];return"string"!=typeof location||location in NAMED_LOCATIONS?void 0:new Error('Unknown location "'+location+'", see '+componentName)}},getDefaultProps:function(){return{location:canUseDOM?HashLocation:null}},componentWillMount:function(){var location=this.getLocation();invariant(null==location||canUseDOM,"Cannot use location without a DOM"),location&&(PathStore.setup(location),PathStore.addChangeListener(this.handlePathChange),this.updateLocation&&this.updateLocation(PathStore.getCurrentPath(),PathStore.getCurrentActionType()))},componentWillUnmount:function(){this.getLocation()&&PathStore.removeChangeListener(this.handlePathChange)},handlePathChange:function(){this.updateLocation&&this.updateLocation(PathStore.getCurrentPath(),PathStore.getCurrentActionType())},getLocation:function(){if(null==this._location){var location=this.props.location;"string"==typeof location&&(location=NAMED_LOCATIONS[location]),location!==HistoryLocation||supportsHistory()||(location=RefreshLocation),this._location=location}return this._location},childContextTypes:{location:React.PropTypes.object},getChildContext:function(){return{location:this.getLocation()}}};module.exports=LocationContext},{"../locations/HashLocation":11,"../locations/HistoryLocation":12,"../locations/RefreshLocation":13,"../stores/PathStore":21,"../utils/supportsHistory":29,"react/lib/ExecutionEnvironment":42,"react/lib/invariant":70}],18:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Navigation={contextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},makePath:function(to,params,query){return this.context.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.makeHref(to,params,query)},transitionTo:function(to,params,query){this.context.transitionTo(to,params,query)},replaceWith:function(to,params,query){this.context.replaceWith(to,params,query)},goBack:function(){this.context.goBack()}};module.exports=Navigation},{}],19:[function(_dereq_,module){function processRoute(route,container,namedRoutes){var props=route.props,parentPath=container&&container.props.path||"/";if(!props.path&&!props.name||props.isDefault||props.catchAll)props.path=parentPath,props.catchAll&&(props.path+="*");else{var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),props.path=Path.normalize(path)}if(props.paramNames=Path.extractParamNames(props.path),container&&Array.isArray(container.props.paramNames)&&container.props.paramNames.forEach(function(paramName){invariant(-1!==props.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',props.path,paramName,container.props.path)}),props.name){var existingRoute=namedRoutes[props.name];invariant(!existingRoute||route===existingRoute,'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route}return props.catchAll?(invariant(container,"<NotFoundRoute> must have a parent <Route>"),invariant(null==container.props.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),container.props.notFoundRoute=route,null):props.isDefault?(invariant(container,"<DefaultRoute> must have a parent <Route>"),invariant(null==container.props.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),container.props.defaultRoute=route,null):(props.children=processRoutes(props.children,route,namedRoutes),route)}function processRoutes(children,container,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=processRoute(child,container,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),Path=_dereq_("../utils/Path"),RouteContext={_processRoutes:function(){this._namedRoutes={},this._routes=processRoutes(this.props.children,this,this._namedRoutes)},getRoutes:function(){return null==this._routes&&this._processRoutes(),this._routes},getNamedRoutes:function(){return null==this._namedRoutes&&this._processRoutes(),this._namedRoutes},getRouteByName:function(routeName){var namedRoutes=this.getNamedRoutes();return namedRoutes[routeName]||null},childContextTypes:{routes:React.PropTypes.array.isRequired,namedRoutes:React.PropTypes.object.isRequired},getChildContext:function(){return{routes:this.getRoutes(),namedRoutes:this.getNamedRoutes()}}};module.exports=RouteContext},{"../utils/Path":22,"react/lib/invariant":70}],20:[function(_dereq_,module){function getWindowScrollPosition(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.scrollX,y:window.scrollY}}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,ImitateBrowserBehavior=_dereq_("../behaviors/ImitateBrowserBehavior"),ScrollToTopBehavior=_dereq_("../behaviors/ScrollToTopBehavior"),NAMED_SCROLL_BEHAVIORS={none:null,browser:ImitateBrowserBehavior,imitateBrowser:ImitateBrowserBehavior,scrollToTop:ScrollToTopBehavior},ScrollContext={propTypes:{scrollBehavior:function(props,propName,componentName){var behavior=props[propName];return"string"!=typeof behavior||behavior in NAMED_SCROLL_BEHAVIORS?void 0:new Error('Unknown scroll behavior "'+behavior+'", see '+componentName)}},getDefaultProps:function(){return{scrollBehavior:canUseDOM?ImitateBrowserBehavior:null}},componentWillMount:function(){invariant(null==this.getScrollBehavior()||canUseDOM,"Cannot use scroll behavior without a DOM")},recordScroll:function(path){var positions=this.getScrollPositions();positions[path]=getWindowScrollPosition()},updateScroll:function(path,actionType){var behavior=this.getScrollBehavior(),position=this.getScrollPosition(path)||null;behavior&&behavior.updateScrollPosition(position,actionType)},getScrollBehavior:function(){if(null==this._scrollBehavior){var behavior=this.props.scrollBehavior;"string"==typeof behavior&&(behavior=NAMED_SCROLL_BEHAVIORS[behavior]),this._scrollBehavior=behavior}return this._scrollBehavior},getScrollPositions:function(){return null==this._scrollPositions&&(this._scrollPositions={}),this._scrollPositions},getScrollPosition:function(path){var positions=this.getScrollPositions();return positions[path]},childContextTypes:{scrollBehavior:React.PropTypes.object},getChildContext:function(){return{scrollBehavior:this.getScrollBehavior()}}};module.exports=ScrollContext},{"../behaviors/ImitateBrowserBehavior":2,"../behaviors/ScrollToTopBehavior":3,"react/lib/ExecutionEnvironment":42,"react/lib/invariant":70}],21:[function(_dereq_,module){function notifyChange(){_events.emit(CHANGE_EVENT)}function handleLocationChangeAction(action){_currentPath!==action.path&&(_currentPath=action.path,_currentActionType=action.type,notifyChange())}var _currentLocation,_currentActionType,invariant=_dereq_("react/lib/invariant"),EventEmitter=_dereq_("events").EventEmitter,CHANGE_EVENT=(_dereq_("../actions/LocationActions"),"change"),_events=new EventEmitter,_currentPath="/",PathStore={addChangeListener:function(listener){_events.addListener(CHANGE_EVENT,listener)},removeChangeListener:function(listener){_events.removeListener(CHANGE_EVENT,listener)},removeAllChangeListeners:function(){_events.removeAllListeners(CHANGE_EVENT)},setup:function(location){invariant(null==_currentLocation||_currentLocation===location,"You cannot use %s and %s on the same page",_currentLocation,location),_currentLocation!==location&&(location.setup&&location.setup(handleLocationChangeAction),_currentPath=location.getCurrentPath()),_currentLocation=location},teardown:function(){_currentLocation&&_currentLocation.teardown&&_currentLocation.teardown(),_currentLocation=_currentActionType=null,_currentPath="/",PathStore.removeAllChangeListeners()},getCurrentPath:function(){return _currentPath},getCurrentActionType:function(){return _currentActionType}};module.exports=PathStore},{"../actions/LocationActions":1,events:31,"react/lib/invariant":70}],22:[function(_dereq_,module){function encodeURL(url){return encodeURIComponent(url).replace(/%20/g,"+")}function decodeURL(url){return decodeURIComponent(url.replace(/\+/g," "))}function encodeURLPath(path){return String(path).split("/").map(encodeURL).join("/")}function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramCompileMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramCompileMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,paramInjectMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g,paramInjectTrailingSlashMatcher=/\/\/\?|\/\?/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=decodeURL(path).match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramInjectMatcher,function(match,paramName){if(paramName=paramName||"splat","?"!==paramName.slice(-1))invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');else if(paramName=paramName.slice(0,-1),null==params[paramName])return"";var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],encodeURLPath(segment)}).replace(paramInjectTrailingSlashMatcher,"/")},extractQuery:function(path){var match=path.match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path },isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:32,"qs/lib/utils":36,"react/lib/invariant":70}],23:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":78}],24:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],25:[function(_dereq_,module){function cloneRoutesForServerRendering(routes){return cloneWithProps(routes,{location:"none",scrollBehavior:"none"})}function mergeStateIntoInitialProps(state,props){copyProperties(props,{initialPath:state.path,initialMatches:state.matches,initialActiveRoutes:state.activeRoutes,initialActiveParams:state.activeParams,initialActiveQuery:state.activeQuery})}function renderRoutesToString(routes,path,callback){invariant(ReactElement.isValidElement(routes),"You must pass a valid ReactComponent to renderRoutesToString");var component=instantiateReactComponent(cloneRoutesForServerRendering(routes));component.dispatch(path,function(error,abortReason,nextState){if(error||abortReason)return callback(error,abortReason);mergeStateIntoInitialProps(nextState,component.props);var transaction;try{var id=ReactInstanceHandles.createReactRootID();transaction=ReactServerRenderingTransaction.getPooled(!1),transaction.perform(function(){var markup=component.mountComponent(id,transaction,0);callback(null,null,ReactMarkupChecksum.addChecksumToMarkup(markup))},null)}finally{ReactServerRenderingTransaction.release(transaction)}})}function renderRoutesToStaticMarkup(routes,path,callback){invariant(ReactElement.isValidElement(routes),"You must pass a valid ReactComponent to renderRoutesToStaticMarkup");var component=instantiateReactComponent(cloneRoutesForServerRendering(routes));component.dispatch(path,function(error,abortReason,nextState){if(error||abortReason)return callback(error,abortReason);mergeStateIntoInitialProps(nextState,component.props);var transaction;try{var id=ReactInstanceHandles.createReactRootID();transaction=ReactServerRenderingTransaction.getPooled(!1),transaction.perform(function(){callback(null,null,component.mountComponent(id,transaction,0))},null)}finally{ReactServerRenderingTransaction.release(transaction)}})}var ReactElement=_dereq_("react/lib/ReactElement"),ReactInstanceHandles=_dereq_("react/lib/ReactInstanceHandles"),ReactMarkupChecksum=_dereq_("react/lib/ReactMarkupChecksum"),ReactServerRenderingTransaction=_dereq_("react/lib/ReactServerRenderingTransaction"),cloneWithProps=_dereq_("react/lib/cloneWithProps"),copyProperties=_dereq_("react/lib/copyProperties"),instantiateReactComponent=_dereq_("react/lib/instantiateReactComponent"),invariant=_dereq_("react/lib/invariant");module.exports={renderRoutesToString:renderRoutesToString,renderRoutesToStaticMarkup:renderRoutesToStaticMarkup}},{"react/lib/ReactElement":48,"react/lib/ReactInstanceHandles":51,"react/lib/ReactMarkupChecksum":53,"react/lib/ReactServerRenderingTransaction":58,"react/lib/cloneWithProps":63,"react/lib/copyProperties":64,"react/lib/instantiateReactComponent":69,"react/lib/invariant":70}],26:[function(_dereq_,module){function Transition(routesComponent,path){this.routesComponent=routesComponent,this.path=path,this.abortReason=null,this.isAborted=!1}var Promise=_dereq_("./Promise"),Redirect=_dereq_("./Redirect");Transition.prototype.abort=function(reason){this.abortReason=reason,this.isAborted=!0},Transition.prototype.redirect=function(to,params,query){this.abort(new Redirect(to,params,query))},Transition.prototype.wait=function(value){this.promise=Promise.resolve(value)},Transition.prototype.retry=function(){this.routesComponent.replaceWith(this.path)},module.exports=Transition},{"./Promise":23,"./Redirect":24}],27:[function(_dereq_,module){function getWindowPath(){return window.location.pathname+window.location.search}module.exports=getWindowPath},{}],28:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],29:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],30:[function(_dereq_,module){function withoutProperties(object,properties){var result={};for(var property in object)object.hasOwnProperty(property)&&!properties[property]&&(result[property]=object[property]);return result}module.exports=withoutProperties},{}],31:[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))throw er=arguments[1],er instanceof Error?er:TypeError('Uncaught, unspecified "error" event.');if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],32:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":33}],33:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse");module.exports={stringify:Stringify,parse:Parse}},{"./parse":34,"./stringify":35}],34:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":36}],35:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":36}],36:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],37:[function(_dereq_,module){"use strict";function CallbackQueue(){this._callbacks=null,this._contexts=null}var PooledClass=_dereq_("./PooledClass"),assign=_dereq_("./Object.assign"),invariant=_dereq_("./invariant");assign(CallbackQueue.prototype,{enqueue:function(callback,context){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(callback),this._contexts.push(context)},notifyAll:function(){var callbacks=this._callbacks,contexts=this._contexts;if(callbacks){invariant(callbacks.length===contexts.length),this._callbacks=null,this._contexts=null;for(var i=0,l=callbacks.length;l>i;i++)callbacks[i].call(contexts[i]);callbacks.length=0,contexts.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),PooledClass.addPoolingTo(CallbackQueue),module.exports=CallbackQueue},{"./Object.assign":43,"./PooledClass":44,"./invariant":70}],38:[function(_dereq_,module){"use strict";var keyMirror=_dereq_("./keyMirror"),PropagationPhases=keyMirror({bubbled:null,captured:null}),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,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),EventConstants={topLevelTypes:topLevelTypes,PropagationPhases:PropagationPhases};module.exports=EventConstants},{"./keyMirror":73}],39:[function(_dereq_,module){"use strict";var EventPluginRegistry=_dereq_("./EventPluginRegistry"),EventPluginUtils=_dereq_("./EventPluginUtils"),accumulateInto=_dereq_("./accumulateInto"),forEachAccumulated=_dereq_("./forEachAccumulated"),invariant=_dereq_("./invariant"),listenerBank={},eventQueue=null,executeDispatchesAndRelease=function(event){if(event){var executeDispatch=EventPluginUtils.executeDispatch,PluginModule=EventPluginRegistry.getPluginModuleForEvent(event);PluginModule&&PluginModule.executeDispatch&&(executeDispatch=PluginModule.executeDispatch),EventPluginUtils.executeDispatchesInOrder(event,executeDispatch),event.isPersistent()||event.constructor.release(event)}},InstanceHandle=null,EventPluginHub={injection:{injectMount:EventPluginUtils.injection.injectMount,injectInstanceHandle:function(InjectedInstanceHandle){InstanceHandle=InjectedInstanceHandle},getInstanceHandle:function(){return InstanceHandle},injectEventPluginOrder:EventPluginRegistry.injectEventPluginOrder,injectEventPluginsByName:EventPluginRegistry.injectEventPluginsByName},eventNameDispatchConfigs:EventPluginRegistry.eventNameDispatchConfigs,registrationNameModules:EventPluginRegistry.registrationNameModules,putListener:function(id,registrationName,listener){invariant(!listener||"function"==typeof listener);var bankForRegistrationName=listenerBank[registrationName]||(listenerBank[registrationName]={});bankForRegistrationName[id]=listener},getListener:function(id,registrationName){var bankForRegistrationName=listenerBank[registrationName];return bankForRegistrationName&&bankForRegistrationName[id]},deleteListener:function(id,registrationName){var bankForRegistrationName=listenerBank[registrationName];bankForRegistrationName&&delete bankForRegistrationName[id]},deleteAllListeners:function(id){for(var registrationName in listenerBank)delete listenerBank[registrationName][id]},extractEvents:function(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent){for(var events,plugins=EventPluginRegistry.plugins,i=0,l=plugins.length;l>i;i++){var possiblePlugin=plugins[i];if(possiblePlugin){var extractedEvents=possiblePlugin.extractEvents(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent);extractedEvents&&(events=accumulateInto(events,extractedEvents))}}return events},enqueueEvents:function(events){events&&(eventQueue=accumulateInto(eventQueue,events))},processEventQueue:function(){var processingEventQueue=eventQueue;eventQueue=null,forEachAccumulated(processingEventQueue,executeDispatchesAndRelease),invariant(!eventQueue)},__purge:function(){listenerBank={}},__getListenerBank:function(){return listenerBank}};module.exports=EventPluginHub},{"./EventPluginRegistry":40,"./EventPluginUtils":41,"./accumulateInto":61,"./forEachAccumulated":67,"./invariant":70}],40:[function(_dereq_,module){"use strict";function recomputePluginOrdering(){if(EventPluginOrder)for(var pluginName in namesToPlugins){var PluginModule=namesToPlugins[pluginName],pluginIndex=EventPluginOrder.indexOf(pluginName);if(invariant(pluginIndex>-1),!EventPluginRegistry.plugins[pluginIndex]){invariant(PluginModule.extractEvents),EventPluginRegistry.plugins[pluginIndex]=PluginModule;var publishedEvents=PluginModule.eventTypes;for(var eventName in publishedEvents)invariant(publishEventForPlugin(publishedEvents[eventName],PluginModule,eventName))}}}function publishEventForPlugin(dispatchConfig,PluginModule,eventName){invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(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!0}return dispatchConfig.registrationName?(publishRegistrationName(dispatchConfig.registrationName,PluginModule,eventName),!0):!1}function publishRegistrationName(registrationName,PluginModule,eventName){invariant(!EventPluginRegistry.registrationNameModules[registrationName]),EventPluginRegistry.registrationNameModules[registrationName]=PluginModule,EventPluginRegistry.registrationNameDependencies[registrationName]=PluginModule.eventTypes[eventName].dependencies}var invariant=_dereq_("./invariant"),EventPluginOrder=null,namesToPlugins={},EventPluginRegistry={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(InjectedEventPluginOrder){invariant(!EventPluginOrder),EventPluginOrder=Array.prototype.slice.call(InjectedEventPluginOrder),recomputePluginOrdering()},injectEventPluginsByName:function(injectedNamesToPlugins){var isOrderingDirty=!1;for(var pluginName in injectedNamesToPlugins)if(injectedNamesToPlugins.hasOwnProperty(pluginName)){var PluginModule=injectedNamesToPlugins[pluginName];namesToPlugins.hasOwnProperty(pluginName)&&namesToPlugins[pluginName]===PluginModule||(invariant(!namesToPlugins[pluginName]),namesToPlugins[pluginName]=PluginModule,isOrderingDirty=!0)}isOrderingDirty&&recomputePluginOrdering()},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)){var PluginModule=EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];if(PluginModule)return PluginModule}return null},_resetEventPlugins:function(){EventPluginOrder=null;for(var pluginName in namesToPlugins)namesToPlugins.hasOwnProperty(pluginName)&&delete namesToPlugins[pluginName];EventPluginRegistry.plugins.length=0;var eventNameDispatchConfigs=EventPluginRegistry.eventNameDispatchConfigs;for(var eventName in eventNameDispatchConfigs)eventNameDispatchConfigs.hasOwnProperty(eventName)&&delete eventNameDispatchConfigs[eventName];var registrationNameModules=EventPluginRegistry.registrationNameModules;for(var registrationName in registrationNameModules)registrationNameModules.hasOwnProperty(registrationName)&&delete registrationNameModules[registrationName]}};module.exports=EventPluginRegistry},{"./invariant":70}],41:[function(_dereq_,module){"use strict";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}function forEachEventDispatch(event,cb){var dispatchListeners=event._dispatchListeners,dispatchIDs=event._dispatchIDs;if(Array.isArray(dispatchListeners))for(var i=0;i<dispatchListeners.length&&!event.isPropagationStopped();i++)cb(event,dispatchListeners[i],dispatchIDs[i]);else dispatchListeners&&cb(event,dispatchListeners,dispatchIDs)}function executeDispatch(event,listener,domID){event.currentTarget=injection.Mount.getNode(domID);var returnValue=listener(event,domID);return event.currentTarget=null,returnValue}function executeDispatchesInOrder(event,executeDispatch){forEachEventDispatch(event,executeDispatch),event._dispatchListeners=null,event._dispatchIDs=null}function executeDispatchesInOrderStopAtTrueImpl(event){var dispatchListeners=event._dispatchListeners,dispatchIDs=event._dispatchIDs;if(Array.isArray(dispatchListeners)){for(var i=0;i<dispatchListeners.length&&!event.isPropagationStopped();i++)if(dispatchListeners[i](event,dispatchIDs[i]))return dispatchIDs[i]}else if(dispatchListeners&&dispatchListeners(event,dispatchIDs))return dispatchIDs;return null}function executeDispatchesInOrderStopAtTrue(event){var ret=executeDispatchesInOrderStopAtTrueImpl(event);return event._dispatchIDs=null,event._dispatchListeners=null,ret}function executeDirectDispatch(event){var dispatchListener=event._dispatchListeners,dispatchID=event._dispatchIDs;invariant(!Array.isArray(dispatchListener));var res=dispatchListener?dispatchListener(event,dispatchID):null;return event._dispatchListeners=null,event._dispatchIDs=null,res}function hasDispatches(event){return!!event._dispatchListeners}var EventConstants=_dereq_("./EventConstants"),invariant=_dereq_("./invariant"),injection={Mount:null,injectMount:function(InjectedMount){injection.Mount=InjectedMount}},topLevelTypes=EventConstants.topLevelTypes,EventPluginUtils={isEndish:isEndish,isMoveish:isMoveish,isStartish:isStartish,executeDirectDispatch:executeDirectDispatch,executeDispatch:executeDispatch,executeDispatchesInOrder:executeDispatchesInOrder,executeDispatchesInOrderStopAtTrue:executeDispatchesInOrderStopAtTrue,hasDispatches:hasDispatches,injection:injection,useTouchEvents:!1};module.exports=EventPluginUtils},{"./EventConstants":38,"./invariant":70}],42:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],43:[function(_dereq_,module){function assign(target){if(null==target)throw new TypeError("Object.assign target cannot be null or undefined");for(var to=Object(target),hasOwnProperty=Object.prototype.hasOwnProperty,nextIndex=1;nextIndex<arguments.length;nextIndex++){var nextSource=arguments[nextIndex];if(null!=nextSource){var from=Object(nextSource);for(var key in from)hasOwnProperty.call(from,key)&&(to[key]=from[key])}}return to}module.exports=assign},{}],44:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),oneArgumentPooler=function(copyFieldsFrom){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,copyFieldsFrom),instance}return new Klass(copyFieldsFrom)},twoArgumentPooler=function(a1,a2){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,a1,a2),instance}return new Klass(a1,a2)},threeArgumentPooler=function(a1,a2,a3){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,a1,a2,a3),instance}return new Klass(a1,a2,a3)},fiveArgumentPooler=function(a1,a2,a3,a4,a5){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,a1,a2,a3,a4,a5),instance}return new Klass(a1,a2,a3,a4,a5)},standardReleaser=function(instance){var Klass=this;invariant(instance instanceof Klass),instance.destructor&&instance.destructor(),Klass.instancePool.length<Klass.poolSize&&Klass.instancePool.push(instance)},DEFAULT_POOL_SIZE=10,DEFAULT_POOLER=oneArgumentPooler,addPoolingTo=function(CopyConstructor,pooler){var NewKlass=CopyConstructor;return NewKlass.instancePool=[],NewKlass.getPooled=pooler||DEFAULT_POOLER,NewKlass.poolSize||(NewKlass.poolSize=DEFAULT_POOL_SIZE),NewKlass.release=standardReleaser,NewKlass},PooledClass={addPoolingTo:addPoolingTo,oneArgumentPooler:oneArgumentPooler,twoArgumentPooler:twoArgumentPooler,threeArgumentPooler:threeArgumentPooler,fiveArgumentPooler:fiveArgumentPooler};module.exports=PooledClass},{"./invariant":70}],45:[function(_dereq_,module){"use strict";function getListeningForDocument(mountAt){return Object.prototype.hasOwnProperty.call(mountAt,topListenersIDKey)||(mountAt[topListenersIDKey]=reactTopListenersCounter++,alreadyListeningTo[mountAt[topListenersIDKey]]={}),alreadyListeningTo[mountAt[topListenersIDKey]]}var EventConstants=_dereq_("./EventConstants"),EventPluginHub=_dereq_("./EventPluginHub"),EventPluginRegistry=_dereq_("./EventPluginRegistry"),ReactEventEmitterMixin=_dereq_("./ReactEventEmitterMixin"),ViewportMetrics=_dereq_("./ViewportMetrics"),assign=_dereq_("./Object.assign"),isEventSupported=_dereq_("./isEventSupported"),alreadyListeningTo={},isMonitoringScrollValue=!1,reactTopListenersCounter=0,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",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},topListenersIDKey="_reactListenersID"+String(Math.random()).slice(2),ReactBrowserEventEmitter=assign({},ReactEventEmitterMixin,{ReactEventListener:null,injection:{injectReactEventListener:function(ReactEventListener){ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel),ReactBrowserEventEmitter.ReactEventListener=ReactEventListener}},setEnabled:function(enabled){ReactBrowserEventEmitter.ReactEventListener&&ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled)},isEnabled:function(){return!(!ReactBrowserEventEmitter.ReactEventListener||!ReactBrowserEventEmitter.ReactEventListener.isEnabled())},listenTo:function(registrationName,contentDocumentHandle){for(var mountAt=contentDocumentHandle,isListening=getListeningForDocument(mountAt),dependencies=EventPluginRegistry.registrationNameDependencies[registrationName],topLevelTypes=EventConstants.topLevelTypes,i=0,l=dependencies.length;l>i;i++){var dependency=dependencies[i];isListening.hasOwnProperty(dependency)&&isListening[dependency]||(dependency===topLevelTypes.topWheel?isEventSupported("wheel")?ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel,"wheel",mountAt):isEventSupported("mousewheel")?ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel,"mousewheel",mountAt):ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel,"DOMMouseScroll",mountAt):dependency===topLevelTypes.topScroll?isEventSupported("scroll",!0)?ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll,"scroll",mountAt):ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll,"scroll",ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE):dependency===topLevelTypes.topFocus||dependency===topLevelTypes.topBlur?(isEventSupported("focus",!0)?(ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus,"focus",mountAt),ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur,"blur",mountAt)):isEventSupported("focusin")&&(ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus,"focusin",mountAt),ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur,"focusout",mountAt)),isListening[topLevelTypes.topBlur]=!0,isListening[topLevelTypes.topFocus]=!0):topEventMapping.hasOwnProperty(dependency)&&ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency,topEventMapping[dependency],mountAt),isListening[dependency]=!0)}},trapBubbledEvent:function(topLevelType,handlerBaseName,handle){return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType,handlerBaseName,handle)},trapCapturedEvent:function(topLevelType,handlerBaseName,handle){return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType,handlerBaseName,handle) },ensureScrollValueMonitoring:function(){if(!isMonitoringScrollValue){var refresh=ViewportMetrics.refreshScrollValues;ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh),isMonitoringScrollValue=!0}},eventNameDispatchConfigs:EventPluginHub.eventNameDispatchConfigs,registrationNameModules:EventPluginHub.registrationNameModules,putListener:EventPluginHub.putListener,getListener:EventPluginHub.getListener,deleteListener:EventPluginHub.deleteListener,deleteAllListeners:EventPluginHub.deleteAllListeners});module.exports=ReactBrowserEventEmitter},{"./EventConstants":38,"./EventPluginHub":39,"./EventPluginRegistry":40,"./Object.assign":43,"./ReactEventEmitterMixin":50,"./ViewportMetrics":60,"./isEventSupported":71}],46:[function(_dereq_,module){"use strict";var assign=_dereq_("./Object.assign"),ReactContext={current:{},withContext:function(newContext,scopedCallback){var result,previousContext=ReactContext.current;ReactContext.current=assign({},previousContext,newContext);try{result=scopedCallback()}finally{ReactContext.current=previousContext}return result}};module.exports=ReactContext},{"./Object.assign":43}],47:[function(_dereq_,module){"use strict";var ReactCurrentOwner={current:null};module.exports=ReactCurrentOwner},{}],48:[function(_dereq_,module){"use strict";var ReactContext=_dereq_("./ReactContext"),ReactCurrentOwner=_dereq_("./ReactCurrentOwner"),RESERVED_PROPS=(_dereq_("./warning"),{key:!0,ref:!0}),ReactElement=function(type,key,ref,owner,context,props){this.type=type,this.key=key,this.ref=ref,this._owner=owner,this._context=context,this.props=props};ReactElement.prototype={_isReactElement:!0},ReactElement.createElement=function(type,config,children){var propName,props={},key=null,ref=null;if(null!=config){ref=void 0===config.ref?null:config.ref,key=null==config.key?null:""+config.key;for(propName in config)config.hasOwnProperty(propName)&&!RESERVED_PROPS.hasOwnProperty(propName)&&(props[propName]=config[propName])}var childrenLength=arguments.length-2;if(1===childrenLength)props.children=children;else if(childrenLength>1){for(var childArray=Array(childrenLength),i=0;childrenLength>i;i++)childArray[i]=arguments[i+2];props.children=childArray}if(type.defaultProps){var defaultProps=type.defaultProps;for(propName in defaultProps)"undefined"==typeof props[propName]&&(props[propName]=defaultProps[propName])}return new ReactElement(type,key,ref,ReactCurrentOwner.current,ReactContext.current,props)},ReactElement.createFactory=function(type){var factory=ReactElement.createElement.bind(null,type);return factory.type=type,factory},ReactElement.cloneAndReplaceProps=function(oldElement,newProps){var newElement=new ReactElement(oldElement.type,oldElement.key,oldElement.ref,oldElement._owner,oldElement._context,newProps);return newElement},ReactElement.isValidElement=function(object){var isElement=!(!object||!object._isReactElement);return isElement},module.exports=ReactElement},{"./ReactContext":46,"./ReactCurrentOwner":47,"./warning":77}],49:[function(_dereq_,module){"use strict";function getEmptyComponent(){return invariant(component),component()}function registerNullComponentID(id){nullComponentIdsRegistry[id]=!0}function deregisterNullComponentID(id){delete nullComponentIdsRegistry[id]}function isNullComponentID(id){return nullComponentIdsRegistry[id]}var component,ReactElement=_dereq_("./ReactElement"),invariant=_dereq_("./invariant"),nullComponentIdsRegistry={},ReactEmptyComponentInjection={injectEmptyComponent:function(emptyComponent){component=ReactElement.createFactory(emptyComponent)}},ReactEmptyComponent={deregisterNullComponentID:deregisterNullComponentID,getEmptyComponent:getEmptyComponent,injection:ReactEmptyComponentInjection,isNullComponentID:isNullComponentID,registerNullComponentID:registerNullComponentID};module.exports=ReactEmptyComponent},{"./ReactElement":48,"./invariant":70}],50:[function(_dereq_,module){"use strict";function runEventQueueInBatch(events){EventPluginHub.enqueueEvents(events),EventPluginHub.processEventQueue()}var EventPluginHub=_dereq_("./EventPluginHub"),ReactEventEmitterMixin={handleTopLevel:function(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent){var events=EventPluginHub.extractEvents(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent);runEventQueueInBatch(events)}};module.exports=ReactEventEmitterMixin},{"./EventPluginHub":39}],51:[function(_dereq_,module){"use strict";function getReactRootIDString(index){return SEPARATOR+index.toString(36)}function isBoundary(id,index){return id.charAt(index)===SEPARATOR||index===id.length}function isValidID(id){return""===id||id.charAt(0)===SEPARATOR&&id.charAt(id.length-1)!==SEPARATOR}function isAncestorIDOf(ancestorID,descendantID){return 0===descendantID.indexOf(ancestorID)&&isBoundary(descendantID,ancestorID.length)}function getParentID(id){return id?id.substr(0,id.lastIndexOf(SEPARATOR)):""}function getNextDescendantID(ancestorID,destinationID){if(invariant(isValidID(ancestorID)&&isValidID(destinationID)),invariant(isAncestorIDOf(ancestorID,destinationID)),ancestorID===destinationID)return ancestorID;for(var start=ancestorID.length+SEPARATOR_LENGTH,i=start;i<destinationID.length&&!isBoundary(destinationID,i);i++);return destinationID.substr(0,i)}function getFirstCommonAncestorID(oneID,twoID){var minLength=Math.min(oneID.length,twoID.length);if(0===minLength)return"";for(var lastCommonMarkerIndex=0,i=0;minLength>=i;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);return invariant(isValidID(longestCommonID)),longestCommonID}function traverseParentPath(start,stop,cb,arg,skipFirst,skipLast){start=start||"",stop=stop||"",invariant(start!==stop);var traverseUp=isAncestorIDOf(stop,start);invariant(traverseUp||isAncestorIDOf(start,stop));for(var depth=0,traverse=traverseUp?getParentID:getNextDescendantID,id=start;;id=traverse(id,stop)){var ret;if(skipFirst&&id===start||skipLast&&id===stop||(ret=cb(id,traverseUp,arg)),ret===!1||id===stop)break;invariant(depth++<MAX_TREE_DEPTH)}}var ReactRootIndex=_dereq_("./ReactRootIndex"),invariant=_dereq_("./invariant"),SEPARATOR=".",SEPARATOR_LENGTH=SEPARATOR.length,MAX_TREE_DEPTH=100,ReactInstanceHandles={createReactRootID:function(){return getReactRootIDString(ReactRootIndex.createReactRootIndex())},createReactID:function(rootID,name){return rootID+name},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},traverseEnterLeave:function(leaveID,enterID,cb,upArg,downArg){var ancestorID=getFirstCommonAncestorID(leaveID,enterID);ancestorID!==leaveID&&traverseParentPath(leaveID,ancestorID,cb,upArg,!1,!0),ancestorID!==enterID&&traverseParentPath(ancestorID,enterID,cb,downArg,!0,!1)},traverseTwoPhase:function(targetID,cb,arg){targetID&&(traverseParentPath("",targetID,cb,arg,!0,!1),traverseParentPath(targetID,"",cb,arg,!1,!0))},traverseAncestors:function(targetID,cb,arg){traverseParentPath("",targetID,cb,arg,!0,!1)},_getFirstCommonAncestorID:getFirstCommonAncestorID,_getNextDescendantID:getNextDescendantID,isAncestorIDOf:isAncestorIDOf,SEPARATOR:SEPARATOR};module.exports=ReactInstanceHandles},{"./ReactRootIndex":57,"./invariant":70}],52:[function(_dereq_,module){"use strict";function proxyStaticMethods(target,source){if("function"==typeof source)for(var key in source)if(source.hasOwnProperty(key)){var value=source[key];if("function"==typeof value){var bound=value.bind(source);for(var k in value)value.hasOwnProperty(k)&&(bound[k]=value[k]);target[key]=bound}else target[key]=value}}var invariant=(_dereq_("./ReactCurrentOwner"),_dereq_("./invariant")),LEGACY_MARKER=(_dereq_("./monitorCodeUse"),_dereq_("./warning"),{}),NON_LEGACY_MARKER={},ReactLegacyElementFactory={};ReactLegacyElementFactory.wrapCreateFactory=function(createFactory){var legacyCreateFactory=function(type){return"function"!=typeof type?createFactory(type):type.isReactNonLegacyFactory?createFactory(type.type):type.isReactLegacyFactory?createFactory(type.type):type};return legacyCreateFactory},ReactLegacyElementFactory.wrapCreateElement=function(createElement){var legacyCreateElement=function(type){if("function"!=typeof type)return createElement.apply(this,arguments);var args;return type.isReactNonLegacyFactory?(args=Array.prototype.slice.call(arguments,0),args[0]=type.type,createElement.apply(this,args)):type.isReactLegacyFactory?(type._isMockFunction&&(type.type._mockedReactClassConstructor=type),args=Array.prototype.slice.call(arguments,0),args[0]=type.type,createElement.apply(this,args)):type.apply(null,Array.prototype.slice.call(arguments,1))};return legacyCreateElement},ReactLegacyElementFactory.wrapFactory=function(factory){invariant("function"==typeof factory);var legacyElementFactory=function(){return factory.apply(this,arguments)};return proxyStaticMethods(legacyElementFactory,factory.type),legacyElementFactory.isReactLegacyFactory=LEGACY_MARKER,legacyElementFactory.type=factory.type,legacyElementFactory},ReactLegacyElementFactory.markNonLegacyFactory=function(factory){return factory.isReactNonLegacyFactory=NON_LEGACY_MARKER,factory},ReactLegacyElementFactory.isValidFactory=function(factory){return"function"==typeof factory&&factory.isReactLegacyFactory===LEGACY_MARKER},ReactLegacyElementFactory.isValidClass=function(factory){return ReactLegacyElementFactory.isValidFactory(factory)},ReactLegacyElementFactory._isLegacyCallWarningEnabled=!0,module.exports=ReactLegacyElementFactory},{"./ReactCurrentOwner":47,"./invariant":70,"./monitorCodeUse":76,"./warning":77}],53:[function(_dereq_,module){"use strict";var adler32=_dereq_("./adler32"),ReactMarkupChecksum={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(markup){var checksum=adler32(markup);return markup.replace(">"," "+ReactMarkupChecksum.CHECKSUM_ATTR_NAME+'="'+checksum+'">')},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":62}],54:[function(_dereq_,module){"use strict";function createInstanceForTag(tag,props,parentType){var componentClass=tagToComponentClass[tag];return null==componentClass?(invariant(genericComponentClass),new genericComponentClass(tag,props)):parentType===tag?(invariant(genericComponentClass),new genericComponentClass(tag,props)):new componentClass.type(props)}var assign=_dereq_("./Object.assign"),invariant=_dereq_("./invariant"),genericComponentClass=null,tagToComponentClass={},ReactNativeComponentInjection={injectGenericComponentClass:function(componentClass){genericComponentClass=componentClass},injectComponentClasses:function(componentClasses){assign(tagToComponentClass,componentClasses)}},ReactNativeComponent={createInstanceForTag:createInstanceForTag,injection:ReactNativeComponentInjection};module.exports=ReactNativeComponent},{"./Object.assign":43,"./invariant":70}],55:[function(_dereq_,module){"use strict";function createTransferStrategy(mergeStrategy){return function(props,key,value){props[key]=props.hasOwnProperty(key)?mergeStrategy(props[key],value):value}}function transferInto(props,newProps){for(var thisKey in newProps)if(newProps.hasOwnProperty(thisKey)){var transferStrategy=TransferStrategies[thisKey];transferStrategy&&TransferStrategies.hasOwnProperty(thisKey)?transferStrategy(props,thisKey,newProps[thisKey]):props.hasOwnProperty(thisKey)||(props[thisKey]=newProps[thisKey])}return props}var assign=_dereq_("./Object.assign"),emptyFunction=_dereq_("./emptyFunction"),invariant=_dereq_("./invariant"),joinClasses=_dereq_("./joinClasses"),transferStrategyMerge=(_dereq_("./warning"),createTransferStrategy(function(a,b){return assign({},b,a)})),TransferStrategies={children:emptyFunction,className:createTransferStrategy(joinClasses),style:transferStrategyMerge},ReactPropTransferer={TransferStrategies:TransferStrategies,mergeProps:function(oldProps,newProps){return transferInto(assign({},oldProps),newProps)},Mixin:{transferPropsTo:function(element){return invariant(element._owner===this),transferInto(element.props,this.props),element}}};module.exports=ReactPropTransferer},{"./Object.assign":43,"./emptyFunction":66,"./invariant":70,"./joinClasses":72,"./warning":77}],56:[function(_dereq_,module){"use strict";function ReactPutListenerQueue(){this.listenersToPut=[]}var PooledClass=_dereq_("./PooledClass"),ReactBrowserEventEmitter=_dereq_("./ReactBrowserEventEmitter"),assign=_dereq_("./Object.assign");assign(ReactPutListenerQueue.prototype,{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];ReactBrowserEventEmitter.putListener(listenerToPut.rootNodeID,listenerToPut.propKey,listenerToPut.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),PooledClass.addPoolingTo(ReactPutListenerQueue),module.exports=ReactPutListenerQueue},{"./Object.assign":43,"./PooledClass":44,"./ReactBrowserEventEmitter":45}],57:[function(_dereq_,module){"use strict";var ReactRootIndexInjection={injectCreateReactRootIndex:function(_createReactRootIndex){ReactRootIndex.createReactRootIndex=_createReactRootIndex}},ReactRootIndex={createReactRootIndex:null,injection:ReactRootIndexInjection};module.exports=ReactRootIndex},{}],58:[function(_dereq_,module){"use strict";function ReactServerRenderingTransaction(renderToStaticMarkup){this.reinitializeTransaction(),this.renderToStaticMarkup=renderToStaticMarkup,this.reactMountReady=CallbackQueue.getPooled(null),this.putListenerQueue=ReactPutListenerQueue.getPooled()}var PooledClass=_dereq_("./PooledClass"),CallbackQueue=_dereq_("./CallbackQueue"),ReactPutListenerQueue=_dereq_("./ReactPutListenerQueue"),Transaction=_dereq_("./Transaction"),assign=_dereq_("./Object.assign"),emptyFunction=_dereq_("./emptyFunction"),ON_DOM_READY_QUEUEING={initialize:function(){this.reactMountReady.reset()},close:emptyFunction},PUT_LISTENER_QUEUEING={initialize:function(){this.putListenerQueue.reset()},close:emptyFunction},TRANSACTION_WRAPPERS=[PUT_LISTENER_QUEUEING,ON_DOM_READY_QUEUEING],Mixin={getTransactionWrappers:function(){return TRANSACTION_WRAPPERS},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){CallbackQueue.release(this.reactMountReady),this.reactMountReady=null,ReactPutListenerQueue.release(this.putListenerQueue),this.putListenerQueue=null}};assign(ReactServerRenderingTransaction.prototype,Transaction.Mixin,Mixin),PooledClass.addPoolingTo(ReactServerRenderingTransaction),module.exports=ReactServerRenderingTransaction},{"./CallbackQueue":37,"./Object.assign":43,"./PooledClass":44,"./ReactPutListenerQueue":56,"./Transaction":59,"./emptyFunction":66}],59:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),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(method,scope,a,b,c,d,e,f){invariant(!this.isInTransaction());var errorThrown,ret;try{this._isInTransaction=!0,errorThrown=!0,this.initializeAll(0),ret=method.call(scope,a,b,c,d,e,f),errorThrown=!1}finally{try{if(errorThrown)try{this.closeAll(0)}catch(err){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return ret},initializeAll:function(startIndex){for(var transactionWrappers=this.transactionWrappers,i=startIndex;i<transactionWrappers.length;i++){var wrapper=transactionWrappers[i];try{this.wrapperInitData[i]=Transaction.OBSERVED_ERROR,this.wrapperInitData[i]=wrapper.initialize?wrapper.initialize.call(this):null}finally{if(this.wrapperInitData[i]===Transaction.OBSERVED_ERROR)try{this.initializeAll(i+1)}catch(err){}}}},closeAll:function(startIndex){invariant(this.isInTransaction());for(var transactionWrappers=this.transactionWrappers,i=startIndex;i<transactionWrappers.length;i++){var errorThrown,wrapper=transactionWrappers[i],initData=this.wrapperInitData[i];try{errorThrown=!0,initData!==Transaction.OBSERVED_ERROR&&wrapper.close&&wrapper.close.call(this,initData),errorThrown=!1}finally{if(errorThrown)try{this.closeAll(i+1)}catch(e){}}}this.wrapperInitData.length=0}},Transaction={Mixin:Mixin,OBSERVED_ERROR:{}};module.exports=Transaction},{"./invariant":70}],60:[function(_dereq_,module){"use strict";var getUnboundedScrollPosition=_dereq_("./getUnboundedScrollPosition"),ViewportMetrics={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var scrollPosition=getUnboundedScrollPosition(window);ViewportMetrics.currentScrollLeft=scrollPosition.x,ViewportMetrics.currentScrollTop=scrollPosition.y}};module.exports=ViewportMetrics},{"./getUnboundedScrollPosition":68}],61:[function(_dereq_,module){"use strict";function accumulateInto(current,next){if(invariant(null!=next),null==current)return next;var currentIsArray=Array.isArray(current),nextIsArray=Array.isArray(next);return currentIsArray&&nextIsArray?(current.push.apply(current,next),current):currentIsArray?(current.push(next),current):nextIsArray?[current].concat(next):[current,next]}var invariant=_dereq_("./invariant");module.exports=accumulateInto},{"./invariant":70}],62:[function(_dereq_,module){"use strict";function adler32(data){for(var a=1,b=0,i=0;i<data.length;i++)a=(a+data.charCodeAt(i))%MOD,b=(b+a)%MOD;return a|b<<16}var MOD=65521;module.exports=adler32},{}],63:[function(_dereq_,module){"use strict";function cloneWithProps(child,props){var newProps=ReactPropTransferer.mergeProps(props,child.props);return!newProps.hasOwnProperty(CHILDREN_PROP)&&child.props.hasOwnProperty(CHILDREN_PROP)&&(newProps.children=child.props.children),ReactElement.createElement(child.type,newProps)}var ReactElement=_dereq_("./ReactElement"),ReactPropTransferer=_dereq_("./ReactPropTransferer"),keyOf=_dereq_("./keyOf"),CHILDREN_PROP=(_dereq_("./warning"),keyOf({children:null}));module.exports=cloneWithProps},{"./ReactElement":48,"./ReactPropTransferer":55,"./keyOf":74,"./warning":77}],64:[function(_dereq_,module){function copyProperties(obj,a,b,c,d,e,f){obj=obj||{};for(var v,args=[a,b,c,d,e],ii=0;args[ii];){v=args[ii++];for(var k in v)obj[k]=v[k];v.hasOwnProperty&&v.hasOwnProperty("toString")&&"undefined"!=typeof v.toString&&obj.toString!==v.toString&&(obj.toString=v.toString)}return obj}module.exports=copyProperties,console.warn("react/lib/copyProperties has been deprecated and will be removed in the next version of React. All uses can be replaced with Object.assign(obj, a, b, ...) or _.extend(obj, a, b, ...).")},{}],65:[function(_dereq_,module){function cx(classNames){return"object"==typeof classNames?Object.keys(classNames).filter(function(className){return classNames[className]}).join(" "):Array.prototype.join.call(arguments," ")}module.exports=cx},{}],66:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}emptyFunction.thatReturns=makeEmptyFunction,emptyFunction.thatReturnsFalse=makeEmptyFunction(!1),emptyFunction.thatReturnsTrue=makeEmptyFunction(!0),emptyFunction.thatReturnsNull=makeEmptyFunction(null),emptyFunction.thatReturnsThis=function(){return this},emptyFunction.thatReturnsArgument=function(arg){return arg},module.exports=emptyFunction},{}],67:[function(_dereq_,module){"use strict";var forEachAccumulated=function(arr,cb,scope){Array.isArray(arr)?arr.forEach(cb,scope):arr&&cb.call(scope,arr)};module.exports=forEachAccumulated},{}],68:[function(_dereq_,module){"use strict";function getUnboundedScrollPosition(scrollable){return scrollable===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:scrollable.scrollLeft,y:scrollable.scrollTop}}module.exports=getUnboundedScrollPosition},{}],69:[function(_dereq_,module){"use strict";function instantiateReactComponent(element,parentCompositeType){var instance;return instance="string"==typeof element.type?ReactNativeComponent.createInstanceForTag(element.type,element.props,parentCompositeType):new element.type(element.props),instance.construct(element),instance}{var ReactNativeComponent=(_dereq_("./warning"),_dereq_("./ReactElement"),_dereq_("./ReactLegacyElement"),_dereq_("./ReactNativeComponent"));_dereq_("./ReactEmptyComponent")}module.exports=instantiateReactComponent},{"./ReactElement":48,"./ReactEmptyComponent":49,"./ReactLegacyElement":52,"./ReactNativeComponent":54,"./warning":77}],70:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)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],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],71:[function(_dereq_,module){"use strict";function isEventSupported(eventNameSuffix,capture){if(!ExecutionEnvironment.canUseDOM||capture&&!("addEventListener"in document))return!1;var eventName="on"+eventNameSuffix,isSupported=eventName in document;if(!isSupported){var element=document.createElement("div");element.setAttribute(eventName,"return;"),isSupported="function"==typeof element[eventName]}return!isSupported&&useHasFeature&&"wheel"===eventNameSuffix&&(isSupported=document.implementation.hasFeature("Events.wheel","3.0")),isSupported}var useHasFeature,ExecutionEnvironment=_dereq_("./ExecutionEnvironment");ExecutionEnvironment.canUseDOM&&(useHasFeature=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),module.exports=isEventSupported},{"./ExecutionEnvironment":42}],72:[function(_dereq_,module){"use strict";function joinClasses(className){className||(className="");var nextClass,argLength=arguments.length;if(argLength>1)for(var ii=1;argLength>ii;ii++)nextClass=arguments[ii],nextClass&&(className=(className?className+" ":"")+nextClass);return className}module.exports=joinClasses},{}],73:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=function(obj){var key,ret={};invariant(obj instanceof Object&&!Array.isArray(obj));for(key in obj)obj.hasOwnProperty(key)&&(ret[key]=key);return ret};module.exports=keyMirror},{"./invariant":70}],74:[function(_dereq_,module){var keyOf=function(oneKeyObj){var key;for(key in oneKeyObj)if(oneKeyObj.hasOwnProperty(key))return key;return null};module.exports=keyOf},{}],75:[function(_dereq_,module){"use strict";var assign=_dereq_("./Object.assign"),merge=function(one,two){return assign({},one,two)};module.exports=merge,console.warn("react/lib/merge has been deprecated and will be removed in the next version of React. All uses can be replaced with Object.assign({}, a, b) or _.extend({}, a, b).")},{"./Object.assign":43}],76:[function(_dereq_,module){"use strict";function monitorCodeUse(eventName){invariant(eventName&&!/[^a-z0-9_]/.test(eventName))}var invariant=_dereq_("./invariant");module.exports=monitorCodeUse},{"./invariant":70}],77:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":66}],78:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":80,"./async":81,"./makePromise":82}],79:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],80:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":79}],81:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],82:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state(); if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to)},Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[10])(10)});
ajax/libs/react/0.10.0-rc1/react.min.js
tholu/cdnjs
/** * React v0.10.0-rc1 * * 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. */ !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.React=e()}}(function(){return function e(t,n,o){function r(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return r(n?n:e)},c,c.exports,e,t,n,o)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<o.length;a++)r(o[a]);return r}({1:[function(e,t){"use strict";var n=e("./focusNode"),o={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=o},{"./focusNode":98}],2:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={columnCount:!0,fillOpacity:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},r=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){r.forEach(function(t){o[n(t,e)]=o[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!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}},a={isUnitlessNumber:o,shorthandPropertyExpansions:i};t.exports=a},{}],3:[function(e,t){"use strict";var n=e("./CSSProperty"),o=e("./dangerousStyleValue"),r=e("./escapeTextForBrowser"),i=e("./hyphenate"),a=e("./memoizeStringOnly"),s=a(function(e){return r(i(e))}),u={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=s(n)+":",t+=o(n,r)+";")}return t||null},setValueForStyles:function(e,t){var r=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=o(i,t[i]);if(a)r[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var u in s)r[u]="";else r[i]=""}}}};t.exports=u},{"./CSSProperty":2,"./dangerousStyleValue":93,"./escapeTextForBrowser":96,"./hyphenate":108,"./memoizeStringOnly":118}],4:[function(e,t){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function o(e){var t=M.getPooled(O.change,T,e);y.accumulateTwoPhaseDispatches(t),R.batchedUpdates(r,t)}function r(e){C.enqueueEvents(e),C.processEventQueue()}function i(e,t){I=e,T=t,I.attachEvent("onchange",o)}function a(){I&&(I.detachEvent("onchange",o),I=null,T=null)}function s(e,t,n){return e===P.topChange?n:void 0}function u(e,t,n){e===P.topFocus?(a(),i(t,n)):e===P.topBlur&&a()}function c(e,t){I=e,T=t,N=e.value,S=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(I,"value",A),I.attachEvent("onpropertychange",p)}function l(){I&&(delete I.value,I.detachEvent("onpropertychange",p),I=null,T=null,N=null,S=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==N&&(N=t,o(e))}}function d(e,t,n){return e===P.topInput?n:void 0}function f(e,t,n){e===P.topFocus?(l(),c(t,n)):e===P.topBlur&&l()}function h(e){return e!==P.topSelectionChange&&e!==P.topKeyUp&&e!==P.topKeyDown||!I||I.value===N?void 0:(N=I.value,T)}function m(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function v(e,t,n){return e===P.topClick?n:void 0}var g=e("./EventConstants"),C=e("./EventPluginHub"),y=e("./EventPropagators"),E=e("./ExecutionEnvironment"),R=e("./ReactUpdates"),M=e("./SyntheticEvent"),D=e("./isEventSupported"),x=e("./isTextInputElement"),b=e("./keyOf"),P=g.topLevelTypes,O={change:{phasedRegistrationNames:{bubbled:b({onChange:null}),captured:b({onChangeCapture:null})},dependencies:[P.topBlur,P.topChange,P.topClick,P.topFocus,P.topInput,P.topKeyDown,P.topKeyUp,P.topSelectionChange]}},I=null,T=null,N=null,S=null,_=!1;E.canUseDOM&&(_=D("change")&&(!("documentMode"in document)||document.documentMode>8));var w=!1;E.canUseDOM&&(w=D("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return S.get.call(this)},set:function(e){N=""+e,S.set.call(this,e)}},k={eventTypes:O,extractEvents:function(e,t,o,r){var i,a;if(n(t)?_?i=s:a=u:x(t)?w?i=d:(i=h,a=f):m(t)&&(i=v),i){var c=i(e,t,o);if(c){var l=M.getPooled(O.change,c,r);return y.accumulateTwoPhaseDispatches(l),l}}a&&a(e,t,o)}};t.exports=k},{"./EventConstants":14,"./EventPluginHub":16,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactUpdates":69,"./SyntheticEvent":76,"./isEventSupported":111,"./isTextInputElement":113,"./keyOf":117}],5:[function(e,t){"use strict";var n=0,o={createReactRootIndex:function(){return n++}};t.exports=o},{}],6:[function(e,t){"use strict";function n(e){switch(e){case g.topCompositionStart:return y.compositionStart;case g.topCompositionEnd:return y.compositionEnd;case g.topCompositionUpdate:return y.compositionUpdate}}function o(e,t){return e===g.topKeyDown&&t.keyCode===h}function r(e,t){switch(e){case g.topKeyUp:return-1!==f.indexOf(t.keyCode);case g.topKeyDown:return t.keyCode!==h;case g.topKeyPress:case g.topMouseDown:case g.topBlur:return!0;default:return!1}}function i(e){this.root=e,this.startSelection=c.getSelection(e),this.startValue=this.getText()}var a=e("./EventConstants"),s=e("./EventPropagators"),u=e("./ExecutionEnvironment"),c=e("./ReactInputSelection"),l=e("./SyntheticCompositionEvent"),p=e("./getTextContentAccessor"),d=e("./keyOf"),f=[9,13,27,32],h=229,m=u.canUseDOM&&"CompositionEvent"in window,v=!m||"documentMode"in document&&document.documentMode>8,g=a.topLevelTypes,C=null,y={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[g.topBlur,g.topCompositionEnd,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[g.topBlur,g.topCompositionStart,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[g.topBlur,g.topCompositionUpdate,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]}};i.prototype.getText=function(){return this.root.value||this.root[p()]},i.prototype.getData=function(){var e=this.getText(),t=this.startSelection.start,n=this.startValue.length-this.startSelection.end;return e.substr(t,e.length-n-t)};var E={eventTypes:y,extractEvents:function(e,t,a,u){var c,p;if(m?c=n(e):C?r(e,u)&&(c=y.compositionEnd):o(e,u)&&(c=y.compositionStart),v&&(C||c!==y.compositionStart?c===y.compositionEnd&&C&&(p=C.getData(),C=null):C=new i(t)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};t.exports=E},{"./EventConstants":14,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactInputSelection":50,"./SyntheticCompositionEvent":74,"./getTextContentAccessor":106,"./keyOf":117}],7:[function(e,t){"use strict";function n(e,t,n){var o=e.childNodes;o[n]!==t&&(t.parentNode===e&&e.removeChild(t),n>=o.length?e.appendChild(t):e.insertBefore(t,o[n]))}var o,r=e("./Danger"),i=e("./ReactMultiChildUpdateTypes"),a=e("./getTextContentAccessor"),s=a();o="textContent"===s?function(e,t){e.textContent=t}:function(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);if(t){var n=e.ownerDocument||document;e.appendChild(n.createTextNode(t))}};var u={dangerouslyReplaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,updateTextContent:o,processUpdates:function(e,t){for(var a,s=null,u=null,c=0;a=e[c];c++)if(a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var l=a.fromIndex,p=a.parentNode.childNodes[l],d=a.parentID;s=s||{},s[d]=s[d]||[],s[d][l]=p,u=u||[],u.push(p)}var f=r.dangerouslyRenderMarkup(t);if(u)for(var h=0;h<u.length;h++)u[h].parentNode.removeChild(u[h]);for(var m=0;a=e[m];m++)switch(a.type){case i.INSERT_MARKUP:n(a.parentNode,f[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:n(a.parentNode,s[a.parentID][a.fromIndex],a.toIndex);break;case i.TEXT_CONTENT:o(a.parentNode,a.textContent);break;case i.REMOVE_NODE:}}};t.exports=u},{"./Danger":10,"./ReactMultiChildUpdateTypes":56,"./getTextContentAccessor":106}],8:[function(e,t){"use strict";var n=e("./invariant"),o={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:16,injectDOMPropertyConfig:function(e){var t=e.Properties||{},r=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},s=e.DOMMutationMethods||{};e.isCustomAttribute&&i._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in t){n(!i.isStandardName[u]),i.isStandardName[u]=!0;var c=u.toLowerCase();i.getPossibleStandardName[c]=u;var l=r[u];l&&(i.getPossibleStandardName[l]=u),i.getAttributeName[u]=l||c,i.getPropertyName[u]=a[u]||u;var p=s[u];p&&(i.getMutationMethod[u]=p);var d=t[u];i.mustUseAttribute[u]=d&o.MUST_USE_ATTRIBUTE,i.mustUseProperty[u]=d&o.MUST_USE_PROPERTY,i.hasSideEffects[u]=d&o.HAS_SIDE_EFFECTS,i.hasBooleanValue[u]=d&o.HAS_BOOLEAN_VALUE,i.hasPositiveNumericValue[u]=d&o.HAS_POSITIVE_NUMERIC_VALUE,n(!i.mustUseAttribute[u]||!i.mustUseProperty[u]),n(i.mustUseProperty[u]||!i.hasSideEffects[u]),n(!i.hasBooleanValue[u]||!i.hasPositiveNumericValue[u])}}},r={},i={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasPositiveNumericValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<i._isCustomAttributeFunctions.length;t++){var n=i._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,o=r[e];return o||(r[e]=o={}),t in o||(n=document.createElement(e),o[t]=n[t]),o[t]},injection:o};t.exports=i},{"./invariant":110}],9:[function(e,t){"use strict";function n(e,t){return null==t||o.hasBooleanValue[e]&&!t||o.hasPositiveNumericValue[e]&&(isNaN(t)||1>t)}var o=e("./DOMProperty"),r=e("./escapeTextForBrowser"),i=e("./memoizeStringOnly"),a=(e("./warning"),i(function(e){return r(e)+'="'})),s={createMarkupForID:function(e){return a(o.ID_ATTRIBUTE_NAME)+r(e)+'"'},createMarkupForProperty:function(e,t){if(o.isStandardName[e]){if(n(e,t))return"";var i=o.getAttributeName[e];return o.hasBooleanValue[e]?r(i):a(i)+r(t)+'"'}return o.isCustomAttribute(e)?null==t?"":a(e)+r(t)+'"':null},setValueForProperty:function(e,t,r){if(o.isStandardName[t]){var i=o.getMutationMethod[t];if(i)i(e,r);else if(n(t,r))this.deleteValueForProperty(e,t);else if(o.mustUseAttribute[t])e.setAttribute(o.getAttributeName[t],""+r);else{var a=o.getPropertyName[t];o.hasSideEffects[t]&&e[a]===r||(e[a]=r)}}else o.isCustomAttribute(t)&&(null==r?e.removeAttribute(o.getAttributeName[t]):e.setAttribute(t,""+r))},deleteValueForProperty:function(e,t){if(o.isStandardName[t]){var n=o.getMutationMethod[t];if(n)n(e,void 0);else if(o.mustUseAttribute[t])e.removeAttribute(o.getAttributeName[t]);else{var r=o.getPropertyName[t],i=o.getDefaultValueForProperty(e.nodeName,r);o.hasSideEffects[t]&&e[r]===i||(e[r]=i)}}else o.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=s},{"./DOMProperty":8,"./escapeTextForBrowser":96,"./memoizeStringOnly":118,"./warning":131}],10:[function(e,t){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var o=e("./ExecutionEnvironment"),r=e("./createNodesFromMarkup"),i=e("./emptyFunction"),a=e("./getMarkupWrap"),s=e("./invariant"),u=/^(<[^ \/>]+)/,c="data-danger-index",l={dangerouslyRenderMarkup:function(e){s(o.canUseDOM);for(var t,l={},p=0;p<e.length;p++)s(e[p]),t=n(e[p]),t=a(t)?t:"*",l[t]=l[t]||[],l[t][p]=e[p];var d=[],f=0;for(t in l)if(l.hasOwnProperty(t)){var h=l[t];for(var m in h)if(h.hasOwnProperty(m)){var v=h[m];h[m]=v.replace(u,"$1 "+c+'="'+m+'" ')}var g=r(h.join(""),i);for(p=0;p<g.length;++p){var C=g[p];C.hasAttribute&&C.hasAttribute(c)&&(m=+C.getAttribute(c),C.removeAttribute(c),s(!d.hasOwnProperty(m)),d[m]=C,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(o.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=r(t,i)[0];e.parentNode.replaceChild(n,e)}};t.exports=l},{"./ExecutionEnvironment":20,"./createNodesFromMarkup":91,"./emptyFunction":94,"./getMarkupWrap":103,"./invariant":110}],11:[function(e,t){"use strict";var n=e("./DOMProperty"),o=n.injection.MUST_USE_ATTRIBUTE,r=n.injection.MUST_USE_PROPERTY,i=n.injection.HAS_BOOLEAN_VALUE,a=n.injection.HAS_SIDE_EFFECTS,s=n.injection.HAS_POSITIVE_NUMERIC_VALUE,u={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,accessKey:null,action:null,allowFullScreen:o|i,allowTransparency:o,alt:null,async:i,autoComplete:null,autoPlay:i,cellPadding:null,cellSpacing:null,charSet:o,checked:r|i,className:r,cols:o|s,colSpan:null,content:null,contentEditable:null,contextMenu:o,controls:r|i,crossOrigin:null,data:null,dateTime:o,defer:i,dir:null,disabled:o|i,download:null,draggable:null,encType:null,form:o,formNoValidate:i,frameBorder:o,height:o,hidden:o|i,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:r,label:null,lang:null,list:null,loop:r|i,max:null,maxLength:o,mediaGroup:null,method:null,min:null,multiple:r|i,muted:r|i,name:null,noValidate:i,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:r|i,rel:null,required:i,role:o,rows:o|s,rowSpan:null,sandbox:null,scope:null,scrollLeft:r,scrollTop:r,seamless:o|i,selected:r|i,size:o|s,span:s,spellCheck:null,src:null,srcDoc:r,srcSet:null,step:null,style:null,tabIndex:null,target:null,title:null,type:null,value:r|a,width:o,wmode:o,autoCapitalize:null,autoCorrect:null,property:null,cx:o,cy:o,d:o,fill:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,offset:o,points:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeLinecap:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,y1:o,y2:o,y:o},DOMAttributeNames:{className:"class",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",htmlFor:"for",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeLinecap:"stroke-linecap",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"enctype",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=u},{"./DOMProperty":8}],12:[function(e,t){"use strict";var n=e("./keyOf"),o=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({CompositionEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=o},{"./keyOf":117}],13:[function(e,t){"use strict";var n=e("./EventConstants"),o=e("./EventPropagators"),r=e("./SyntheticMouseEvent"),i=e("./ReactMount"),a=e("./keyOf"),s=n.topLevelTypes,u=i.getFirstReactDOM,c={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l=[null,null],p={eventTypes:c,extractEvents:function(e,t,n,a){if(e===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var p;if(t.window===t)p=t;else{var d=t.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=u(a.relatedTarget||a.toElement)||p):(f=p,h=t),f===h)return null;var m=f?i.getID(f):"",v=h?i.getID(h):"",g=r.getPooled(c.mouseLeave,m,a);g.type="mouseleave",g.target=f,g.relatedTarget=h;var C=r.getPooled(c.mouseEnter,v,a);return C.type="mouseenter",C.target=h,C.relatedTarget=f,o.accumulateEnterLeaveDispatches(g,C,m,v),l[0]=g,l[1]=C,l}};t.exports=p},{"./EventConstants":14,"./EventPropagators":19,"./ReactMount":53,"./SyntheticMouseEvent":79,"./keyOf":117}],14:[function(e,t){"use strict";var n=e("./keyMirror"),o=n({bubbled:null,captured:null}),r=n({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}),i={topLevelTypes:r,PropagationPhases:o};t.exports=i},{"./keyMirror":116}],15:[function(e,t){var n=e("./emptyFunction"),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent(t,n)}}):void 0},capture:function(e,t,o){return e.addEventListener?(e.addEventListener(t,o,!0),{remove:function(){e.removeEventListener(t,o,!0)}}):{remove:n}}};t.exports=o},{"./emptyFunction":94}],16:[function(e,t){"use strict";var n=e("./EventPluginRegistry"),o=e("./EventPluginUtils"),r=e("./ExecutionEnvironment"),i=e("./accumulate"),a=e("./forEachAccumulated"),s=e("./invariant"),u=(e("./isEventSupported"),e("./monitorCodeUse"),{}),c=null,l=function(e){if(e){var t=o.executeDispatch,r=n.getPluginModuleForEvent(e);r&&r.executeDispatch&&(t=r.executeDispatch),o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},p=null,d={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){p=e},getInstanceHandle:function(){return p},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(e,t,n){s(r.canUseDOM),s(!n||"function"==typeof n);var o=u[t]||(u[t]={});o[e]=n},getListener:function(e,t){var n=u[t];return n&&n[e]},deleteListener:function(e,t){var n=u[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in u)delete u[t][e]},extractEvents:function(e,t,o,r){for(var a,s=n.plugins,u=0,c=s.length;c>u;u++){var l=s[u];if(l){var p=l.extractEvents(e,t,o,r);p&&(a=i(a,p))}}return a},enqueueEvents:function(e){e&&(c=i(c,e))},processEventQueue:function(){var e=c;c=null,a(e,l),s(!c)},__purge:function(){u={}},__getListenerBank:function(){return u}};t.exports=d},{"./EventPluginRegistry":17,"./EventPluginUtils":18,"./ExecutionEnvironment":20,"./accumulate":85,"./forEachAccumulated":99,"./invariant":110,"./isEventSupported":111,"./monitorCodeUse":123}],17:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var r=t.eventTypes;for(var c in r)i(o(r[c],t,c))}}}function o(e,t,n){i(!u.eventNameDispatchConfigs[n]),u.eventNameDispatchConfigs[n]=e;var o=e.phasedRegistrationNames;if(o){for(var a in o)if(o.hasOwnProperty(a)){var s=o[a];r(s,t,n)}return!0}return e.registrationName?(r(e.registrationName,t,n),!0):!1}function r(e,t,n){i(!u.registrationNameModules[e]),u.registrationNameModules[e]=t,u.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e("./invariant"),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var o in e)if(e.hasOwnProperty(o)){var r=e[o];s[o]!==r&&(i(!s[o]),s[o]=r,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var o=u.registrationNameModules[t.phasedRegistrationNames[n]];if(o)return o}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var o=u.registrationNameModules;for(var r in o)o.hasOwnProperty(r)&&delete o[r]}};t.exports=u},{"./invariant":110}],18:[function(e,t){"use strict";function n(e){return e===h.topMouseUp||e===h.topTouchEnd||e===h.topTouchCancel}function o(e){return e===h.topMouseMove||e===h.topTouchMove}function r(e){return e===h.topMouseDown||e===h.topTouchStart}function i(e,t){var n=e._dispatchListeners,o=e._dispatchIDs;if(Array.isArray(n))for(var r=0;r<n.length&&!e.isPropagationStopped();r++)t(e,n[r],o[r]);else n&&t(e,n,o)}function a(e,t,n){e.currentTarget=f.Mount.getNode(n);var o=t(e,n);return e.currentTarget=null,o}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var o=0;o<t.length&&!e.isPropagationStopped();o++)if(t[o](e,n[o]))return n[o]}else if(t&&t(e,n))return n;return null}function c(e){var t=e._dispatchListeners,n=e._dispatchIDs;d(!Array.isArray(t));var o=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,o}function l(e){return!!e._dispatchListeners}var p=e("./EventConstants"),d=e("./invariant"),f={Mount:null,injectMount:function(e){f.Mount=e}},h=p.topLevelTypes,m={isEndish:n,isMoveish:o,isStartish:r,executeDirectDispatch:c,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:u,hasDispatches:l,injection:f,useTouchEvents:!1};t.exports=m},{"./EventConstants":14,"./invariant":110}],19:[function(e,t){"use strict";function n(e,t,n){var o=t.dispatchConfig.phasedRegistrationNames[n];return m(e,o)}function o(e,t,o){var r=t?h.bubbled:h.captured,i=n(e,o,r);i&&(o._dispatchListeners=d(o._dispatchListeners,i),o._dispatchIDs=d(o._dispatchIDs,e))}function r(e){e&&e.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var o=n.dispatchConfig.registrationName,r=m(e,o);r&&(n._dispatchListeners=d(n._dispatchListeners,r),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){f(e,r)}function u(e,t,n,o){p.injection.getInstanceHandle().traverseEnterLeave(n,o,i,e,t)}function c(e){f(e,a)}var l=e("./EventConstants"),p=e("./EventPluginHub"),d=e("./accumulate"),f=e("./forEachAccumulated"),h=l.PropagationPhases,m=p.getListener,v={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};t.exports=v},{"./EventConstants":14,"./EventPluginHub":16,"./accumulate":85,"./forEachAccumulated":99}],20:[function(e,t){"use strict";var n="undefined"!=typeof window,o={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&(window.addEventListener||window.attachEvent),isInWorker:!n};t.exports=o},{}],21:[function(e,t){"use strict";function n(e){u(null==e.props.checkedLink||null==e.props.valueLink)}function o(e){n(e),u(null==e.props.value&&null==e.props.onChange)}function r(e){n(e),u(null==e.props.checked&&null==e.props.onChange)}function i(e){this.props.valueLink.requestChange(e.target.value)}function a(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e("./ReactPropTypes"),u=e("./invariant"),c=(e("./warning"),{Mixin:{propTypes:{value:function(){},checked:function(){},onChange:s.func}},getValue:function(e){return e.props.valueLink?(o(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(r(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(o(e),i):e.props.checkedLink?(r(e),a):e.props.onChange}});t.exports=c},{"./ReactPropTypes":62,"./invariant":110,"./warning":131}],22:[function(e,t){"use strict";var n=e("./EventConstants"),o=e("./emptyFunction"),r=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===r.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=o)}}};t.exports=i},{"./EventConstants":14,"./emptyFunction":94}],23:[function(e,t){"use strict";var n=e("./invariant"),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},r=function(e,t){var n=this;if(n.instancePool.length){var o=n.instancePool.pop();return n.call(o,e,t),o}return new n(e,t)},i=function(e,t,n){var o=this;if(o.instancePool.length){var r=o.instancePool.pop();return o.call(r,e,t,n),r}return new o(e,t,n)},a=function(e,t,n,o,r){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,o,r),a}return new i(e,t,n,o,r)},s=function(e){var t=this;n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},u=10,c=o,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:l,oneArgumentPooler:o,twoArgumentPooler:r,threeArgumentPooler:i,fiveArgumentPooler:a};t.exports=p},{"./invariant":110}],24:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),o=e("./EventPluginUtils"),r=e("./ReactChildren"),i=e("./ReactComponent"),a=e("./ReactCompositeComponent"),s=e("./ReactContext"),u=e("./ReactCurrentOwner"),c=e("./ReactDOM"),l=e("./ReactDOMComponent"),p=e("./ReactDefaultInjection"),d=e("./ReactInstanceHandles"),f=e("./ReactMount"),h=e("./ReactMultiChild"),m=e("./ReactPerf"),v=e("./ReactPropTypes"),g=e("./ReactServerRendering"),C=e("./ReactTextComponent"),y=e("./onlyChild");p.inject();var E={Children:{map:r.map,forEach:r.forEach,only:y},DOM:c,PropTypes:v,initializeTouchEvents:function(e){o.useTouchEvents=e},createClass:a.createClass,constructAndRenderComponent:f.constructAndRenderComponent,constructAndRenderComponentByID:f.constructAndRenderComponentByID,renderComponent:m.measure("React","renderComponent",f.renderComponent),renderComponentToString:g.renderComponentToString,renderComponentToStaticMarkup:g.renderComponentToStaticMarkup,unmountComponentAtNode:f.unmountComponentAtNode,isValidClass:a.isValidClass,isValidComponent:i.isValidComponent,withContext:s.withContext,__internals:{Component:i,CurrentOwner:u,DOMComponent:l,DOMPropertyOperations:n,InstanceHandles:d,Mount:f,MultiChild:h,TextComponent:C}};E.version="0.10.0-rc1",t.exports=E},{"./DOMPropertyOperations":9,"./EventPluginUtils":18,"./ReactChildren":26,"./ReactComponent":27,"./ReactCompositeComponent":29,"./ReactContext":30,"./ReactCurrentOwner":31,"./ReactDOM":32,"./ReactDOMComponent":34,"./ReactDefaultInjection":44,"./ReactInstanceHandles":51,"./ReactMount":53,"./ReactMultiChild":55,"./ReactPerf":58,"./ReactPropTypes":62,"./ReactServerRendering":66,"./ReactTextComponent":68,"./onlyChild":126}],25:[function(e,t){"use strict";var n=e("./ReactMount"),o=e("./invariant"),r={getDOMNode:function(){return o(this.isMounted()),n.getNode(this._rootNodeID)}};t.exports=r},{"./ReactMount":53,"./invariant":110}],26:[function(e,t){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function o(e,t,n,o){var r=e;r.forEachFunction.call(r.forEachContext,t,o)}function r(e,t,r){if(null==e)return e;var i=n.getPooled(t,r);l(e,o,i),n.release(i)}function i(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function a(e,t,n,o){var r=e,i=r.mapResult,a=r.mapFunction.call(r.mapContext,t,o);c(!i.hasOwnProperty(n)),i[n]=a}function s(e,t,n){if(null==e)return e;var o={},r=i.getPooled(o,t,n);return l(e,a,r),i.release(r),o}var u=e("./PooledClass"),c=e("./invariant"),l=e("./traverseAllChildren"),p=u.twoArgumentPooler,d=u.threeArgumentPooler;u.addPoolingTo(n,p),u.addPoolingTo(i,d);var f={forEach:r,map:s};t.exports=f},{"./PooledClass":23,"./invariant":110,"./traverseAllChildren":130}],27:[function(e,t){"use strict";var n=e("./ReactCurrentOwner"),o=e("./ReactOwner"),r=e("./ReactUpdates"),i=e("./invariant"),a=e("./keyMirror"),s=e("./merge"),u=(e("./monitorCodeUse"),a({MOUNTED:null,UNMOUNTED:null})),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(e){i(!c),p=e.mountImageIntoNode,l=e.unmountIDFromEnvironment,d.BackendIDOperations=e.BackendIDOperations,d.ReactReconcileTransaction=e.ReactReconcileTransaction,c=!0}},isValidComponent:function(e){if(!e||!e.type||!e.type.prototype)return!1;var t=e.type.prototype;return"function"==typeof t.mountComponentIntoNode&&"function"==typeof t.receiveComponent},LifeCycle:u,BackendIDOperations:null,ReactReconcileTransaction:null,Mixin:{isMounted:function(){return this._lifeCycleState===u.MOUNTED},setProps:function(e,t){this.replaceProps(s(this._pendingProps||this.props,e),t)},replaceProps:function(e,t){i(this.isMounted()),i(0===this._mountDepth),this._pendingProps=e,r.enqueueUpdate(this,t)},construct:function(e,t){this.props=e||{},this._owner=n.current,this._lifeCycleState=u.UNMOUNTED,this._pendingProps=null,this._pendingCallbacks=null,this._pendingOwner=this._owner;var o=arguments.length-1;if(1===o)this.props.children=t;else if(o>1){for(var r=Array(o),i=0;o>i;i++)r[i]=arguments[i+1];this.props.children=r}},mountComponent:function(e,t,n){i(!this.isMounted());var r=this.props;null!=r.ref&&o.addComponentAsRefTo(this,r.ref,this._owner),this._rootNodeID=e,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){i(this.isMounted());var e=this.props;null!=e.ref&&o.removeComponentAsRefFrom(this,e.ref,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(e,t){i(this.isMounted()),this._pendingOwner=e._owner,this._pendingProps=e.props,this._performUpdateIfNecessary(t)},performUpdateIfNecessary:function(){var e=d.ReactReconcileTransaction.getPooled();e.perform(this._performUpdateIfNecessary,this,e),d.ReactReconcileTransaction.release(e)},_performUpdateIfNecessary:function(e){if(null!=this._pendingProps){var t=this.props,n=this._owner;this.props=this._pendingProps,this._owner=this._pendingOwner,this._pendingProps=null,this.updateComponent(e,t,n)}},updateComponent:function(e,t,n){var r=this.props;(this._owner!==n||r.ref!==t.ref)&&(null!=t.ref&&o.removeComponentAsRefFrom(this,t.ref,n),null!=r.ref&&o.addComponentAsRefTo(this,r.ref,this._owner))},mountComponentIntoNode:function(e,t,n){var o=d.ReactReconcileTransaction.getPooled();o.perform(this._mountComponentIntoNode,this,e,t,o,n),d.ReactReconcileTransaction.release(o)},_mountComponentIntoNode:function(e,t,n,o){var r=this.mountComponent(e,n,0);p(r,t,o)},isOwnedBy:function(e){return this._owner===e},getSiblingByRef:function(e){var t=this._owner;return t&&t.refs?t.refs[e]:null}}};t.exports=d},{"./ReactCurrentOwner":31,"./ReactOwner":57,"./ReactUpdates":69,"./invariant":110,"./keyMirror":116,"./merge":119,"./monitorCodeUse":123}],28:[function(e,t){"use strict";var n=e("./ReactDOMIDOperations"),o=e("./ReactMarkupChecksum"),r=e("./ReactMount"),i=e("./ReactPerf"),a=e("./ReactReconcileTransaction"),s=e("./getReactRootElementInContainer"),u=e("./invariant"),c=1,l=9,p={ReactReconcileTransaction:a,BackendIDOperations:n,unmountIDFromEnvironment:function(e){r.purgeID(e)},mountImageIntoNode:i.measure("ReactComponentBrowserEnvironment","mountImageIntoNode",function(e,t,n){if(u(t&&(t.nodeType===c||t.nodeType===l)),n){if(o.canReuseMarkup(e,s(t)))return;u(t.nodeType!==l)}u(t.nodeType!==l),t.innerHTML=e})};t.exports=p},{"./ReactDOMIDOperations":36,"./ReactMarkupChecksum":52,"./ReactMount":53,"./ReactPerf":58,"./ReactReconcileTransaction":64,"./getReactRootElementInContainer":105,"./invariant":110}],29:[function(e,t){"use strict"; function n(e,t){for(var n in t)t.hasOwnProperty(n)&&R("function"==typeof t[n])}function o(e,t){var n=T[t];_.hasOwnProperty(t)&&R(n===O.OVERRIDE_BASE),e.hasOwnProperty(t)&&R(n===O.DEFINE_MANY||n===O.DEFINE_MANY_MERGED)}function r(e){var t=e._compositeLifeCycleState;R(e.isMounted()||t===S.MOUNTING),R(t!==S.RECEIVING_STATE),R(t!==S.UNMOUNTING)}function i(e,t){R(!l(t)),R(!p.isValidComponent(t));var n=e.componentConstructor,r=n.prototype;for(var i in t){var a=t[i];if(t.hasOwnProperty(i))if(o(r,i),N.hasOwnProperty(i))N[i](e,a);else{var s=i in T,d=i in r,f=a&&a.__reactDontBind,h="function"==typeof a,m=h&&!s&&!d&&!f;m?(r.__reactAutoBindMap||(r.__reactAutoBindMap={}),r.__reactAutoBindMap[i]=a,r[i]=a):r[i]=d?T[i]===O.DEFINE_MANY_MERGED?u(r[i],a):c(r[i],a):a}}}function a(e,t){if(t)for(var n in t){var o=t[n];if(!t.hasOwnProperty(n))return;var r=n in e,i=o;if(r){var a=e[n],s=typeof a,u=typeof o;R("function"===s&&"function"===u),i=c(a,o)}e[n]=i,e.componentConstructor[n]=i}}function s(e,t){return R(e&&t&&"object"==typeof e&&"object"==typeof t),b(t,function(t,n){R(void 0===e[n]),e[n]=t}),e}function u(e,t){return function(){var n=e.apply(this,arguments),o=t.apply(this,arguments);return null==n?o:null==o?n:s(n,o)}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e){return e instanceof Function&&"componentConstructor"in e&&e.componentConstructor instanceof Function}var p=e("./ReactComponent"),d=e("./ReactContext"),f=e("./ReactCurrentOwner"),h=e("./ReactErrorUtils"),m=e("./ReactOwner"),v=e("./ReactPerf"),g=e("./ReactPropTransferer"),C=e("./ReactPropTypeLocations"),y=(e("./ReactPropTypeLocationNames"),e("./ReactUpdates")),E=e("./instantiateReactComponent"),R=e("./invariant"),M=e("./keyMirror"),D=e("./merge"),x=e("./mixInto"),b=(e("./monitorCodeUse"),e("./objMap")),P=e("./shouldUpdateReactComponent"),O=(e("./warning"),M({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null})),I=[],T={mixins:O.DEFINE_MANY,statics:O.DEFINE_MANY,propTypes:O.DEFINE_MANY,contextTypes:O.DEFINE_MANY,childContextTypes:O.DEFINE_MANY,getDefaultProps:O.DEFINE_MANY_MERGED,getInitialState:O.DEFINE_MANY_MERGED,getChildContext:O.DEFINE_MANY_MERGED,render:O.DEFINE_ONCE,componentWillMount:O.DEFINE_MANY,componentDidMount:O.DEFINE_MANY,componentWillReceiveProps:O.DEFINE_MANY,shouldComponentUpdate:O.DEFINE_ONCE,componentWillUpdate:O.DEFINE_MANY,componentDidUpdate:O.DEFINE_MANY,componentWillUnmount:O.DEFINE_MANY,updateComponent:O.OVERRIDE_BASE},N={displayName:function(e,t){e.componentConstructor.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,t){var o=e.componentConstructor;n(o,t,C.childContext),o.childContextTypes=D(o.childContextTypes,t)},contextTypes:function(e,t){var o=e.componentConstructor;n(o,t,C.context),o.contextTypes=D(o.contextTypes,t)},propTypes:function(e,t){var o=e.componentConstructor;n(o,t,C.prop),o.propTypes=D(o.propTypes,t)},statics:function(e,t){a(e,t)}},S=M({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null,RECEIVING_STATE:null}),_={construct:function(){p.Mixin.construct.apply(this,arguments),m.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this.context=null,this._currentContext=d.current,this._pendingContext=null,this._descriptor=null,this._compositeLifeCycleState=null},toJSON:function(){return{type:this.type,props:this.props}},isMounted:function(){return p.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==S.MOUNTING},mountComponent:v.measure("ReactCompositeComponent","mountComponent",function(e,t,n){p.Mixin.mountComponent.call(this,e,t,n),this._compositeLifeCycleState=S.MOUNTING,this.context=this._processContext(this._currentContext),this._defaultProps=this.getDefaultProps?this.getDefaultProps():null,this.props=this._processProps(this.props),this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.state=this.getInitialState?this.getInitialState():null,R("object"==typeof this.state&&!Array.isArray(this.state)),this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=E(this._renderValidatedComponent()),this._compositeLifeCycleState=null;var o=this._renderedComponent.mountComponent(e,t,n+1);return this.componentDidMount&&t.getReactMountReady().enqueue(this,this.componentDidMount),o}),unmountComponent:function(){this._compositeLifeCycleState=S.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._defaultProps=null,this._renderedComponent.unmountComponent(),this._renderedComponent=null,p.Mixin.unmountComponent.call(this)},setState:function(e,t){R("object"==typeof e||null==e),this.replaceState(D(this._pendingState||this.state,e),t)},replaceState:function(e,t){r(this),this._pendingState=e,y.enqueueUpdate(this,t)},_processContext:function(e){var t=null,n=this.constructor.contextTypes;if(n){t={};for(var o in n)t[o]=e[o]}return t},_processChildContext:function(e){var t=this.getChildContext&&this.getChildContext();if(this.constructor.displayName||"ReactCompositeComponent",t){R("object"==typeof this.constructor.childContextTypes);for(var n in t)R(n in this.constructor.childContextTypes);return D(e,t)}return e},_processProps:function(e){var t=D(e),n=this._defaultProps;for(var o in n)"undefined"==typeof t[o]&&(t[o]=n[o]);return t},_checkPropTypes:function(e,t,n){var o=this.constructor.displayName;for(var r in e)e.hasOwnProperty(r)&&e[r](t,r,o,n)},performUpdateIfNecessary:function(){var e=this._compositeLifeCycleState;e!==S.MOUNTING&&e!==S.RECEIVING_PROPS&&p.Mixin.performUpdateIfNecessary.call(this)},_performUpdateIfNecessary:function(e){if(null!=this._pendingProps||null!=this._pendingState||null!=this._pendingContext||this._pendingForceUpdate){var t=this._pendingContext||this._currentContext,n=this._processContext(t);this._pendingContext=null;var o=this.props;null!=this._pendingProps&&(o=this._processProps(this._pendingProps),this._pendingProps=null,this._compositeLifeCycleState=S.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(o,n)),this._compositeLifeCycleState=S.RECEIVING_STATE;var r=this._pendingOwner,i=this._pendingState||this.state;this._pendingState=null;try{this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(o,i,n)?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,t,n,e)):(this.props=o,this._owner=r,this.state=i,this._currentContext=t,this.context=n)}finally{this._compositeLifeCycleState=null}}},_performComponentUpdate:function(e,t,n,o,r,i){var a=this.props,s=this._owner,u=this.state,c=this.context;this.componentWillUpdate&&this.componentWillUpdate(e,n,r),this.props=e,this._owner=t,this.state=n,this._currentContext=o,this.context=r,this.updateComponent(i,a,s,u,c),this.componentDidUpdate&&i.getReactMountReady().enqueue(this,this.componentDidUpdate.bind(this,a,u,c))},receiveComponent:function(e,t){e!==this._descriptor&&(this._descriptor=e,this._pendingContext=e._currentContext,p.Mixin.receiveComponent.call(this,e,t))},updateComponent:v.measure("ReactCompositeComponent","updateComponent",function(e,t,n){p.Mixin.updateComponent.call(this,e,t,n);var o=this._renderedComponent,r=this._renderValidatedComponent();if(P(o,r))o.receiveComponent(r,e);else{var i=this._rootNodeID,a=o._rootNodeID;o.unmountComponent(),this._renderedComponent=E(r);var s=this._renderedComponent.mountComponent(i,e,this._mountDepth+1);p.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(a,s)}}),forceUpdate:function(e){var t=this._compositeLifeCycleState;R(this.isMounted()||t===S.MOUNTING),R(t!==S.RECEIVING_STATE&&t!==S.UNMOUNTING),this._pendingForceUpdate=!0,y.enqueueUpdate(this,e)},_renderValidatedComponent:v.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var e,t=d.current;d.current=this._processChildContext(this._currentContext),f.current=this;try{e=this.render()}finally{d.current=t,f.current=null}return R(p.isValidComponent(e)),e}),_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(h.guard(t,this.constructor.displayName+"."+e))}},_bindAutoBindMethod:function(e){var t=this,n=function(){return e.apply(t,arguments)};return n}},w=function(){};x(w,p.Mixin),x(w,m.Mixin),x(w,g.Mixin),x(w,_);var A={LifeCycle:S,Base:w,createClass:function(e){var t=function(){};t.prototype=new w,t.prototype.constructor=t;var n=t,o=function(){var e=new n;return e.construct.apply(e,arguments),e};o.componentConstructor=t,t.ConvenienceConstructor=o,o.originalSpec=e,I.forEach(i.bind(null,o)),i(o,e),R(t.prototype.render),o.type=t,t.prototype.type=t;for(var r in T)t.prototype[r]||(t.prototype[r]=null);return o},isValidClass:l,injection:{injectMixin:function(e){I.push(e)}}};t.exports=A},{"./ReactComponent":27,"./ReactContext":30,"./ReactCurrentOwner":31,"./ReactErrorUtils":45,"./ReactOwner":57,"./ReactPerf":58,"./ReactPropTransferer":59,"./ReactPropTypeLocationNames":60,"./ReactPropTypeLocations":61,"./ReactUpdates":69,"./instantiateReactComponent":109,"./invariant":110,"./keyMirror":116,"./merge":119,"./mixInto":122,"./monitorCodeUse":123,"./objMap":124,"./shouldUpdateReactComponent":128,"./warning":131}],30:[function(e,t){"use strict";var n=e("./merge"),o={current:{},withContext:function(e,t){var r,i=o.current;o.current=n(i,e);try{r=t()}finally{o.current=i}return r}};t.exports=o},{"./merge":119}],31:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],32:[function(e,t){"use strict";function n(e,t){var n=function(){};n.prototype=new o(e,t),n.prototype.constructor=n,n.displayName=e;var r=function(){var e=new n;return e.construct.apply(e,arguments),e};return r.type=n,n.prototype.type=n,n.ConvenienceConstructor=r,r.componentConstructor=n,r}var o=e("./ReactDOMComponent"),r=e("./mergeInto"),i=e("./objMapKeyVal"),a=i({a:!1,abbr:!1,address:!1,area:!0,article:!1,aside:!1,audio:!1,b:!1,base:!0,bdi:!1,bdo:!1,big:!1,blockquote:!1,body:!1,br:!0,button:!1,canvas:!1,caption:!1,cite:!1,code:!1,col:!0,colgroup:!1,data:!1,datalist:!1,dd:!1,del:!1,details:!1,dfn:!1,div:!1,dl:!1,dt:!1,em:!1,embed:!0,fieldset:!1,figcaption:!1,figure:!1,footer:!1,form:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,head:!1,header:!1,hr:!0,html:!1,i:!1,iframe:!1,img:!0,input:!0,ins:!1,kbd:!1,keygen:!0,label:!1,legend:!1,li:!1,link:!0,main:!1,map:!1,mark:!1,menu:!1,menuitem:!1,meta:!0,meter:!1,nav:!1,noscript:!1,object:!1,ol:!1,optgroup:!1,option:!1,output:!1,p:!1,param:!0,pre:!1,progress:!1,q:!1,rp:!1,rt:!1,ruby:!1,s:!1,samp:!1,script:!1,section:!1,select:!1,small:!1,source:!0,span:!1,strong:!1,style:!1,sub:!1,summary:!1,sup:!1,table:!1,tbody:!1,td:!1,textarea:!1,tfoot:!1,th:!1,thead:!1,time:!1,title:!1,tr:!1,track:!0,u:!1,ul:!1,"var":!1,video:!1,wbr:!0,circle:!1,defs:!1,g:!1,line:!1,linearGradient:!1,path:!1,polygon:!1,polyline:!1,radialGradient:!1,rect:!1,stop:!1,svg:!1,text:!1},n),s={injectComponentClasses:function(e){r(a,e)}};a.injection=s,t.exports=a},{"./ReactDOMComponent":34,"./mergeInto":121,"./objMapKeyVal":125}],33:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),o=e("./ReactBrowserComponentMixin"),r=e("./ReactCompositeComponent"),i=e("./ReactDOM"),a=e("./keyMirror"),s=i.button,u=a({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=r.createClass({displayName:"ReactDOMButton",mixins:[n,o],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&u[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=c},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./keyMirror":116}],34:[function(e,t){"use strict";function n(e){e&&(m(null==e.children||null==e.dangerouslySetInnerHTML),m(null==e.style||"object"==typeof e.style))}function o(e,t,n,o){var r=p.findReactContainerForID(e);if(r){var i=r.nodeType===x?r.ownerDocument:r;E(t,i)}o.getPutListenerQueue().enqueuePutListener(e,t,n)}function r(e,t){this._tagOpen="<"+e,this._tagClose=t?"":"</"+e+">",this.tagName=e.toUpperCase()}var i=e("./CSSPropertyOperations"),a=e("./DOMProperty"),s=e("./DOMPropertyOperations"),u=e("./ReactBrowserComponentMixin"),c=e("./ReactComponent"),l=e("./ReactEventEmitter"),p=e("./ReactMount"),d=e("./ReactMultiChild"),f=e("./ReactPerf"),h=e("./escapeTextForBrowser"),m=e("./invariant"),v=e("./keyOf"),g=e("./merge"),C=e("./mixInto"),y=l.deleteListener,E=l.listenTo,R=l.registrationNameModules,M={string:!0,number:!0},D=v({style:null}),x=1;r.Mixin={mountComponent:f.measure("ReactDOMComponent","mountComponent",function(e,t,o){return c.Mixin.mountComponent.call(this,e,t,o),n(this.props),this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+this._tagClose}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n=this._tagOpen;for(var r in t)if(t.hasOwnProperty(r)){var a=t[r];if(null!=a)if(R[r])o(this._rootNodeID,r,a,e);else{r===D&&(a&&(a=t.style=g(t.style)),a=i.createMarkupForStyles(a));var u=s.createMarkupForProperty(r,a);u&&(n+=" "+u)}}if(e.renderToStaticMarkup)return n+">";var c=s.createMarkupForID(this._rootNodeID);return n+" "+c+">"},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=M[typeof this.props.children]?this.props.children:null,o=null!=n?null:this.props.children;if(null!=n)return h(n);if(null!=o){var r=this.mountChildren(o,e);return r.join("")}}return""},receiveComponent:function(e,t){e!==this&&(n(e.props),c.Mixin.receiveComponent.call(this,e,t))},updateComponent:f.measure("ReactDOMComponent","updateComponent",function(e,t,n){c.Mixin.updateComponent.call(this,e,t,n),this._updateDOMProperties(t,e),this._updateDOMChildren(t,e)}),_updateDOMProperties:function(e,t){var n,r,i,s=this.props;for(n in e)if(!s.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===D){var u=e[n];for(r in u)u.hasOwnProperty(r)&&(i=i||{},i[r]="")}else R[n]?y(this._rootNodeID,n):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in s){var l=s[n],p=e[n];if(s.hasOwnProperty(n)&&l!==p)if(n===D)if(l&&(l=s.style=g(l)),p){for(r in p)p.hasOwnProperty(r)&&!l.hasOwnProperty(r)&&(i=i||{},i[r]="");for(r in l)l.hasOwnProperty(r)&&p[r]!==l[r]&&(i=i||{},i[r]=l[r])}else i=l;else R[n]?o(this._rootNodeID,n,l,t):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,l)}i&&c.BackendIDOperations.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t){var n=this.props,o=M[typeof e.children]?e.children:null,r=M[typeof n.children]?n.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,u=null!=r?null:n.children,l=null!=o||null!=i,p=null!=r||null!=a;null!=s&&null==u?this.updateChildren(null,t):l&&!p&&this.updateTextContent(""),null!=r?o!==r&&this.updateTextContent(""+r):null!=a?i!==a&&c.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,t)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.Mixin.unmountComponent.call(this)}},C(r,c.Mixin),C(r,r.Mixin),C(r,d.Mixin),C(r,u),t.exports=r},{"./CSSPropertyOperations":3,"./DOMProperty":8,"./DOMPropertyOperations":9,"./ReactBrowserComponentMixin":25,"./ReactComponent":27,"./ReactEventEmitter":46,"./ReactMount":53,"./ReactMultiChild":55,"./ReactPerf":58,"./escapeTextForBrowser":96,"./invariant":110,"./keyOf":117,"./merge":119,"./mixInto":122}],35:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),r=e("./ReactDOM"),i=e("./ReactEventEmitter"),a=e("./EventConstants"),s=r.form,u=o.createClass({displayName:"ReactDOMForm",mixins:[n],render:function(){return this.transferPropsTo(s(null,this.props.children))},componentDidMount:function(){i.trapBubbledEvent(a.topLevelTypes.topReset,"reset",this.getDOMNode()),i.trapBubbledEvent(a.topLevelTypes.topSubmit,"submit",this.getDOMNode())}});t.exports=u},{"./EventConstants":14,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":46}],36:[function(e,t){"use strict";var n,o=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),i=e("./DOMPropertyOperations"),a=e("./ReactMount"),s=e("./ReactPerf"),u=e("./invariant"),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:s.measure("ReactDOMIDOperations","updatePropertyByID",function(e,t,n){var o=a.getNode(e);u(!c.hasOwnProperty(t)),null!=n?i.setValueForProperty(o,t,n):i.deleteValueForProperty(o,t)}),deletePropertyByID:s.measure("ReactDOMIDOperations","deletePropertyByID",function(e,t,n){var o=a.getNode(e);u(!c.hasOwnProperty(t)),i.deleteValueForProperty(o,t,n)}),updateStylesByID:s.measure("ReactDOMIDOperations","updateStylesByID",function(e,t){var n=a.getNode(e);o.setValueForStyles(n,t)}),updateInnerHTMLByID:s.measure("ReactDOMIDOperations","updateInnerHTMLByID",function(e,t){var o=a.getNode(e);if(void 0===n){var r=document.createElement("div");r.innerHTML=" ",n=""===r.innerHTML}n&&o.parentNode.replaceChild(o,o),n&&t.match(/^[ \r\n\t\f]/)?(o.innerHTML=""+t,o.firstChild.deleteData(0,1)):o.innerHTML=t}),updateTextContentByID:s.measure("ReactDOMIDOperations","updateTextContentByID",function(e,t){var n=a.getNode(e);r.updateTextContent(n,t)}),dangerouslyReplaceNodeWithMarkupByID:s.measure("ReactDOMIDOperations","dangerouslyReplaceNodeWithMarkupByID",function(e,t){var n=a.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)}),dangerouslyProcessChildrenUpdates:s.measure("ReactDOMIDOperations","dangerouslyProcessChildrenUpdates",function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);r.processUpdates(e,t)})};t.exports=l},{"./CSSPropertyOperations":3,"./DOMChildrenOperations":7,"./DOMPropertyOperations":9,"./ReactMount":53,"./ReactPerf":58,"./invariant":110}],37:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),r=e("./ReactDOM"),i=e("./ReactEventEmitter"),a=e("./EventConstants"),s=r.img,u=o.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[n],render:function(){return s(this.props)},componentDidMount:function(){var e=this.getDOMNode();i.trapBubbledEvent(a.topLevelTypes.topLoad,"load",e),i.trapBubbledEvent(a.topLevelTypes.topError,"error",e)}});t.exports=u},{"./EventConstants":14,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":46}],38:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),o=e("./DOMPropertyOperations"),r=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./ReactMount"),c=e("./invariant"),l=e("./merge"),p=s.input,d={},f=a.createClass({displayName:"ReactDOMInput",mixins:[n,r.Mixin,i],getInitialState:function(){var e=this.props.defaultValue;return{checked:this.props.defaultChecked||!1,value:null!=e?e:null}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=l(this.props);e.defaultChecked=null,e.defaultValue=null;var t=r.getValue(this);e.value=null!=t?t:this.state.value;var n=r.getChecked(this);return e.checked=null!=n?n:this.state.checked,e.onChange=this._handleChange,p(e,this.props.children)},componentDidMount:function(){var e=u.getID(this.getDOMNode());d[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=u.getID(e);delete d[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&o.setValueForProperty(e,"checked",this.props.checked||!1);var t=r.getValue(this);null!=t&&o.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,n=r.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({checked:e.target.checked,value:e.target.value});var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var i=this.getDOMNode(),a=i;a.parentNode;)a=a.parentNode;for(var s=a.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),l=0,p=s.length;p>l;l++){var f=s[l];if(f!==i&&f.form===i.form){var h=u.getID(f);c(h);var m=d[h];c(m),m.setState({checked:!1})}}}return t}});t.exports=f},{"./AutoFocusMixin":1,"./DOMPropertyOperations":9,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactMount":53,"./invariant":110,"./merge":119}],39:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),r=e("./ReactDOM"),i=(e("./warning"),r.option),a=o.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return i(this.props,this.props.children)}});t.exports=a},{"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./warning":131}],40:[function(e,t){"use strict";function n(e,t){null!=e[t]&&c(e.multiple?Array.isArray(e[t]):!Array.isArray(e[t]))}function o(e,t){var n,o,r,i=e.props.multiple,a=null!=t?t:e.state.value,s=e.getDOMNode().options;if(i)for(n={},o=0,r=a.length;r>o;++o)n[""+a[o]]=!0;else n=""+a;for(o=0,r=s.length;r>o;o++){var u=i?n.hasOwnProperty(s[o].value):s[o].value===n;u!==s[o].selected&&(s[o].selected=u)}}var r=e("./AutoFocusMixin"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactDOM"),c=e("./invariant"),l=e("./merge"),p=u.select,d=s.createClass({displayName:"ReactDOMSelect",mixins:[r,i.Mixin,a],propTypes:{defaultValue:n,value:n},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillReceiveProps:function(e){!this.props.multiple&&e.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!e.multiple&&this.setState({value:this.state.value[0]})},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=l(this.props);return e.onChange=this._handleChange,e.value=null,p(e,this.props.children)},componentDidMount:function(){o(this,i.getValue(this))},componentDidUpdate:function(){var e=i.getValue(this);null!=e&&o(this,e)},_handleChange:function(e){var t,n=i.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1);var o;if(this.props.multiple){o=[];for(var r=e.target.options,a=0,s=r.length;s>a;a++)r[a].selected&&o.push(r[a].value)}else o=e.target.value;return this.setState({value:o}),t}});t.exports=d},{"./AutoFocusMixin":1,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./invariant":110,"./merge":119}],41:[function(e,t){"use strict";function n(e){var t=document.selection,n=t.createRange(),o=n.text.length,r=n.duplicate();r.moveToElementText(e),r.setEndPoint("EndToStart",n);var i=r.text.length,a=i+o;return{start:i,end:a}}function o(e){var t=window.getSelection();if(0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,r=t.focusNode,i=t.focusOffset,a=t.getRangeAt(0),s=a.toString().length,u=a.cloneRange();u.selectNodeContents(e),u.setEnd(a.startContainer,a.startOffset);var c=u.toString().length,l=c+s,p=document.createRange();p.setStart(n,o),p.setEnd(r,i);var d=p.collapsed;return p.detach(),{start:d?l:c,end:d?c:l}}function r(e,t){var n,o,r=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,o=n):t.start>t.end?(n=t.end,o=t.start):(n=t.start,o=t.end),r.moveToElementText(e),r.moveStart("character",n),r.setEndPoint("EndToStart",r),r.moveEnd("character",o-n),r.select()}function i(e,t){var n=window.getSelection(),o=e[s()].length,r=Math.min(t.start,o),i="undefined"==typeof t.end?r:Math.min(t.end,o);if(!n.extend&&r>i){var u=i;i=r,r=u}var c=a(e,r),l=a(e,i);if(c&&l){var p=document.createRange();p.setStart(c.node,c.offset),n.removeAllRanges(),r>i?(n.addRange(p),n.extend(l.node,l.offset)):(p.setEnd(l.node,l.offset),n.addRange(p)),p.detach()}}var a=e("./getNodeForCharacterOffset"),s=e("./getTextContentAccessor"),u={getOffsets:function(e){var t=document.selection?n:o;return t(e)},setOffsets:function(e,t){var n=document.selection?r:i;n(e,t)}};t.exports=u},{"./getNodeForCharacterOffset":104,"./getTextContentAccessor":106}],42:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),o=e("./DOMPropertyOperations"),r=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./invariant"),c=e("./merge"),l=(e("./warning"),s.textarea),p=a.createClass({displayName:"ReactDOMTextarea",mixins:[n,r.Mixin,i],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(u(null==e),Array.isArray(t)&&(u(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=r.getValue(this);return{initialValue:""+(null!=n?n:e),value:e}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props),t=r.getValue(this);return u(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null!=t?t:this.state.value,e.onChange=this._handleChange,l(e,this.state.initialValue)},componentDidUpdate:function(){var e=r.getValue(this);if(null!=e){var t=this.getDOMNode();o.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,n=r.getOnChange(this);return n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({value:e.target.value}),t}});t.exports=p},{"./AutoFocusMixin":1,"./DOMPropertyOperations":9,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./invariant":110,"./merge":119,"./warning":131}],43:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var o=e("./ReactUpdates"),r=e("./Transaction"),i=e("./emptyFunction"),a=e("./mixInto"),s={initialize:i,close:function(){p.isBatchingUpdates=!1}},u={initialize:i,close:o.flushBatchedUpdates.bind(o)},c=[u,s];a(n,r.Mixin),a(n,{getTransactionWrappers:function(){return c}});var l=new n,p={isBatchingUpdates:!1,batchedUpdates:function(e,t){var n=p.isBatchingUpdates;p.isBatchingUpdates=!0,n?e(t):l.perform(e,null,t)}};t.exports=p},{"./ReactUpdates":69,"./Transaction":83,"./emptyFunction":94,"./mixInto":122}],44:[function(e,t){"use strict";function n(){o.EventEmitter.injectTopLevelCallbackCreator(h),o.EventPluginHub.injectEventPluginOrder(c),o.EventPluginHub.injectInstanceHandle(D),o.EventPluginHub.injectMount(x),o.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:O,EnterLeaveEventPlugin:l,ChangeEventPlugin:a,CompositionEventPlugin:u,MobileSafariClickEventPlugin:p,SelectEventPlugin:b}),o.DOM.injectComponentClasses({button:v,form:g,img:C,input:y,option:E,select:R,textarea:M,html:T(m.html),head:T(m.head),title:T(m.title),body:T(m.body)}),o.CompositeComponent.injectMixin(d),o.DOMProperty.injectDOMPropertyConfig(i),o.Updates.injectBatchingStrategy(I),o.RootIndex.injectCreateReactRootIndex(r.canUseDOM?s.createReactRootIndex:P.createReactRootIndex),o.Component.injectEnvironment(f)}var o=e("./ReactInjection"),r=e("./ExecutionEnvironment"),i=e("./DefaultDOMPropertyConfig"),a=e("./ChangeEventPlugin"),s=e("./ClientReactRootIndex"),u=e("./CompositionEventPlugin"),c=e("./DefaultEventPluginOrder"),l=e("./EnterLeaveEventPlugin"),p=e("./MobileSafariClickEventPlugin"),d=e("./ReactBrowserComponentMixin"),f=e("./ReactComponentBrowserEnvironment"),h=e("./ReactEventTopLevelCallback"),m=e("./ReactDOM"),v=e("./ReactDOMButton"),g=e("./ReactDOMForm"),C=e("./ReactDOMImg"),y=e("./ReactDOMInput"),E=e("./ReactDOMOption"),R=e("./ReactDOMSelect"),M=e("./ReactDOMTextarea"),D=e("./ReactInstanceHandles"),x=e("./ReactMount"),b=e("./SelectEventPlugin"),P=e("./ServerReactRootIndex"),O=e("./SimpleEventPlugin"),I=e("./ReactDefaultBatchingStrategy"),T=e("./createFullPageComponent");t.exports={inject:n}},{"./ChangeEventPlugin":4,"./ClientReactRootIndex":5,"./CompositionEventPlugin":6,"./DefaultDOMPropertyConfig":11,"./DefaultEventPluginOrder":12,"./EnterLeaveEventPlugin":13,"./ExecutionEnvironment":20,"./MobileSafariClickEventPlugin":22,"./ReactBrowserComponentMixin":25,"./ReactComponentBrowserEnvironment":28,"./ReactDOM":32,"./ReactDOMButton":33,"./ReactDOMForm":35,"./ReactDOMImg":37,"./ReactDOMInput":38,"./ReactDOMOption":39,"./ReactDOMSelect":40,"./ReactDOMTextarea":42,"./ReactDefaultBatchingStrategy":43,"./ReactEventTopLevelCallback":48,"./ReactInjection":49,"./ReactInstanceHandles":51,"./ReactMount":53,"./SelectEventPlugin":70,"./ServerReactRootIndex":71,"./SimpleEventPlugin":72,"./createFullPageComponent":90}],45:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],46:[function(e,t){"use strict";function n(e){return null==e[y]&&(e[y]=g++,m[e[y]]={}),m[e[y]]}function o(e,t,n){a.listen(n,t,E.TopLevelCallbackCreator.createTopLevelCallback(e))}function r(e,t,n){a.capture(n,t,E.TopLevelCallbackCreator.createTopLevelCallback(e))}var i=e("./EventConstants"),a=e("./EventListener"),s=e("./EventPluginHub"),u=e("./EventPluginRegistry"),c=e("./ExecutionEnvironment"),l=e("./ReactEventEmitterMixin"),p=e("./ViewportMetrics"),d=e("./invariant"),f=e("./isEventSupported"),h=e("./merge"),m={},v=!1,g=0,C={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"},y="_reactListenersID"+String(Math.random()).slice(2),E=h(l,{TopLevelCallbackCreator:null,injection:{injectTopLevelCallbackCreator:function(e){E.TopLevelCallbackCreator=e}},setEnabled:function(e){d(c.canUseDOM),E.TopLevelCallbackCreator&&E.TopLevelCallbackCreator.setEnabled(e)},isEnabled:function(){return!(!E.TopLevelCallbackCreator||!E.TopLevelCallbackCreator.isEnabled())},listenTo:function(e,t){for(var a=t,s=n(a),c=u.registrationNameDependencies[e],l=i.topLevelTypes,p=0,d=c.length;d>p;p++){var h=c[p];if(!s[h]){var m=l[h];m===l.topWheel?f("wheel")?o(l.topWheel,"wheel",a):f("mousewheel")?o(l.topWheel,"mousewheel",a):o(l.topWheel,"DOMMouseScroll",a):m===l.topScroll?f("scroll",!0)?r(l.topScroll,"scroll",a):o(l.topScroll,"scroll",window):m===l.topFocus||m===l.topBlur?(f("focus",!0)?(r(l.topFocus,"focus",a),r(l.topBlur,"blur",a)):f("focusin")&&(o(l.topFocus,"focusin",a),o(l.topBlur,"focusout",a)),s[l.topBlur]=!0,s[l.topFocus]=!0):C[h]&&o(m,C[h],a),s[h]=!0}}},ensureScrollValueMonitoring:function(){if(!v){var e=p.refreshScrollValues;a.listen(window,"scroll",e),a.listen(window,"resize",e),v=!0}},eventNameDispatchConfigs:s.eventNameDispatchConfigs,registrationNameModules:s.registrationNameModules,putListener:s.putListener,getListener:s.getListener,deleteListener:s.deleteListener,deleteAllListeners:s.deleteAllListeners,trapBubbledEvent:o,trapCapturedEvent:r});t.exports=E},{"./EventConstants":14,"./EventListener":15,"./EventPluginHub":16,"./EventPluginRegistry":17,"./ExecutionEnvironment":20,"./ReactEventEmitterMixin":47,"./ViewportMetrics":84,"./invariant":110,"./isEventSupported":111,"./merge":119}],47:[function(e,t){"use strict";function n(e){o.enqueueEvents(e),o.processEventQueue()}var o=e("./EventPluginHub"),r=e("./ReactUpdates"),i={handleTopLevel:function(e,t,i,a){var s=o.extractEvents(e,t,i,a); r.batchedUpdates(n,s)}};t.exports=i},{"./EventPluginHub":16,"./ReactUpdates":69}],48:[function(e,t){"use strict";function n(e){var t=u.getID(e),n=s.getReactRootIDFromNodeID(t),o=u.findReactContainerForID(n),r=u.getFirstReactDOM(o);return r}function o(e,t,o){for(var r=u.getFirstReactDOM(c(t))||window,i=r;i;)o.ancestors.push(i),i=n(i);for(var s=0,l=o.ancestors.length;l>s;s++){r=o.ancestors[s];var p=u.getID(r)||"";a.handleTopLevel(e,r,p,t)}}function r(){this.ancestors=[]}var i=e("./PooledClass"),a=e("./ReactEventEmitter"),s=e("./ReactInstanceHandles"),u=e("./ReactMount"),c=e("./getEventTarget"),l=e("./mixInto"),p=!0;l(r,{destructor:function(){this.ancestors.length=0}}),i.addPoolingTo(r);var d={setEnabled:function(e){p=!!e},isEnabled:function(){return p},createTopLevelCallback:function(e){return function(t){if(p){var n=r.getPooled();try{o(e,t,n)}finally{r.release(n)}}}}};t.exports=d},{"./PooledClass":23,"./ReactEventEmitter":46,"./ReactInstanceHandles":51,"./ReactMount":53,"./getEventTarget":102,"./mixInto":122}],49:[function(e,t){"use strict";var n=e("./DOMProperty"),o=e("./EventPluginHub"),r=e("./ReactComponent"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=e("./ReactEventEmitter"),u=e("./ReactPerf"),c=e("./ReactRootIndex"),l=e("./ReactUpdates"),p={Component:r.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EventPluginHub:o.injection,DOM:a.injection,EventEmitter:s.injection,Perf:u.injection,RootIndex:c.injection,Updates:l.injection};t.exports=p},{"./DOMProperty":8,"./EventPluginHub":16,"./ReactComponent":27,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":46,"./ReactPerf":58,"./ReactRootIndex":65,"./ReactUpdates":69}],50:[function(e,t){"use strict";function n(e){return r(document.documentElement,e)}var o=e("./ReactDOMSelection"),r=e("./containsNode"),i=e("./focusNode"),a=e("./getActiveElement"),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=a();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=a(),o=e.focusedElem,r=e.selectionRange;t!==o&&n(o)&&(s.hasSelectionCapabilities(o)&&s.setSelection(o,r),i(o))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};t.exports=s},{"./ReactDOMSelection":41,"./containsNode":87,"./focusNode":98,"./getActiveElement":100}],51:[function(e,t){"use strict";function n(e){return d+e.toString(36)}function o(e,t){return e.charAt(t)===d||t===e.length}function r(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function i(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(d)):""}function s(e,t){if(p(r(e)&&r(t)),p(i(e,t)),e===t)return e;for(var n=e.length+f,a=n;a<t.length&&!o(t,a);a++);return t.substr(0,a)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return p(r(s)),s}function c(e,t,n,o,r,u){e=e||"",t=t||"",p(e!==t);var c=i(t,e);p(c||i(e,t));for(var l=0,d=c?a:s,f=e;;f=d(f,t)){var m;if(r&&f===e||u&&f===t||(m=n(f,c,o)),m===!1||f===t)break;p(l++<h)}}var l=e("./ReactRootIndex"),p=e("./invariant"),d=".",f=d.length,h=100,m={createReactRootID:function(){return n(l.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,o,r){var i=u(e,t);i!==e&&c(e,i,n,o,!1,!0),i!==t&&c(i,t,n,r,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};t.exports=m},{"./ReactRootIndex":65,"./invariant":110}],52:[function(e,t){"use strict";var n=e("./adler32"),o={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+o.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var r=t.getAttribute(o.CHECKSUM_ATTR_NAME);r=r&&parseInt(r,10);var i=n(e);return i===r}};t.exports=o},{"./adler32":86}],53:[function(e,t){"use strict";function n(e){var t=v(e);return t&&T.getID(t)}function o(e){var t=r(e);if(t)if(M.hasOwnProperty(t)){var n=M[t];n!==e&&(C(!s(n,t)),M[t]=e)}else M[t]=e;return t}function r(e){return e&&e.getAttribute&&e.getAttribute(R)||""}function i(e,t){var n=r(e);n!==t&&delete M[n],e.setAttribute(R,t),M[t]=e}function a(e){return M.hasOwnProperty(e)&&s(M[e],e)||(M[e]=T.findReactNodeByID(e)),M[e]}function s(e,t){if(e){C(r(e)===t);var n=T.findReactContainerForID(t);if(n&&m(n,e))return!0}return!1}function u(e){delete M[e]}function c(e){var t=M[e];return t&&s(t,e)?void(I=t):!1}function l(e){I=null,f.traverseAncestors(e,c);var t=I;return I=null,t}var p=e("./DOMProperty"),d=e("./ReactEventEmitter"),f=e("./ReactInstanceHandles"),h=e("./ReactPerf"),m=e("./containsNode"),v=e("./getReactRootElementInContainer"),g=e("./instantiateReactComponent"),C=e("./invariant"),y=e("./shouldUpdateReactComponent"),E=f.SEPARATOR,R=p.ID_ATTRIBUTE_NAME,M={},D=1,x=9,b={},P={},O=[],I=null,T={totalInstantiationTime:0,totalInjectionTime:0,useTouchEvents:!1,_instancesByReactRootID:b,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,o){var r=t.props;return T.scrollMonitor(n,function(){e.replaceProps(r,o)}),e},_registerComponent:function(e,t){C(t&&(t.nodeType===D||t.nodeType===x)),d.ensureScrollValueMonitoring();var n=T.registerContainer(t);return b[n]=e,n},_renderNewRootComponent:h.measure("ReactMount","_renderNewRootComponent",function(e,t,n){var o=g(e),r=T._registerComponent(o,t);return o.mountComponentIntoNode(r,t,n),o}),renderComponent:function(e,t,o){var r=b[n(t)];if(r){if(y(r,e))return T._updateRootComponent(r,e,t,o);T.unmountComponentAtNode(t)}var i=v(t),a=i&&T.isRenderedByReact(i),s=a&&!r,u=T._renderNewRootComponent(e,t,s);return o&&o.call(u),u},constructAndRenderComponent:function(e,t,n){return T.renderComponent(e(t),n)},constructAndRenderComponentByID:function(e,t,n){var o=document.getElementById(n);return C(o),T.constructAndRenderComponent(e,t,o)},registerContainer:function(e){var t=n(e);return t&&(t=f.getReactRootIDFromNodeID(t)),t||(t=f.createReactRootID()),P[t]=e,t},unmountComponentAtNode:function(e){var t=n(e),o=b[t];return o?(T.unmountComponentFromNode(o,e),delete b[t],delete P[t],!0):!1},unmountComponentFromNode:function(e,t){for(e.unmountComponent(),t.nodeType===x&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=f.getReactRootIDFromNodeID(e),n=P[t];return n},findReactNodeByID:function(e){var t=T.findReactContainerForID(e);return T.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=T.getID(e);return t?t.charAt(0)===E:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(T.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=O,o=0,r=l(t)||e;for(n[0]=r.firstChild,n.length=1;o<n.length;){for(var i,a=n[o++];a;){var s=T.getID(a);s?t===s?i=a:f.isAncestorIDOf(s,t)&&(n.length=o=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,C(!1)},getReactRootID:n,getID:o,setID:i,getNode:a,purgeID:u};t.exports=T},{"./DOMProperty":8,"./ReactEventEmitter":46,"./ReactInstanceHandles":51,"./ReactPerf":58,"./containsNode":87,"./getReactRootElementInContainer":105,"./instantiateReactComponent":109,"./invariant":110,"./shouldUpdateReactComponent":128}],54:[function(e,t){"use strict";function n(e){this._queue=e||null}var o=e("./PooledClass"),r=e("./mixInto");r(n,{enqueue:function(e,t){this._queue=this._queue||[],this._queue.push({component:e,callback:t})},notifyAll:function(){var e=this._queue;if(e){this._queue=null;for(var t=0,n=e.length;n>t;t++){var o=e[t].component,r=e[t].callback;r.call(o)}e.length=0}},reset:function(){this._queue=null},destructor:function(){this.reset()}}),o.addPoolingTo(n),t.exports=n},{"./PooledClass":23,"./mixInto":122}],55:[function(e,t){"use strict";function n(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function o(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function r(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function a(){h.length&&(u.BackendIDOperations.dangerouslyProcessChildrenUpdates(h,m),s())}function s(){h.length=0,m.length=0}var u=e("./ReactComponent"),c=e("./ReactMultiChildUpdateTypes"),l=e("./flattenChildren"),p=e("./instantiateReactComponent"),d=e("./shouldUpdateReactComponent"),f=0,h=[],m=[],v={Mixin:{mountChildren:function(e,t){var n=l(e),o=[],r=0;this._renderedChildren=n;for(var i in n){var a=n[i];if(n.hasOwnProperty(i)){var s=p(a);n[i]=s;var u=this._rootNodeID+i,c=s.mountComponent(u,t,this._mountDepth+1);s._mountIndex=r,o.push(c),r++}}return o},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;for(var o in n)n.hasOwnProperty(o)&&this._unmountChildByName(n[o],o);this.setTextContent(e),t=!1}finally{f--,f||(t?s():a())}},updateChildren:function(e,t){f++;var n=!0;try{this._updateChildren(e,t),n=!1}finally{f--,f||(n?s():a())}},_updateChildren:function(e,t){var n=l(e),o=this._renderedChildren;if(n||o){var r,i=0,a=0;for(r in n)if(n.hasOwnProperty(r)){var s=o&&o[r],u=n[r];if(d(s,u))this.moveChild(s,a,i),i=Math.max(s._mountIndex,i),s.receiveComponent(u,t),s._mountIndex=a;else{s&&(i=Math.max(s._mountIndex,i),this._unmountChildByName(s,r));var c=p(u);this._mountChildByNameAtIndex(c,r,a,t)}a++}for(r in o)!o.hasOwnProperty(r)||n&&n[r]||this._unmountChildByName(o[r],r)}},unmountChildren:function(){var e=this._renderedChildren;for(var t in e){var n=e[t];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){r(this._rootNodeID,e._mountIndex)},setTextContent:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,o){var r=this._rootNodeID+t,i=e.mountComponent(r,o,this._mountDepth+1);e._mountIndex=n,this.createChild(e,i),this._renderedChildren=this._renderedChildren||{},this._renderedChildren[t]=e},_unmountChildByName:function(e,t){u.isValidComponent(e)&&(this.removeChild(e),e._mountIndex=null,e.unmountComponent(),delete this._renderedChildren[t])}}};t.exports=v},{"./ReactComponent":27,"./ReactMultiChildUpdateTypes":56,"./flattenChildren":97,"./instantiateReactComponent":109,"./shouldUpdateReactComponent":128}],56:[function(e,t){"use strict";var n=e("./keyMirror"),o=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=o},{"./keyMirror":116}],57:[function(e,t){"use strict";var n=e("./emptyObject"),o=e("./invariant"),r={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o(r.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o(r.isValidOwner(n)),n.refs[t]===e&&n.detachRef(t)},Mixin:{construct:function(){this.refs=n},attachRef:function(e,t){o(t.isOwnedBy(this));var r=this.refs===n?this.refs={}:this.refs;r[e]=t},detachRef:function(e){delete this.refs[e]}}};t.exports=r},{"./emptyObject":95,"./invariant":110}],58:[function(e,t){"use strict";function n(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:n,measure:function(e,t,n){return n},injection:{injectMeasure:function(e){o.storedMeasure=e}}};t.exports=o},{}],59:[function(e,t){"use strict";function n(e){return function(t,n,o){t[n]=t.hasOwnProperty(n)?e(t[n],o):o}}var o=e("./emptyFunction"),r=e("./invariant"),i=e("./joinClasses"),a=e("./merge"),s={children:o,className:n(i),key:o,ref:o,style:n(a)},u={TransferStrategies:s,mergeProps:function(e,t){var n=a(e);for(var o in t)if(t.hasOwnProperty(o)){var r=s[o];r&&s.hasOwnProperty(o)?r(n,o,t[o]):n.hasOwnProperty(o)||(n[o]=t[o])}return n},Mixin:{transferPropsTo:function(e){return r(e._owner===this),e.props=u.mergeProps(e.props,this.props),e}}};t.exports=u},{"./emptyFunction":94,"./invariant":110,"./joinClasses":115,"./merge":119}],60:[function(e,t){"use strict";var n={};t.exports=n},{}],61:[function(e,t){"use strict";var n=e("./keyMirror"),o=n({prop:null,context:null,childContext:null});t.exports=o},{"./keyMirror":116}],62:[function(e,t){"use strict";function n(e){switch(typeof e){case"number":case"string":return!0;case"object":if(Array.isArray(e))return e.every(n);if(h.isValidComponent(e))return!0;for(var t in e)if(!n(e[t]))return!1;return!0;default:return!1}}function o(e){var t=typeof e;return"object"===t&&Array.isArray(e)?"array":t}function r(){function e(){return!0}return f(e)}function i(e){function t(t,n){var r=o(n),i=r===e;return i}return f(t)}function a(e){function t(e,t){var o=n[t];return o}var n=m(e);return f(t)}function s(e){function t(t,n,r,i,a){var s=o(n),u="object"===s;if(u)for(var c in e){var l=e[c];if(l&&!l(n,c,i,a))return!1}return u}return f(t)}function u(e){function t(t,n){var o=n instanceof e;return o}return f(t)}function c(e){function t(t,n,o,r,i){var a=Array.isArray(n);if(a)for(var s=0;s<n.length;s++)if(!e(n,s,r,i))return!1;return a}return f(t)}function l(){function e(e,t){var o=n(t);return o}return f(e)}function p(){function e(e,t){var n=h.isValidComponent(t);return n}return f(e)}function d(e){return function(t,n,o,r){for(var i=!1,a=0;a<e.length;a++){var s=e[a];if("function"==typeof s.weak&&(s=s.weak),s(t,n,o,r)){i=!0;break}}return i}}function f(e){function t(t,n,o,r,i,a){var s=o[r];if(null!=s)return e(n,s,r,i||g,a);var u=!t;return u}var n=t.bind(null,!1,!0);return n.weak=t.bind(null,!1,!1),n.isRequired=t.bind(null,!0,!0),n.weak.isRequired=t.bind(null,!0,!1),n.isRequired.weak=n.weak.isRequired,n}var h=e("./ReactComponent"),m=(e("./ReactPropTypeLocationNames"),e("./warning"),e("./createObjectFrom")),v={array:i("array"),bool:i("boolean"),func:i("function"),number:i("number"),object:i("object"),string:i("string"),shape:s,oneOf:a,oneOfType:d,arrayOf:c,instanceOf:u,renderable:l(),component:p(),any:r()},g="<<anonymous>>";t.exports=v},{"./ReactComponent":27,"./ReactPropTypeLocationNames":60,"./createObjectFrom":92,"./warning":131}],63:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var o=e("./PooledClass"),r=e("./ReactEventEmitter"),i=e("./mixInto");i(n,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];r.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),o.addPoolingTo(n),t.exports=n},{"./PooledClass":23,"./ReactEventEmitter":46,"./mixInto":122}],64:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=a.getPooled(null),this.putListenerQueue=s.getPooled()}var o=e("./PooledClass"),r=e("./ReactEventEmitter"),i=e("./ReactInputSelection"),a=e("./ReactMountReady"),s=e("./ReactPutListenerQueue"),u=e("./Transaction"),c=e("./mixInto"),l={initialize:i.getSelectionInformation,close:i.restoreSelection},p={initialize:function(){var e=r.isEnabled();return r.setEnabled(!1),e},close:function(e){r.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[f,l,p,d],m={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){a.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(n,u.Mixin),c(n,m),o.addPoolingTo(n),t.exports=n},{"./PooledClass":23,"./ReactEventEmitter":46,"./ReactInputSelection":50,"./ReactMountReady":54,"./ReactPutListenerQueue":63,"./Transaction":83,"./mixInto":122}],65:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:n};t.exports=o},{}],66:[function(e,t){"use strict";function n(e){c(r.isValidComponent(e)),c(!(2===arguments.length&&"function"==typeof arguments[1]));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var o=u(e),r=o.mountComponent(n,t,0);return a.addChecksumToMarkup(r)},null)}finally{s.release(t)}}function o(e){c(r.isValidComponent(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var o=u(e);return o.mountComponent(n,t,0)},null)}finally{s.release(t)}}var r=e("./ReactComponent"),i=e("./ReactInstanceHandles"),a=e("./ReactMarkupChecksum"),s=e("./ReactServerRenderingTransaction"),u=e("./instantiateReactComponent"),c=e("./invariant");t.exports={renderComponentToString:n,renderComponentToStaticMarkup:o}},{"./ReactComponent":27,"./ReactInstanceHandles":51,"./ReactMarkupChecksum":52,"./ReactServerRenderingTransaction":67,"./instantiateReactComponent":109,"./invariant":110}],67:[function(e,t){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=r.getPooled(null),this.putListenerQueue=i.getPooled()}var o=e("./PooledClass"),r=e("./ReactMountReady"),i=e("./ReactPutListenerQueue"),a=e("./Transaction"),s=e("./emptyFunction"),u=e("./mixInto"),c={initialize:function(){this.reactMountReady.reset()},close:s},l={initialize:function(){this.putListenerQueue.reset()},close:s},p=[l,c],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};u(n,a.Mixin),u(n,d),o.addPoolingTo(n),t.exports=n},{"./PooledClass":23,"./ReactMountReady":54,"./ReactPutListenerQueue":63,"./Transaction":83,"./emptyFunction":94,"./mixInto":122}],68:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),o=e("./ReactBrowserComponentMixin"),r=e("./ReactComponent"),i=e("./escapeTextForBrowser"),a=e("./mixInto"),s=function(e){this.construct({text:e})};s.ConvenienceConstructor=function(e){return new s(e.text)},a(s,r.Mixin),a(s,o),a(s,{mountComponent:function(e,t,o){r.Mixin.mountComponent.call(this,e,t,o);var a=i(this.props.text);return t.renderToStaticMarkup?a:"<span "+n.createMarkupForID(e)+">"+a+"</span>"},receiveComponent:function(e){var t=e.props;t.text!==this.props.text&&(this.props.text=t.text,r.BackendIDOperations.updateTextContentByID(this._rootNodeID,t.text))}}),s.type=s,s.prototype.type=s,t.exports=s},{"./DOMPropertyOperations":9,"./ReactBrowserComponentMixin":25,"./ReactComponent":27,"./escapeTextForBrowser":96,"./mixInto":122}],69:[function(e,t){"use strict";function n(){c(p)}function o(e,t){n(),p.batchedUpdates(e,t)}function r(e,t){return e._mountDepth-t._mountDepth}function i(){l.sort(r);for(var e=0;e<l.length;e++){var t=l[e];if(t.isMounted()){var n=t._pendingCallbacks;if(t._pendingCallbacks=null,t.performUpdateIfNecessary(),n)for(var o=0;o<n.length;o++)n[o].call(t)}}}function a(){l.length=0}function s(e,t){return c(!t||"function"==typeof t),n(),p.isBatchingUpdates?(l.push(e),void(t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]))):(e.performUpdateIfNecessary(),void(t&&t.call(e)))}var u=e("./ReactPerf"),c=e("./invariant"),l=[],p=null,d=u.measure("ReactUpdates","flushBatchedUpdates",function(){try{i()}finally{a()}}),f={injectBatchingStrategy:function(e){c(e),c("function"==typeof e.batchedUpdates),c("boolean"==typeof e.isBatchingUpdates),p=e}},h={batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:d,injection:f};t.exports=h},{"./ReactPerf":58,"./invariant":110}],70:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(document.selection){var t=document.selection.createRange();return{parentElement:t.parentElement(),text:t.text,top:t.boundingTop,left:t.boundingLeft}}var n=window.getSelection();return{anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}}function o(e){if(!g&&null!=h&&h==u()){var t=n(h);if(!v||!p(v,t)){v=t;var o=s.getPooled(f.select,m,e);return o.type="select",o.target=h,i.accumulateTwoPhaseDispatches(o),o}}}var r=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ReactInputSelection"),s=e("./SyntheticEvent"),u=e("./getActiveElement"),c=e("./isTextInputElement"),l=e("./keyOf"),p=e("./shallowEqual"),d=r.topLevelTypes,f={select:{phasedRegistrationNames:{bubbled:l({onSelect:null}),captured:l({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},h=null,m=null,v=null,g=!1,C={eventTypes:f,extractEvents:function(e,t,n,r){switch(e){case d.topFocus:(c(t)||"true"===t.contentEditable)&&(h=t,m=n,v=null);break;case d.topBlur:h=null,m=null,v=null;break;case d.topMouseDown:g=!0;break;case d.topContextMenu:case d.topMouseUp:return g=!1,o(r);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return o(r)}}};t.exports=C},{"./EventConstants":14,"./EventPropagators":19,"./ReactInputSelection":50,"./SyntheticEvent":76,"./getActiveElement":100,"./isTextInputElement":113,"./keyOf":117,"./shallowEqual":127}],71:[function(e,t){"use strict";var n=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=o},{}],72:[function(e,t){"use strict";var n=e("./EventConstants"),o=e("./EventPluginUtils"),r=e("./EventPropagators"),i=e("./SyntheticClipboardEvent"),a=e("./SyntheticEvent"),s=e("./SyntheticFocusEvent"),u=e("./SyntheticKeyboardEvent"),c=e("./SyntheticMouseEvent"),l=e("./SyntheticDragEvent"),p=e("./SyntheticTouchEvent"),d=e("./SyntheticUIEvent"),f=e("./SyntheticWheelEvent"),h=e("./invariant"),m=e("./keyOf"),v=n.topLevelTypes,g={blur:{phasedRegistrationNames:{bubbled:m({onBlur:!0}),captured:m({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:m({onClick:!0}),captured:m({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:m({onContextMenu:!0}),captured:m({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:m({onCopy:!0}),captured:m({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:m({onCut:!0}),captured:m({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:m({onDoubleClick:!0}),captured:m({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:m({onDrag:!0}),captured:m({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:m({onDragEnd:!0}),captured:m({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:m({onDragEnter:!0}),captured:m({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:m({onDragExit:!0}),captured:m({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:m({onDragLeave:!0}),captured:m({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:m({onDragOver:!0}),captured:m({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:m({onDragStart:!0}),captured:m({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:m({onDrop:!0}),captured:m({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:m({onFocus:!0}),captured:m({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:m({onInput:!0}),captured:m({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:m({onKeyDown:!0}),captured:m({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:m({onKeyPress:!0}),captured:m({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:m({onKeyUp:!0}),captured:m({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:m({onLoad:!0}),captured:m({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:m({onError:!0}),captured:m({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:m({onMouseDown:!0}),captured:m({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:m({onMouseMove:!0}),captured:m({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:m({onMouseOut:!0}),captured:m({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:m({onMouseOver:!0}),captured:m({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:m({onMouseUp:!0}),captured:m({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:m({onPaste:!0}),captured:m({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:m({onReset:!0}),captured:m({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:m({onScroll:!0}),captured:m({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:m({onSubmit:!0}),captured:m({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:m({onTouchCancel:!0}),captured:m({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:m({onTouchEnd:!0}),captured:m({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:m({onTouchMove:!0}),captured:m({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:m({onTouchStart:!0}),captured:m({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:m({onWheel:!0}),captured:m({onWheelCapture:!0})}}},C={topBlur:g.blur,topClick:g.click,topContextMenu:g.contextMenu,topCopy:g.copy,topCut:g.cut,topDoubleClick:g.doubleClick,topDrag:g.drag,topDragEnd:g.dragEnd,topDragEnter:g.dragEnter,topDragExit:g.dragExit,topDragLeave:g.dragLeave,topDragOver:g.dragOver,topDragStart:g.dragStart,topDrop:g.drop,topError:g.error,topFocus:g.focus,topInput:g.input,topKeyDown:g.keyDown,topKeyPress:g.keyPress,topKeyUp:g.keyUp,topLoad:g.load,topMouseDown:g.mouseDown,topMouseMove:g.mouseMove,topMouseOut:g.mouseOut,topMouseOver:g.mouseOver,topMouseUp:g.mouseUp,topPaste:g.paste,topReset:g.reset,topScroll:g.scroll,topSubmit:g.submit,topTouchCancel:g.touchCancel,topTouchEnd:g.touchEnd,topTouchMove:g.touchMove,topTouchStart:g.touchStart,topWheel:g.wheel};for(var y in C)C[y].dependencies=[y];var E={eventTypes:g,executeDispatch:function(e,t,n){var r=o.executeDispatch(e,t,n);r===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,o){var m=C[e];if(!m)return null;var g;switch(e){case v.topInput:case v.topLoad:case v.topError:case v.topReset:case v.topSubmit:g=a;break;case v.topKeyDown:case v.topKeyPress:case v.topKeyUp:g=u;break;case v.topBlur:case v.topFocus:g=s;break;case v.topClick:if(2===o.button)return null;case v.topContextMenu:case v.topDoubleClick:case v.topMouseDown:case v.topMouseMove:case v.topMouseOut:case v.topMouseOver:case v.topMouseUp:g=c;break;case v.topDrag:case v.topDragEnd:case v.topDragEnter:case v.topDragExit:case v.topDragLeave:case v.topDragOver:case v.topDragStart:case v.topDrop:g=l;break;case v.topTouchCancel:case v.topTouchEnd:case v.topTouchMove:case v.topTouchStart:g=p;break;case v.topScroll:g=d;break;case v.topWheel:g=f;break;case v.topCopy:case v.topCut:case v.topPaste:g=i}h(g);var y=g.getPooled(m,n,o);return r.accumulateTwoPhaseDispatches(y),y}};t.exports=E},{"./EventConstants":14,"./EventPluginUtils":18,"./EventPropagators":19,"./SyntheticClipboardEvent":73,"./SyntheticDragEvent":75,"./SyntheticEvent":76,"./SyntheticFocusEvent":77,"./SyntheticKeyboardEvent":78,"./SyntheticMouseEvent":79,"./SyntheticTouchEvent":80,"./SyntheticUIEvent":81,"./SyntheticWheelEvent":82,"./invariant":110,"./keyOf":117}],73:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticEvent"),r={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(n,r),t.exports=n},{"./SyntheticEvent":76}],74:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticEvent"),r={data:null};o.augmentClass(n,r),t.exports=n},{"./SyntheticEvent":76}],75:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticMouseEvent"),r={dataTransfer:null};o.augmentClass(n,r),t.exports=n},{"./SyntheticMouseEvent":79}],76:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var a=o[i];this[i]=a?a(n):n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?r.thatReturnsTrue:r.thatReturnsFalse,this.isPropagationStopped=r.thatReturnsFalse}var o=e("./PooledClass"),r=e("./emptyFunction"),i=e("./getEventTarget"),a=e("./merge"),s=e("./mergeInto"),u={type:null,target:i,currentTarget:r.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};s(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=r.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=r.thatReturnsTrue},persist:function(){this.isPersistent=r.thatReturnsTrue},isPersistent:r.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=u,n.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);s(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=a(n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.threeArgumentPooler)},o.addPoolingTo(n,o.threeArgumentPooler),t.exports=n},{"./PooledClass":23,"./emptyFunction":94,"./getEventTarget":102,"./merge":119,"./mergeInto":121}],77:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticUIEvent"),r={relatedTarget:null};o.augmentClass(n,r),t.exports=n},{"./SyntheticUIEvent":81}],78:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticUIEvent"),r=e("./getEventKey"),i={key:r,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,"char":null,charCode:null,keyCode:null,which:null};o.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":81,"./getEventKey":101}],79:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticUIEvent"),r=e("./ViewportMetrics"),i={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+r.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+r.currentScrollTop }};o.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":81,"./ViewportMetrics":84}],80:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticUIEvent"),r={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null};o.augmentClass(n,r),t.exports=n},{"./SyntheticUIEvent":81}],81:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticEvent"),r={view:null,detail:null};o.augmentClass(n,r),t.exports=n},{"./SyntheticEvent":76}],82:[function(e,t){"use strict";function n(e,t,n){o.call(this,e,t,n)}var o=e("./SyntheticMouseEvent"),r={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(n,r),t.exports=n},{"./SyntheticMouseEvent":79}],83:[function(e,t){"use strict";var n=e("./invariant"),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this.timingMetrics||(this.timingMetrics={}),this.timingMetrics.methodInvocationTime=0,this.timingMetrics.wrapperInitTimes?this.timingMetrics.wrapperInitTimes.length=0:this.timingMetrics.wrapperInitTimes=[],this.timingMetrics.wrapperCloseTimes?this.timingMetrics.wrapperCloseTimes.length=0:this.timingMetrics.wrapperCloseTimes=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,o,r,i,a,s,u){n(!this.isInTransaction());var c,l,p=Date.now();try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,o,r,i,a,s,u),c=!1}finally{var d=Date.now();this.methodInvocationTime+=d-p;try{if(c)try{this.closeAll(0)}catch(f){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=this.timingMetrics.wrapperInitTimes,o=e;o<t.length;o++){var i=Date.now(),a=t[o];try{this.wrapperInitData[o]=r.OBSERVED_ERROR,this.wrapperInitData[o]=a.initialize?a.initialize.call(this):null}finally{var s=n[o],u=Date.now();if(n[o]=(s||0)+(u-i),this.wrapperInitData[o]===r.OBSERVED_ERROR)try{this.initializeAll(o+1)}catch(c){}}}},closeAll:function(e){n(this.isInTransaction());for(var t=this.transactionWrappers,o=this.timingMetrics.wrapperCloseTimes,i=e;i<t.length;i++){var a,s=t[i],u=Date.now(),c=this.wrapperInitData[i];try{a=!0,c!==r.OBSERVED_ERROR&&s.close&&s.close.call(this,c),a=!1}finally{var l=Date.now(),p=o[i];if(o[i]=(p||0)+(l-u),a)try{this.closeAll(i+1)}catch(d){}}}this.wrapperInitData.length=0}},r={Mixin:o,OBSERVED_ERROR:{}};t.exports=r},{"./invariant":110}],84:[function(e,t){"use strict";var n=e("./getUnboundedScrollPosition"),o={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var e=n(window);o.currentScrollLeft=e.x,o.currentScrollTop=e.y}};t.exports=o},{"./getUnboundedScrollPosition":107}],85:[function(e,t){"use strict";function n(e,t){if(o(null!=t),null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n?e.concat(t):r?[e].concat(t):[e,t]}var o=e("./invariant");t.exports=n},{"./invariant":110}],86:[function(e,t){"use strict";function n(e){for(var t=1,n=0,r=0;r<e.length;r++)t=(t+e.charCodeAt(r))%o,n=(n+t)%o;return t|n<<16}var o=65521;t.exports=n},{}],87:[function(e,t){function n(e,t){return e&&t?e===t?!0:o(e)?!1:o(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var o=e("./isTextNode");t.exports=n},{"./isTextNode":114}],88:[function(e,t){function n(e,t,n,o,r,i){e=e||{};for(var a,s=[t,n,o,r,i],u=0;s[u];){a=s[u++];for(var c in a)e[c]=a[c];a.hasOwnProperty&&a.hasOwnProperty("toString")&&"undefined"!=typeof a.toString&&e.toString!==a.toString&&(e.toString=a.toString)}return e}t.exports=n},{}],89:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return n(e)?Array.isArray(e)?e.slice():r(e):[e]}var r=e("./toArray");t.exports=o},{"./toArray":129}],90:[function(e,t){"use strict";function n(e){var t=o.createClass({displayName:"ReactFullPageComponent"+(e.componentConstructor.displayName||""),componentWillUnmount:function(){r(!1)},render:function(){return this.transferPropsTo(e(null,this.props.children))}});return t}var o=e("./ReactCompositeComponent"),r=e("./invariant");t.exports=n},{"./ReactCompositeComponent":29,"./invariant":110}],91:[function(e,t){function n(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,t){var o=u;s(!!u);var r=n(e),c=r&&a(r);if(c){o.innerHTML=c[1]+e+c[2];for(var l=c[0];l--;)o=o.lastChild}else o.innerHTML=e;var p=o.getElementsByTagName("script");p.length&&(s(t),i(p).forEach(t));for(var d=i(o.childNodes);o.lastChild;)o.removeChild(o.lastChild);return d}var r=e("./ExecutionEnvironment"),i=e("./createArrayFrom"),a=e("./getMarkupWrap"),s=e("./invariant"),u=r.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=o},{"./ExecutionEnvironment":20,"./createArrayFrom":89,"./getMarkupWrap":103,"./invariant":110}],92:[function(e,t){function n(e,t){var n={},o=Array.isArray(t);"undefined"==typeof t&&(t=!0);for(var r=e.length;r--;)n[e[r]]=o?t[r]:t;return n}t.exports=n},{}],93:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||o.isUnitlessNumber[e]?""+t:t+"px"}var o=e("./CSSProperty");t.exports=n},{"./CSSProperty":2}],94:[function(e,t){function n(e){return function(){return e}}function o(){}var r=e("./copyProperties");r(o,{thatReturns:n,thatReturnsFalse:n(!1),thatReturnsTrue:n(!0),thatReturnsNull:n(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(e){return e}}),t.exports=o},{"./copyProperties":88}],95:[function(e,t){"use strict";var n={};t.exports=n},{}],96:[function(e,t){"use strict";function n(e){return r[e]}function o(e){return(""+e).replace(i,n)}var r={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;","/":"&#x2f;"},i=/[&><"'\/]/g;t.exports=o},{}],97:[function(e,t){"use strict";function n(e,t,n){var o=e;r(!o.hasOwnProperty(n)),null!=t&&(o[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,n,t),t}var r=e("./invariant"),i=e("./traverseAllChildren");t.exports=o},{"./invariant":110,"./traverseAllChildren":130}],98:[function(e,t){"use strict";function n(e){e.disabled||e.focus()}t.exports=n},{}],99:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],100:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],101:[function(e,t){"use strict";function n(e){return"key"in e?o[e.key]||e.key:r[e.which||e.keyCode]||"Unidentified"}var o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},r={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"};t.exports=n},{}],102:[function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],103:[function(e,t){function n(e){return r(!!i),p.hasOwnProperty(e)||(e="*"),a.hasOwnProperty(e)||(i.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",a[e]=!i.firstChild),a[e]?p[e]:null}var o=e("./ExecutionEnvironment"),r=e("./invariant"),i=o.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],l=[1,"<svg>","</svg>"],p={"*":[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:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c,circle:l,defs:l,g:l,line:l,linearGradient:l,path:l,polygon:l,polyline:l,radialGradient:l,rect:l,stop:l,text:l};t.exports=n},{"./ExecutionEnvironment":20,"./invariant":110}],104:[function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function r(e,t){for(var r=n(e),i=0,a=0;r;){if(3==r.nodeType){if(a=i+r.textContent.length,t>=i&&a>=t)return{node:r,offset:t-i};i=a}r=n(o(r))}}t.exports=r},{}],105:[function(e,t){"use strict";function n(e){return e?e.nodeType===o?e.documentElement:e.firstChild:null}var o=9;t.exports=n},{}],106:[function(e,t){"use strict";function n(){return!r&&o.canUseDOM&&(r="textContent"in document.createElement("div")?"textContent":"innerText"),r}var o=e("./ExecutionEnvironment"),r=null;t.exports=n},{"./ExecutionEnvironment":20}],107:[function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],108:[function(e,t){function n(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=n},{}],109:[function(e,t){"use strict";function n(e){return e._descriptor=e,e}e("./warning");t.exports=n},{"./warning":131}],110:[function(e,t){"use strict";var n=function(e){if(!e){var t=new Error("Minified exception occured; use the non-minified dev environment for the full error message and additional helpful warnings.");throw t.framesToPop=1,t}};t.exports=n},{}],111:[function(e,t){"use strict";function n(e,t){if(!r.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&o&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var o,r=e("./ExecutionEnvironment");r.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":20}],112:[function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],113:[function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&o[e.type]||"TEXTAREA"===e.nodeName)}var o={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};t.exports=n},{}],114:[function(e,t){function n(e){return o(e)&&3==e.nodeType}var o=e("./isNode");t.exports=n},{"./isNode":112}],115:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var o=1;n>o;o++)t=arguments[o],t&&(e+=" "+t);return e}t.exports=n},{}],116:[function(e,t){"use strict";var n=e("./invariant"),o=function(e){var t,o={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(o[t]=t);return o};t.exports=o},{"./invariant":110}],117:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],118:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)?t[n]:t[n]=e.call(this,n)}}t.exports=n},{}],119:[function(e,t){"use strict";var n=e("./mergeInto"),o=function(e,t){var o={};return n(o,e),n(o,t),o};t.exports=o},{"./mergeInto":121}],120:[function(e,t){"use strict";var n=e("./invariant"),o=e("./keyMirror"),r=36,i=function(e){return"object"!=typeof e||null===e},a={MAX_MERGE_DEPTH:r,isTerminal:i,normalizeMergeArg:function(e){return void 0===e||null===e?{}:e},checkMergeArrayArgs:function(e,t){n(Array.isArray(e)&&Array.isArray(t))},checkMergeObjectArgs:function(e,t){a.checkMergeObjectArg(e),a.checkMergeObjectArg(t)},checkMergeObjectArg:function(e){n(!i(e)&&!Array.isArray(e))},checkMergeLevel:function(e){n(r>e)},checkArrayStrategy:function(e){n(void 0===e||e in a.ArrayStrategies)},ArrayStrategies:o({Clobber:!0,IndexByIndex:!0})};t.exports=a},{"./invariant":110,"./keyMirror":116}],121:[function(e,t){"use strict";function n(e,t){if(r(e),null!=t){r(t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}}var o=e("./mergeHelpers"),r=o.checkMergeObjectArg;t.exports=n},{"./mergeHelpers":120}],122:[function(e,t){"use strict";var n=function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e.prototype[n]=t[n])};t.exports=n},{}],123:[function(e,t){"use strict";function n(e){o(e&&!/[^a-z0-9_]/.test(e))}var o=e("./invariant");t.exports=n},{"./invariant":110}],124:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o=0,r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.call(n,e[i],i,o++));return r}t.exports=n},{}],125:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o=0,r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.call(n,i,e[i],o++));return r}t.exports=n},{}],126:[function(e,t){"use strict";function n(e){return r(o.isValidComponent(e)),e}var o=e("./ReactComponent"),r=e("./invariant");t.exports=n},{"./ReactComponent":27,"./invariant":110}],127:[function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=n},{}],128:[function(e,t){"use strict";function n(e,t){return e&&t&&e.constructor===t.constructor&&(e.props&&e.props.key)===(t.props&&t.props.key)&&e._owner===t._owner?!0:!1}t.exports=n},{}],129:[function(e,t){function n(e){var t=e.length;if(o(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),o("number"==typeof t),o(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=e("./invariant");t.exports=n},{"./invariant":110}],130:[function(e,t){"use strict";function n(e){return d[e]}function o(e,t){return e&&e.props&&null!=e.props.key?i(e.props.key):t.toString(36)}function r(e){return(""+e).replace(f,n)}function i(e){return"$"+r(e)}function a(e,t,n){null!==e&&void 0!==e&&h(e,"",0,t,n)}var s=e("./ReactInstanceHandles"),u=e("./ReactTextComponent"),c=e("./invariant"),l=s.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},f=/[=.:]/g,h=function(e,t,n,r,a){var s=0;if(Array.isArray(e))for(var d=0;d<e.length;d++){var f=e[d],m=t+(t?p:l)+o(f,d),v=n+s;s+=h(f,m,v,r,a)}else{var g=typeof e,C=""===t,y=C?l+o(e,0):t;if(null==e||"boolean"===g)r(a,null,y,n),s=1;else if(e.type&&e.type.prototype&&e.type.prototype.mountComponentIntoNode)r(a,e,y,n),s=1;else if("object"===g){c(!e||1!==e.nodeType);for(var E in e)e.hasOwnProperty(E)&&(s+=h(e[E],t+(t?p:l)+i(E)+p+o(e[E],0),n+s,r,a))}else if("string"===g){var R=new u(e);r(a,R,y,n),s+=1}else if("number"===g){var M=new u(""+e);r(a,M,y,n),s+=1}}return s};t.exports=a},{"./ReactInstanceHandles":51,"./ReactTextComponent":68,"./invariant":110}],131:[function(e,t){"use strict";var n=e("./emptyFunction"),o=n;t.exports=o},{"./emptyFunction":94}]},{},[24])(24)});
src/scripts/pages/NotFound.page.js
ModuloM/kodokojo-ui
/** * Kodo Kojo - Software factory done right * Copyright © 2016 Kodo Kojo (infos@kodokojo.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import { connect } from 'react-redux' // import DocumentMeta from 'react-document-meta' // Component commons import Card from 'kodokojo-ui-commons/src/scripts/components/card/Card.component' import CardContent from 'kodokojo-ui-commons/src/scripts/components/card/CardContent.component' import CardContainer from 'kodokojo-ui-commons/src/scripts/components/card/CardContainer.component' // const metaData = { // title: '404 Page Not Found', // description: 'KodoKojo', // meta: { // charset: 'utf-8', // name: { // keywords: 'test, keyword, other', // } // } // } export class NotFound extends React.Component { static propTypes = { contentFromRoute: React.PropTypes.string.isRequired, status: React.PropTypes.number.isRequired } render() { const { status, contentFromRoute } = this.props return ( <CardContainer> <Card title={ `${status} NotFound` } > <CardContent> <p>{ contentFromRoute }</p> </CardContent> </Card> </CardContainer> ) } } // NotFounPage container const mapStateProps = (state, ownProps) => ( { status: ownProps.route.status, contentFromRoute: ownProps.route.contentFromRoute } ) const NotFoundPage = connect( mapStateProps )(NotFound) export default NotFoundPage
ges-client/src/index.js
martenhz/ges
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route } from 'react-router-dom' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Top from './components/Top'; import Dashboard from './components/Dashboard'; import Categories from './components/Categories'; import Products from './components/Products'; import './index.css'; import injectTapEventPlugin from 'react-tap-event-plugin'; //Needed for onTouchTap //http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); ReactDOM.render( <Router> <MuiThemeProvider> <div> <Top /> <Route exact path="/" component={Dashboard} /> <Route path="/categories" component={Categories} /> <Route path="/products" component={Products} /> </div> </MuiThemeProvider> </Router>, document.getElementById('app') );
test/RowSpec.js
IveWong/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Row from '../src/Row'; describe('Row', function () { it('uses "div" by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Row /> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); }); it('has "row" class', function () { let instance = ReactTestUtils.renderIntoDocument( <Row>Row content</Row> ); assert.equal(React.findDOMNode(instance).className, 'row'); }); it('Should merge additional classes passed in', function () { let instance = ReactTestUtils.renderIntoDocument( <Row className="bob"/> ); assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/)); assert.ok(React.findDOMNode(instance).className.match(/\brow\b/)); }); it('allows custom elements instead of "div"', function () { let instance = ReactTestUtils.renderIntoDocument( <Row componentClass='section' /> ); assert.equal(React.findDOMNode(instance).nodeName, 'SECTION'); }); });
ajax/libs/forerunnerdb/1.3.919/fdb-core.js
tholu/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.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 {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.sortAsc(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.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":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) { 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'); 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 () { 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; }; /** * 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 {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); } // 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]); } 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 (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.deferEmit('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; },{"./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. * @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] !== 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': // 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; },{}],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 (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; },{}],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: '1.3.919', 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]);
ajax/libs/yui/3.10.3/simpleyui/simpleyui.js
ethantw/cdnjs
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { if (Y.config.throwFail) { mod.fn(Y, name); } else { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** The minimum log level to log messages for. Log levels are defined incrementally. Messages greater than or equal to the level specified will be shown. All others will be discarded. The order of log levels in increasing priority is: debug info warn error @property {String} logLevel @default 'debug' @since 3.10.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property {Object|String} delayUntil @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); if (/Mobile|Tablet/.test(ua)) { o.mobile = "ffos"; } } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** Deep object/array copy. Function clones are actually wrappers around the original function. Array-like objects are treated as arrays. Primitives are returned untouched. Optionally, a function can be provided to handle other data types, filter keys, validate values, etc. **Note:** Cloning a non-trivial object is a reasonably heavy operation, due to the need to recursively iterate down non-primitive properties. Clone should be used only when a deep clone down to leaf level properties is explicitly required. This method will also In many cases (for example, when trying to isolate objects used as hashes for configuration properties), a shallow copy, using `Y.merge()` is normally sufficient. If more than one level of isolation is required, `Y.merge()` can be used selectively at each level which needs to be isolated from the original without going all the way to leaf properties. @method clone @param {object} o what to clone. @param {boolean} safe if true, objects will not have prototype items from the source. If false, they will. In this case, the original is initially protected, but the clone is not completely immune from changes to the source object prototype. Also, cloned prototype items that are deleted from the clone will result in the value of the source prototype being exposed. If operating on a non-safe clone, items should be nulled out rather than deleted. @param {function} f optional function to apply to each item in a collection; it will be executed prior to applying the value to the new object. Return false to prevent the copy. @param {object} c optional execution context for f. @param {object} owner Owner object passed when clone is iterating an object. Used to set up context for cloned functions. @param {object} cloned hash of previously cloned objects to avoid multiple clones. @return {Array|Object} the cloned object. **/ Y.clone = function(o, safe, f, c, owner, cloned) { var o2, marked, stamp; // Does not attempt to clone: // // * Non-typeof-object values, "primitive" values don't need cloning. // // * YUI instances, cloning complex object like YUI instances is not // advised, this is like cloning the world. // // * DOM nodes (#2528250), common host objects like DOM nodes cannot be // "subclassed" in Firefox and old versions of IE. Trying to use // `Object.create()` or `Y.extend()` on a DOM node will throw an error in // these browsers. // // Instad, the passed-in `o` will be return as-is when it matches one of the // above criteria. if (!L.isObject(o) || Y.instanceOf(o, YUI) || (o.addEventListener || o.attachEvent)) { return o; } marked = cloned || {}; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } Y.each(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})(\ufffe)?/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})(\ufffe)?/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ KEYWORDS: { 'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff', 'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f', 'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0', 'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff' }, /** NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})(\ufffe)?/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})(\ufffe)?/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** Converts the provided string to the provided type. You can use the `Y.Color.TYPES` to get a valid `to` type. If the color cannot be converted, the original color will be returned. @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { var convert = Y.Color.CONVERTS[to.toLowerCase()], clr = str; if (convert && Y.Color[convert]) { clr = Y.Color[convert](str); } return clr; }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'), isTransparent = clr.toLowerCase() === 'transparent'; if (clr.charAt(0) !== '#' && !isTransparent) { clr = '#' + clr; } return isTransparent ? clr.toLowerCase() : clr.toUpperCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values where the last value is the alpha value. Will return an empty array if the provided string is not able to be parsed. NOTE: `(\ufffe)?` is added to `HEX` and `HEX3` Regular Expressions to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression Y.Color.toArray('fff'); // ['ff', 'ff', 'ff', 1] Y.Color.toArray('rgb(0, 0, 0)'); // ['0', '0', '0', 1] Y.Color.toArray('rgba(0, 0, 0, 0)'); // ['0', '0', '0', 1] @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; if (type === 'HEX3') { arr[0] += arr[0]; arr[1] += arr[1]; arr[2] += arr[2]; } lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { if (clr === 'transparent') { return clr; } var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } } if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr)) { clr = Y.Color.toArray(clr); } clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base", "color-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; this._hasAfters = true; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; this._hasSubs = true; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); if (subs.length === 0) { if (when === AFTER) { this._hasAfters = false; } else { this._hasSubs = false; } } } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, YObject = Y.Object, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { if (!e) { e = EMPTY; } this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret = true, events, subs, ons, afters, afterQueue, postponed, prevented, preventedFn, defaultFn, self = this, host = self.host || self, next, oldbubble, stack, yuievt = host._yuievt, hasPotentialSubscribers; stack = self.stack; if (stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type !== stack.next.type) { self.log('queue ' + self.type); if (!stack.queue) { stack.queue = []; } stack.queue.push([self, args]); return true; } } hasPotentialSubscribers = self.hasSubs() || yuievt.hasTargets || self.broadcast; self.target = self.target || host; self.currentTarget = host; self.details = args.concat(); if (hasPotentialSubscribers) { es = stack || { id: self.id, // id of the first event in the stack next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly }; subs = self.getSubs(); ons = subs[0]; afters = subs[1]; self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; if (self.stoppedFn) { // PERF TODO: Can we replace with callback, like preventedFn. Look into history events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (ons) { self._procSubs(ons, args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type !== self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } prevented = self.prevented; if (prevented) { preventedFn = self.preventedFn; if (preventedFn) { preventedFn.apply(host, args); } } else { defaultFn = self.defaultFn; if (defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { defaultFn.apply(host, args); } } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. if (self.broadcast) { self._broadcast(args); } if (afters && !self.prevented && self.stopped < 2) { // Queue the after afterQueue = es.afterQueue; if (es.id === self.id || self.type !== yuievt.bubbling) { self._procSubs(afters, args, ef); if (afterQueue) { while ((next = afterQueue.last())) { next(); } } } else { postponed = afters; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } if (!afterQueue) { es.afterQueue = new Y.Queue(); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; if (queue) { while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce._fire(q[1]); } } self.stack = null; } ret = !(self.stopped); if (self.type !== yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } } else { defaultFn = self.defaultFn; if(defaultFn) { ef = self._getFacade(args); if ((!self.defaultTargetOnly) || (host === ef.target)) { defaultFn.apply(host, args); } } } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function(fireArgs) { var userArgs = this.details, firstArg = userArgs && userArgs[0], firstArgIsObj = (firstArg && (typeof firstArg === "object")), ef = this._facade; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } if (firstArgIsObj) { // protect the event facade properties mixFacadeProps(ef, firstArg); // Allow the event type to be faked http://yuilibrary.com/projects/yui3/ticket/2528376 if (firstArg.type) { ef.type = firstArg.type; } if (fireArgs) { fireArgs[0] = ef; } } else { if (fireArgs) { fireArgs.unshift(ef); } } // update the details field with the arguments ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { var etState = this._yuievt; if (!etState.targets) { etState.targets = {}; } etState.targets[Y.stamp(o)] = o; etState.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { var targets = this._yuievt.targets; return targets ? YObject.values(targets) : []; }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { var targets = this._yuievt.targets; if (targets) { delete targets[Y.stamp(o, true)]; if (YObject.size(targets) === 0) { this._yuievt.hasTargets = false; } } }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, ce, i, bc, ce2, type = evt && evt.type, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t._yuievt.events[type]; if (t._hasSiblings) { ce2 = t.getSibling(type, ce); } if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { if (ce2) { ce.sibling = ce2; } // set the original target to that the target payload on the facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; // TODO: See what's getting in the way of changing this to use // the more performant ce._fire(args || evt.details || []). // Something in Widget Parent/Child tests is not happy if we // change it - maybe evt.details related? ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist; if (this._node) { nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; } return nodelist || Y.all([]); }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node | null} The last item in the NodeList, or null if the list is empty. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node | null} The first item in the NodeList, or null if the NodeList is empty. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to remove the hidden attribute and reset the CSS style.display property. * @method _show * @protected * @chainable */ _show: function() { this.removeAttribute('hidden'); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getAttribute(this._node, 'hidden') === 'true'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using given named effect. * @method toggleView * @for Node * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to set the hidden attribute to true and set the CSS style.display to 'none'. * @method _hide * @protected * @chainable */ _hide: function() { this.setAttribute('hidden', true); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using given named effect. * @method toggleView * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { name = this.DATA_PREFIX + name; var node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !Y.DOM.isWindow(o)); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, emitFacade:false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { /*jshint maxlen:300*/ } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function (Y, NAME) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ function IEEventFacade() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); } /* * (intentially left out of API docs) * Alternate Facade implementation that is based on Object.defineProperty, which * is partially supported in IE8. Properties that involve setup work are * deferred to temporary getters using the static _define method. */ function IELazyFacade(e) { var proxy = Y.config.doc.createEventObject(e), proto = IELazyFacade.prototype; // TODO: necessary? proxy.hasOwnProperty = function () { return true; }; proxy.init = proto.init; proxy.halt = proto.halt; proxy.preventDefault = proto.preventDefault; proxy.stopPropagation = proto.stopPropagation; proxy.stopImmediatePropagation = proto.stopImmediatePropagation; Y.DOM2EventFacade.apply(proxy, arguments); return proxy; } var imp = Y.config.doc && Y.config.doc.implementation, useLazyFacade = Y.config.lazyEventFacade, buttonMap = { 0: 1, // left click 4: 2, // middle click 2: 3 // right click }, relatedTargetMap = { mouseout: 'toElement', mouseover: 'fromElement' }, resolve = Y.DOM2EventFacade.resolve, proto = { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. this.relatedTarget = resolve(t || e.relatedTarget); // which should contain the unicode key code if this is a key event. // For click events, which is normalized for which mouse button was // clicked. this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; }, stopPropagation: function() { this._event.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }; Y.extend(IEEventFacade, Y.DOM2EventFacade, proto); Y.extend(IELazyFacade, Y.DOM2EventFacade, proto); IELazyFacade.prototype.init = function () { var e = this._event, overrides = this._wrapper.overrides, define = IELazyFacade._define, lazyProperties = IELazyFacade._lazyProperties, prop; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.keyCode = // chained assignment this.charCode = e.keyCode; this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; for (prop in lazyProperties) { if (lazyProperties.hasOwnProperty(prop)) { define(this, prop, lazyProperties[prop]); } } if (this._touch) { this._touch(e, this._currentTarget, this._wrapper); } }; IELazyFacade._lazyProperties = { target: function () { return resolve(this._event.srcElement); }, relatedTarget: function () { var e = this._event, targetProp = relatedTargetMap[e.type] || 'relatedTarget'; // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. return resolve(e[targetProp] || e.relatedTarget); }, currentTarget: function () { return resolve(this._currentTarget); }, wheelDelta: function () { var e = this._event; if (e.type === "mousewheel" || e.type === "DOMMouseScroll") { return (e.detail) ? (e.detail * -1) : // wheelDelta between -80 and 80 result in -1 or 1 Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } }, pageX: function () { var e = this._event, val = e.pageX, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollLeft; docScroll = doc.documentElement.scrollLeft; val = e.clientX + (docScroll || bodyScroll || 0); } return val; }, pageY: function () { var e = this._event, val = e.pageY, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollTop; docScroll = doc.documentElement.scrollTop; val = e.clientY + (docScroll || bodyScroll || 0); } return val; } }; /** * Wrapper function for Object.defineProperty that creates a property whose * value will be calulated only when asked for. After calculating the value, * the getter wll be removed, so it will behave as a normal property beyond that * point. A setter is also assigned so assigning to the property will clear * the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter, * overwriting value 'a'. * * Used only by the DOMEventFacades used by IE8 when the YUI configuration * <code>lazyEventFacade</code> is set to true. * * @method _define * @param o {DOMObject} A DOM object to add the property to * @param prop {String} The name of the new property * @param valueFn {Function} The function that will return the initial, default * value for the property. * @static * @private */ IELazyFacade._define = function (o, prop, valueFn) { function val(v) { var ret = (arguments.length) ? v : valueFn.call(this); delete o[prop]; Object.defineProperty(o, prop, { value: ret, configurable: true, writable: true }); return ret; } Object.defineProperty(o, prop, { get: val, set: val, configurable: true }); }; if (imp && (!imp.hasFeature('Events', '2.0'))) { if (useLazyFacade) { // Make sure we can use the lazy facade logic try { Object.defineProperty(Y.config.doc.createEventObject(), 'z', {}); } catch (e) { useLazyFacade = false; } } Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade; } }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Boolean} True if in region, false if not. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * <dt>credentials</dt> * <dd>Set the value to 'true' to set XHR.withCredentials property to true.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize a map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { if (Y.QueryString && Y.QueryString.stringify) { config.data = data = Y.QueryString.stringify(data); } else { } } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } // Convert falsy values to an empty string. This way IE can't be // rediculous and translate `undefined` to "undefined". data || (data = ''); if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { var _JSON = Y.config.global.JSON; Y.namespace('JSON').parse = function (obj, reviver, space) { return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', DOCUMENT_STYLE = DOCUMENT[DOCUMENT_ELEMENT].style, TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; // One off handling of transform-prefixing. Transition._TRANSFORM = 'transform'; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; // Map transition properties to vendor-specific versions. if ('transition' in DOCUMENT_STYLE && 'transitionProperty' in DOCUMENT_STYLE && 'transitionDuration' in DOCUMENT_STYLE && 'transitionTimingFunction' in DOCUMENT_STYLE && 'transitionDelay' in DOCUMENT_STYLE) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } // Map transform property to vendor-specific versions. // One-off required for cssText injection. if (typeof DOCUMENT_STYLE.transform === 'undefined') { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transform'; if (typeof DOCUMENT_STYLE[property] !== 'undefined') { Transition._TRANSFORM = property; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration !== 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay !== 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[Transition._TRANSFORM]) { config[Transition._TRANSFORM] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function() { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; Y.NodeList.prototype.show = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).show(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback && typeof callback === 'function') { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; Y.NodeList.prototype.hide = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).hide(name, config, callback); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name !== 'string') { // no transition, just toggle on = name; this._toggleView(on, callback); // call original _toggleView in Y.Node return; } if (typeof on === 'function') { // Ignore "on" if used for callback argument. on = undefined; } if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { node = Y.one(node); node.toggleView.apply(node, arguments); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
components/Loading/index.js
SaraVieira/30-30
// @flow import React from 'react'; import style from './style.css'; const Loading = () => ( <div className={style.loading}> <div className={style.loadingBar} /> <div className={style.loadingBar} /> <div className={style.loadingBar} /> <div className={style.loadingBar} /> </div> ); export default Loading;
src/svg-icons/editor/attach-file.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorAttachFile = (props) => ( <SvgIcon {...props}> <path d="M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6h-1.5z"/> </SvgIcon> ); EditorAttachFile = pure(EditorAttachFile); EditorAttachFile.displayName = 'EditorAttachFile'; EditorAttachFile.muiName = 'SvgIcon'; export default EditorAttachFile;
ajax/libs/webshim/1.15.1/dev/shims/moxie/js/moxie-html4.js
steadiest/cdnjs
/** * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill * v1.2.1 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2014-05-14 */ /** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: src/javascript/core/utils/Basic.js /** * Basic.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Basic', [], function() { /** Gets the true type of the built-in object (better version of typeof). @author Angus Croll (http://javascriptweblog.wordpress.com/) @method typeOf @for Utils @static @param {Object} o Object to check. @return {String} Object [[Class]] */ var typeOf = function(o) { var undef; if (o === undef) { return 'undefined'; } else if (o === null) { return 'null'; } else if (o.nodeType) { return 'node'; } // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8 return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); }; /** Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object. */ var extend = function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }; /** Executes the callback function for each item in array/object. If you return false in the callback it will break the loop. @method each @static @param {Object} obj Object to iterate. @param {function} callback Callback function to execute for each item. */ var each = function(obj, callback) { var length, key, i, undef; if (obj) { try { length = obj.length; } catch(ex) { length = undef; } if (length === undef) { // Loop object items for (key in obj) { if (obj.hasOwnProperty(key)) { if (callback(obj[key], key) === false) { return; } } } } else { // Loop array items for (i = 0; i < length; i++) { if (callback(obj[i], i) === false) { return; } } } } }; /** Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean} */ var isEmptyObj = function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }; /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of error */ var inSeries = function(queue, cb) { var i = 0, length = queue.length; if (typeOf(cb) !== 'function') { cb = function() {}; } if (!queue || !queue.length) { cb(); } function callNext(i) { if (typeOf(queue[i]) === 'function') { queue[i](function(error) { /*jshint expr:true */ ++i < length && !error ? callNext(i) : cb(error); }); } } callNext(i); }; /** Recieve an array of functions (usually async) to call in parallel, each function receives a callback as first argument that it should call, when it completes. After everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the process and invoke main callback immediately. @method inParallel @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of erro */ var inParallel = function(queue, cb) { var count = 0, num = queue.length, cbArgs = new Array(num); each(queue, function(fn, i) { fn(function(error) { if (error) { return cb(error); } var args = [].slice.call(arguments); args.shift(); // strip error - undefined or not cbArgs[i] = args; count++; if (count === num) { cbArgs.unshift(null); cb.apply(this, cbArgs); } }); }); }; /** Find an element in array and return it's index if present, otherwise return -1. @method inArray @static @param {Mixed} needle Element to find @param {Array} array @return {Int} Index of the element, or -1 if not found */ var inArray = function(needle, array) { if (array) { if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, needle); } for (var i = 0, length = array.length; i < length; i++) { if (array[i] === needle) { return i; } } } return -1; }; /** Returns elements of first array if they are not present in second. And false - otherwise. @private @method arrayDiff @param {Array} needles @param {Array} array @return {Array|Boolean} */ var arrayDiff = function(needles, array) { var diff = []; if (typeOf(needles) !== 'array') { needles = [needles]; } if (typeOf(array) !== 'array') { array = [array]; } for (var i in needles) { if (inArray(needles[i], array) === -1) { diff.push(needles[i]); } } return diff.length ? diff : false; }; /** Find intersection of two arrays. @private @method arrayIntersect @param {Array} array1 @param {Array} array2 @return {Array} Intersection of two arrays or null if there is none */ var arrayIntersect = function(array1, array2) { var result = []; each(array1, function(item) { if (inArray(item, array2) !== -1) { result.push(item); } }); return result.length ? result : null; }; /** Forces anything into an array. @method toArray @static @param {Object} obj Object with length field. @return {Array} Array object containing all items. */ var toArray = function(obj) { var i, arr = []; for (i = 0; i < obj.length; i++) { arr[i] = obj[i]; } return arr; }; /** Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. It's more probable for the earth to be hit with an ansteriod. Y @method guid @static @param {String} prefix to prepend (by default 'o' will be prepended). @method guid @return {String} Virtually unique id. */ var guid = (function() { var counter = 0; return function(prefix) { var guid = new Date().getTime().toString(32), i; for (i = 0; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'o_') + guid + (counter++).toString(32); }; }()); /** Trims white spaces around the string @method trim @static @param {String} str @return {String} */ var trim = function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }; /** Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes. */ var parseSizeStr = function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }; return { guid: guid, typeOf: typeOf, extend: extend, each: each, isEmptyObj: isEmptyObj, inSeries: inSeries, inParallel: inParallel, inArray: inArray, arrayDiff: arrayDiff, arrayIntersect: arrayIntersect, toArray: toArray, trim: trim, parseSizeStr: parseSizeStr }; }); // Included from: src/javascript/core/I18n.js /** * I18n.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/I18n", [ "moxie/core/utils/Basic" ], function(Basic) { var i18n = {}; return { /** * Extends the language pack object with new items. * * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n: function(pack) { return Basic.extend(i18n, pack); }, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate: function(str) { return i18n[str] || str; }, /** * Shortcut for translate function * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ _: function(str) { return this.translate(str); }, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf: function(str) { var args = [].slice.call(arguments, 1); return str.replace(/%[a-z]/g, function() { var value = args.shift(); return Basic.typeOf(value) !== 'undefined' ? value : ''; }); } }; }); // Included from: src/javascript/core/utils/Mime.js /** * Mime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Mime", [ "moxie/core/utils/Basic", "moxie/core/I18n" ], function(Basic, I18n) { var mimeData = "" + "application/msword,doc dot," + "application/pdf,pdf," + "application/pgp-signature,pgp," + "application/postscript,ps ai eps," + "application/rtf,rtf," + "application/vnd.ms-excel,xls xlb," + "application/vnd.ms-powerpoint,ppt pps pot," + "application/zip,zip," + "application/x-shockwave-flash,swf swfl," + "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," + "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," + "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," + "application/vnd.openxmlformats-officedocument.presentationml.template,potx," + "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," + "application/x-javascript,js," + "application/json,json," + "audio/mpeg,mp3 mpga mpega mp2," + "audio/x-wav,wav," + "audio/x-m4a,m4a," + "audio/ogg,oga ogg," + "audio/aiff,aiff aif," + "audio/flac,flac," + "audio/aac,aac," + "audio/ac3,ac3," + "audio/x-ms-wma,wma," + "image/bmp,bmp," + "image/gif,gif," + "image/jpeg,jpg jpeg jpe," + "image/photoshop,psd," + "image/png,png," + "image/svg+xml,svg svgz," + "image/tiff,tiff tif," + "text/plain,asc txt text diff log," + "text/html,htm html xhtml," + "text/css,css," + "text/csv,csv," + "text/rtf,rtf," + "video/mpeg,mpeg mpg mpe m2v," + "video/quicktime,qt mov," + "video/mp4,mp4," + "video/x-m4v,m4v," + "video/x-flv,flv," + "video/x-ms-wmv,wmv," + "video/avi,avi," + "video/webm,webm," + "video/3gpp,3gpp 3gp," + "video/3gpp2,3g2," + "video/vnd.rn-realvideo,rv," + "video/ogg,ogv," + "video/x-matroska,mkv," + "application/vnd.oasis.opendocument.formula-template,otf," + "application/octet-stream,exe"; var Mime = { mimes: {}, extensions: {}, // Parses the default mime types string into a mimes and extensions lookup maps addMimeType: function (mimeData) { var items = mimeData.split(/,/), i, ii, ext; for (i = 0; i < items.length; i += 2) { ext = items[i + 1].split(/ /); // extension to mime lookup for (ii = 0; ii < ext.length; ii++) { this.mimes[ext[ii]] = items[i]; } // mime to extension lookup this.extensions[items[i]] = ext; } }, extList2mimes: function (filters, addMissingExtensions) { var self = this, ext, i, ii, type, mimes = []; // convert extensions to mime types list for (i = 0; i < filters.length; i++) { ext = filters[i].extensions.split(/\s*,\s*/); for (ii = 0; ii < ext.length; ii++) { // if there's an asterisk in the list, then accept attribute is not required if (ext[ii] === '*') { return []; } type = self.mimes[ext[ii]]; if (!type) { if (addMissingExtensions && /^\w+$/.test(ext[ii])) { mimes.push('.' + ext[ii]); } else { return []; // accept all } } else if (Basic.inArray(type, mimes) === -1) { mimes.push(type); } } } return mimes; }, mimes2exts: function(mimes) { var self = this, exts = []; Basic.each(mimes, function(mime) { if (mime === '*') { exts = []; return false; } // check if this thing looks like mime type var m = mime.match(/^(\w+)\/(\*|\w+)$/); if (m) { if (m[2] === '*') { // wildcard mime type detected Basic.each(self.extensions, function(arr, mime) { if ((new RegExp('^' + m[1] + '/')).test(mime)) { [].push.apply(exts, self.extensions[mime]); } }); } else if (self.extensions[mime]) { [].push.apply(exts, self.extensions[mime]); } } }); return exts; }, mimes2extList: function(mimes) { var accept = [], exts = []; if (Basic.typeOf(mimes) === 'string') { mimes = Basic.trim(mimes).split(/\s*,\s*/); } exts = this.mimes2exts(mimes); accept.push({ title: I18n.translate('Files'), extensions: exts.length ? exts.join(',') : '*' }); // save original mimes string accept.mimes = mimes; return accept; }, getFileExtension: function(fileName) { var matches = fileName && fileName.match(/\.([^.]+)$/); if (matches) { return matches[1].toLowerCase(); } return ''; }, getFileMime: function(fileName) { return this.mimes[this.getFileExtension(fileName)] || ''; } }; Mime.addMimeType(mimeData); return Mime; }); // Included from: src/javascript/core/utils/Env.js /** * Env.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Env", [ "moxie/core/utils/Basic" ], function(Basic) { // UAParser.js v0.6.2 // Lightweight JavaScript-based User-Agent string parser // https://github.com/faisalman/ua-parser-js // // Copyright © 2012-2013 Faisalman <fyzlman@gmail.com> // Dual licensed under GPLv2 & MIT var UAParser = (function (undefined) { ////////////// // Constants ///////////// var EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', MAJOR = 'major', MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE= 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet'; /////////// // Helper ////////// var util = { has : function (str1, str2) { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; }, lowerize : function (str) { return str.toLowerCase(); } }; /////////////// // Map helper ////////////// var mapper = { rgx : function () { // loop through all regexes maps for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) { var regex = args[i], // even sequence (0,2,4,..) props = args[i + 1]; // odd sequence (1,3,5,..) // construct object barebones if (typeof(result) === UNDEF_TYPE) { result = {}; for (p in props) { q = props[p]; if (typeof(q) === OBJ_TYPE) { result[q[0]] = undefined; } else { result[q] = undefined; } } } // try matching uastring with regexes for (j = k = 0; j < regex.length; j++) { matches = regex[j].exec(this.getUA()); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof(q) === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (typeof(q[1]) == FUNC_TYPE) { // assign modified match result[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match result[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex result[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { result[q] = match ? match : undefined; } } break; } } if(!!matches) break; // break the loop immediately if match found } return result; }, str : function (str, map) { for (var i in map) { // check if array if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], str)) { return (i === UNKNOWN) ? undefined : i; } } } else if (util.has(map[i], str)) { return (i === UNKNOWN) ? undefined : i; } } return str; } }; /////////////// // String map ////////////// var maps = { browser : { oldsafari : { major : { '1' : ['/8', '/1', '/3'], '2' : '/4', '?' : '/' }, version : { '1.0' : '/8', '1.2' : '/1', '1.3' : '/3', '2.0' : '/412', '2.0.2' : '/416', '2.0.3' : '/417', '2.0.4' : '/419', '?' : '/' } } }, device : { sprint : { model : { 'Evo Shift 4G' : '7373KT' }, vendor : { 'HTC' : 'APA', 'Sprint' : 'Sprint' } } }, os : { windows : { version : { 'ME' : '4.90', 'NT 3.11' : 'NT3.51', 'NT 4.0' : 'NT4.0', '2000' : 'NT 5.0', 'XP' : ['NT 5.1', 'NT 5.2'], 'Vista' : 'NT 6.0', '7' : 'NT 6.1', '8' : 'NT 6.2', '8.1' : 'NT 6.3', 'RT' : 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser : [[ // Presto based /(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION, MAJOR], [ /\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION, MAJOR], [ // Mixed /(kindle)\/((\d+)?[\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron ], [NAME, VERSION, MAJOR], [ /(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION, MAJOR], [ /(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION, MAJOR], [ /(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION, MAJOR], [ /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION, MAJOR], [ /(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION, MAJOR], [ /((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION, MAJOR], [ /((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser ], [[NAME, 'Android Browser'], VERSION, MAJOR], [ /version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [ /version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, MAJOR, NAME], [ /webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0 ], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [ /(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror /(webkit|khtml)\/((\d+)?[\w\.]+)/i ], [NAME, VERSION, MAJOR], [ // Gecko based /(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION, MAJOR], [ /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i, // UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser /(links)\s\(((\d+)?[\w\.]+)/i, // Links /(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser /(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic ], [NAME, VERSION, MAJOR] ], engine : [[ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]+).*(gecko)/i // Gecko ], [VERSION, NAME] ], os : [[ // Windows based /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [ /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry /(tizen)\/([\w\.]+)/i, // Tizen /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo ], [NAME, VERSION], [ /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian ], [[NAME, 'Symbian'], VERSION],[ /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w+)*/i, // Mint /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux /(gnu)\s?([\w\.]+)*/i // GNU ], [NAME, VERSION], [ /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION],[ // Solaris /(sunos)\s?([\w\.]+\d)*/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION],[ /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [ /(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS ], [NAME, [VERSION, /_/g, '.']], [ // Other /(haiku)\s(\w+)/i, // Haiku /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX /(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS /(unix)\s?([\w\.]+)*/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// var UAParser = function (uastring) { var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); this.getBrowser = function () { return mapper.rgx.apply(this, regexes.browser); }; this.getEngine = function () { return mapper.rgx.apply(this, regexes.engine); }; this.getOS = function () { return mapper.rgx.apply(this, regexes.os); }; this.getResult = function() { return { ua : this.getUA(), browser : this.getBrowser(), engine : this.getEngine(), os : this.getOS() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; return this; }; this.setUA(ua); }; return new UAParser().getResult(); })(); function version_compare(v1, v2, operator) { // From: http://phpjs.org/functions // + original by: Philippe Jausions (http://pear.php.net/user/jausions) // + original by: Aidan Lister (http://aidanlister.com/) // + reimplemented by: Kankrelune (http://www.webfaktory.info/) // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Scott Baker // + improved by: Theriault // * example 1: version_compare('8.2.5rc', '8.2.5a'); // * returns 1: 1 // * example 2: version_compare('8.2.50', '8.2.52', '<'); // * returns 2: true // * example 3: version_compare('5.3.0-dev', '5.3.0'); // * returns 3: -1 // * example 4: version_compare('4.1.0.52','4.01.0.51'); // * returns 4: 1 // Important: compare must be initialized at 0. var i = 0, x = 0, compare = 0, // vm maps textual PHP versions to negatives so they're less than 0. // PHP currently defines these as CASE-SENSITIVE. It is important to // leave these as negatives so that they can come before numerical versions // and as if no letters were there to begin with. // (1alpha is < 1 and < 1.1 but > 1dev1) // If a non-numerical value can't be mapped to this table, it receives // -7 as its value. vm = { 'dev': -6, 'alpha': -5, 'a': -5, 'beta': -4, 'b': -4, 'RC': -3, 'rc': -3, '#': -2, 'p': 1, 'pl': 1 }, // This function will be called to prepare each version argument. // It replaces every _, -, and + with a dot. // It surrounds any nonsequence of numbers/dots with dots. // It replaces sequences of dots with a single dot. // version_compare('4..0', '4.0') == 0 // Important: A string of 0 length needs to be converted into a value // even less than an unexisting value in vm (-7), hence [-8]. // It's also important to not strip spaces because of this. // version_compare('', ' ') == 1 prepVersion = function (v) { v = ('' + v).replace(/[_\-+]/g, '.'); v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.'); return (!v.length ? [-8] : v.split('.')); }, // This converts a version component to a number. // Empty component becomes 0. // Non-numerical component becomes a negative number. // Numerical component becomes itself as an integer. numVersion = function (v) { return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10)); }; v1 = prepVersion(v1); v2 = prepVersion(v2); x = Math.max(v1.length, v2.length); for (i = 0; i < x; i++) { if (v1[i] == v2[i]) { continue; } v1[i] = numVersion(v1[i]); v2[i] = numVersion(v2[i]); if (v1[i] < v2[i]) { compare = -1; break; } else if (v1[i] > v2[i]) { compare = 1; break; } } if (!operator) { return compare; } // Important: operator is CASE-SENSITIVE. // "No operator" seems to be treated as "<." // Any other values seem to make the function return null. switch (operator) { case '>': case 'gt': return (compare > 0); case '>=': case 'ge': return (compare >= 0); case '<=': case 'le': return (compare <= 0); case '==': case '=': case 'eq': return (compare === 0); case '<>': case '!=': case 'ne': return (compare !== 0); case '': case '<': case 'lt': return (compare < 0); default: return null; } } var can = (function() { var caps = { define_property: (function() { /* // currently too much extra code required, not exactly worth it try { // as of IE8, getters/setters are supported only on DOM elements var obj = {}; if (Object.defineProperty) { Object.defineProperty(obj, 'prop', { enumerable: true, configurable: true }); return true; } } catch(ex) {} if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { return true; }*/ return false; }()), create_canvas: (function() { // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ var el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }()), return_response_type: function(responseType) { try { if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) { return true; } else if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); xhr.open('get', '/'); // otherwise Gecko throws an exception if ('responseType' in xhr) { xhr.responseType = responseType; // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?) if (xhr.responseType !== responseType) { return false; } return true; } } } catch (ex) {} return false; }, // ideas for this heavily come from Modernizr (http://modernizr.com/) use_data_uri: (function() { var du = new Image(); du.onload = function() { caps.use_data_uri = (du.width === 1 && du.height === 1); }; setTimeout(function() { du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; }, 1); return false; }()), use_data_uri_over32kb: function() { // IE8 return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9); }, use_data_uri_of: function(bytes) { return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb()); }, use_fileinput: function() { var el = document.createElement('input'); el.setAttribute('type', 'file'); return !el.disabled; } }; return function(cap) { var args = [].slice.call(arguments); args.shift(); // shift of cap return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap]; }; }()); var Env = { can: can, browser: UAParser.browser.name, version: parseFloat(UAParser.browser.major), os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason osVersion: UAParser.os.version, verComp: version_compare, swf_url: "../flash/Moxie.swf", xap_url: "../silverlight/Moxie.xap", global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent" }; // for backward compatibility // @deprecated Use `Env.os` instead Env.OS = Env.os; return Env; }); // Included from: src/javascript/core/utils/Dom.js /** * Dom.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) { /** Get DOM Element by it's id. @method get @for Utils @param {String} id Identifier of the DOM Element @return {DOMElement} */ var get = function(id) { if (typeof id !== 'string') { return id; } return document.getElementById(id); }; /** Checks if specified DOM element has specified class. @method hasClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var hasClass = function(obj, name) { if (!obj.className) { return false; } var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); return regExp.test(obj.className); }; /** Adds specified className to specified DOM element. @method addClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var addClass = function(obj, name) { if (!hasClass(obj, name)) { obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name; } }; /** Removes specified className from specified DOM element. @method removeClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var removeClass = function(obj, name) { if (obj.className) { var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); obj.className = obj.className.replace(regExp, function($0, $1, $2) { return $1 === ' ' && $2 === ' ' ? ' ' : ''; }); } }; /** Returns a given computed style of a DOM element. @method getStyle @static @param {Object} obj DOM element like object. @param {String} name Style you want to get from the DOM element */ var getStyle = function(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[name]; } }; /** Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. @method getPos @static @param {Element} node HTML element or element id to get x, y position from. @param {Element} root Optional root element to stop calculations at. @return {object} Absolute position of the specified element object with x, y fields. */ var getPos = function(node, root) { var x = 0, y = 0, parent, doc = document, nodeRect, rootRect; node = node; root = root || doc.body; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos(node) { var bodyElm, rect, x = 0, y = 0; if (node) { rect = node.getBoundingClientRect(); bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body; x = rect.left + bodyElm.scrollLeft; y = rect.top + bodyElm.scrollTop; } return { x : x, y : y }; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) { nodeRect = getIEPos(node); rootRect = getIEPos(root); return { x : nodeRect.x - rootRect.x, y : nodeRect.y - rootRect.y }; } parent = node; while (parent && parent != root && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } parent = node.parentNode; while (parent && parent != root && parent.nodeType) { x -= parent.scrollLeft || 0; y -= parent.scrollTop || 0; parent = parent.parentNode; } return { x : x, y : y }; }; /** Returns the size of the specified node in pixels. @method getSize @static @param {Node} node Node to get the size of. @return {Object} Object with a w and h property. */ var getSize = function(node) { return { w : node.offsetWidth || node.clientWidth, h : node.offsetHeight || node.clientHeight }; }; return { get: get, hasClass: hasClass, addClass: addClass, removeClass: removeClass, getStyle: getStyle, getPos: getPos, getSize: getSize }; }); // Included from: src/javascript/core/Exceptions.js /** * Exceptions.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/Exceptions', [ 'moxie/core/utils/Basic' ], function(Basic) { function _findKey(obj, value) { var key; for (key in obj) { if (obj[key] === value) { return key; } } return null; } return { RuntimeError: (function() { var namecodes = { NOT_INIT_ERR: 1, NOT_SUPPORTED_ERR: 9, JS_ERR: 4 }; function RuntimeError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": RuntimeError " + this.code; } Basic.extend(RuntimeError, namecodes); RuntimeError.prototype = Error.prototype; return RuntimeError; }()), OperationNotAllowedException: (function() { function OperationNotAllowedException(code) { this.code = code; this.name = 'OperationNotAllowedException'; } Basic.extend(OperationNotAllowedException, { NOT_ALLOWED_ERR: 1 }); OperationNotAllowedException.prototype = Error.prototype; return OperationNotAllowedException; }()), ImageError: (function() { var namecodes = { WRONG_FORMAT: 1, MAX_RESOLUTION_ERR: 2 }; function ImageError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": ImageError " + this.code; } Basic.extend(ImageError, namecodes); ImageError.prototype = Error.prototype; return ImageError; }()), FileException: (function() { var namecodes = { NOT_FOUND_ERR: 1, SECURITY_ERR: 2, ABORT_ERR: 3, NOT_READABLE_ERR: 4, ENCODING_ERR: 5, NO_MODIFICATION_ALLOWED_ERR: 6, INVALID_STATE_ERR: 7, SYNTAX_ERR: 8 }; function FileException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": FileException " + this.code; } Basic.extend(FileException, namecodes); FileException.prototype = Error.prototype; return FileException; }()), DOMException: (function() { var namecodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function DOMException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": DOMException " + this.code; } Basic.extend(DOMException, namecodes); DOMException.prototype = Error.prototype; return DOMException; }()), EventException: (function() { function EventException(code) { this.code = code; this.name = 'EventException'; } Basic.extend(EventException, { UNSPECIFIED_EVENT_TYPE_ERR: 0 }); EventException.prototype = Error.prototype; return EventException; }()) }; }); // Included from: src/javascript/core/EventTarget.js /** * EventTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/EventTarget', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic' ], function(x, Basic) { /** Parent object for all event dispatching components and objects @class EventTarget @constructor EventTarget */ function EventTarget() { // hash of event listeners by object uid var eventpool = {}; Basic.extend(this, { /** Unique id of the event dispatcher, usually overriden by children @property uid @type String */ uid: null, /** Can be called from within a child in order to acquire uniqie id in automated manner @method init */ init: function() { if (!this.uid) { this.uid = Basic.guid('uid_'); } }, /** Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in */ addEventListener: function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }, /** Check if any handlers were registered to the specified event @method hasEventListener @param {String} type Type or basically a name of the event to check @return {Mixed} Returns a handler if it was found and false, if - not */ hasEventListener: function(type) { return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid]; }, /** Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister */ removeEventListener: function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }, /** Remove all event handlers from the object @method removeAllEventListeners */ removeAllEventListeners: function() { if (eventpool[this.uid]) { delete eventpool[this.uid]; } }, /** Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false */ dispatchEvent: function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }, /** Alias for addEventListener @method bind @protected */ bind: function() { this.addEventListener.apply(this, arguments); }, /** Alias for removeEventListener @method unbind @protected */ unbind: function() { this.removeEventListener.apply(this, arguments); }, /** Alias for removeAllEventListeners @method unbindAll @protected */ unbindAll: function() { this.removeAllEventListeners.apply(this, arguments); }, /** Alias for dispatchEvent @method trigger @protected */ trigger: function() { return this.dispatchEvent.apply(this, arguments); }, /** Converts properties of on[event] type to corresponding event handlers, is used to avoid extra hassle around the process of calling them back @method convertEventPropsToHandlers @private */ convertEventPropsToHandlers: function(handlers) { var h; if (Basic.typeOf(handlers) !== 'array') { handlers = [handlers]; } for (var i = 0; i < handlers.length; i++) { h = 'on' + handlers[i]; if (Basic.typeOf(this[h]) === 'function') { this.addEventListener(handlers[i], this[h]); } else if (Basic.typeOf(this[h]) === 'undefined') { this[h] = null; // object must have defined event properties, even if it doesn't make use of them } } } }); } EventTarget.instance = new EventTarget(); return EventTarget; }); // Included from: src/javascript/core/utils/Encode.js /** * Encode.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Encode', [], function() { /** Encode string with UTF-8 @method utf8_encode @for Utils @static @param {String} str String to encode @return {String} UTF-8 encoded string */ var utf8_encode = function(str) { return unescape(encodeURIComponent(str)); }; /** Decode UTF-8 encoded string @method utf8_decode @static @param {String} str String to decode @return {String} Decoded string */ var utf8_decode = function(str_data) { return decodeURIComponent(escape(str_data)); }; /** Decode Base64 encoded string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js @method atob @static @param {String} data String to decode @return {String} Decoded string */ var atob = function(data, utf8) { if (typeof(window.atob) === 'function') { return utf8 ? utf8_decode(window.atob(data)) : window.atob(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window.atob == 'function') { // return atob(data); //} var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return utf8 ? utf8_decode(dec) : dec; }; /** Base64 encode string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js @method btoa @static @param {String} data String to encode @return {String} Base64 encoded string */ var btoa = function(data, utf8) { if (utf8) { utf8_encode(data); } if (typeof(window.btoa) === 'function') { return window.btoa(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Rafał Kukawski (http://kukawski.pl) // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; return { utf8_encode: utf8_encode, utf8_decode: utf8_decode, atob: atob, btoa: btoa }; }); // Included from: src/javascript/runtime/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/Runtime', [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/EventTarget" ], function(Basic, Dom, EventTarget) { var runtimeConstructors = {}, runtimes = {}; /** Common set of methods and properties for every runtime instance @class Runtime @param {Object} options @param {String} type Sanitized name of the runtime @param {Object} [caps] Set of capabilities that differentiate specified runtime @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested */ function Runtime(options, type, caps, modeCaps, preferredMode) { /** Dispatched when runtime is initialized and ready. Results in RuntimeInit on a connected component. @event Init */ /** Dispatched when runtime fails to initialize. Results in RuntimeError on a connected component. @event Error */ var self = this , _shim , _uid = Basic.guid(type + '_') , defaultMode = preferredMode || 'browser' ; options = options || {}; // register runtime in private hash runtimes[_uid] = this; /** Default set of capabilities, which can be redifined later by specific runtime @private @property caps @type Object */ caps = Basic.extend({ // Runtime can: // provide access to raw binary data of the file access_binary: false, // provide access to raw binary data of the image (image extension is optional) access_image_binary: false, // display binary data as thumbs for example display_media: false, // make cross-domain requests do_cors: false, // accept files dragged and dropped from the desktop drag_and_drop: false, // filter files in selection dialog by their extensions filter_by_extension: true, // resize image (and manipulate it raw data of any file in general) resize_image: false, // periodically report how many bytes of total in the file were uploaded (loaded) report_upload_progress: false, // provide access to the headers of http response return_response_headers: false, // support response of specific type, which should be passed as an argument // e.g. runtime.can('return_response_type', 'blob') return_response_type: false, // return http status code of the response return_status_code: true, // send custom http header with the request send_custom_headers: false, // pick up the files from a dialog select_file: false, // select whole folder in file browse dialog select_folder: false, // select multiple files at once in file browse dialog select_multiple: true, // send raw binary data, that is generated after image resizing or manipulation of other kind send_binary_string: false, // send cookies with http request and therefore retain session send_browser_cookies: true, // send data formatted as multipart/form-data send_multipart: true, // slice the file or blob to smaller parts slice_blob: false, // upload file without preloading it to memory, stream it out directly from disk stream_upload: false, // programmatically trigger file browse dialog summon_file_dialog: false, // upload file of specific size, size should be passed as argument // e.g. runtime.can('upload_filesize', '500mb') upload_filesize: true, // initiate http request with specific http method, method should be passed as argument // e.g. runtime.can('use_http_method', 'put') use_http_method: true }, caps); // default to the mode that is compatible with preferred caps if (options.preferred_caps) { defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode); } // small extension factory here (is meant to be extended with actual extensions constructors) _shim = (function() { var objpool = {}; return { exec: function(uid, comp, fn, args) { if (_shim[comp]) { if (!objpool[uid]) { objpool[uid] = { context: this, instance: new _shim[comp]() }; } if (objpool[uid].instance[fn]) { return objpool[uid].instance[fn].apply(this, args); } } }, removeInstance: function(uid) { delete objpool[uid]; }, removeAllInstances: function() { var self = this; Basic.each(objpool, function(obj, uid) { if (Basic.typeOf(obj.instance.destroy) === 'function') { obj.instance.destroy.call(obj.context); } self.removeInstance(uid); }); } }; }()); // public methods Basic.extend(this, { /** Specifies whether runtime instance was initialized or not @property initialized @type {Boolean} @default false */ initialized: false, // shims require this flag to stop initialization retries /** Unique ID of the runtime @property uid @type {String} */ uid: _uid, /** Runtime type (e.g. flash, html5, etc) @property type @type {String} */ type: type, /** Runtime (not native one) may operate in browser or client mode. @property mode @private @type {String|Boolean} current mode or false, if none possible */ mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode), /** id of the DOM container for the runtime (if available) @property shimid @type {String} */ shimid: _uid + '_container', /** Number of connected clients. If equal to zero, runtime can be destroyed @property clients @type {Number} */ clients: 0, /** Runtime initialization options @property options @type {Object} */ options: options, /** Checks if the runtime has specific capability @method can @param {String} cap Name of capability to check @param {Mixed} [value] If passed, capability should somehow correlate to the value @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set) @return {Boolean} true if runtime has such capability and false, if - not */ can: function(cap, value) { var refCaps = arguments[2] || caps; // if cap var is a comma-separated list of caps, convert it to object (key/value) if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') { cap = Runtime.parseCaps(cap); } if (Basic.typeOf(cap) === 'object') { for (var key in cap) { if (!this.can(key, cap[key], refCaps)) { return false; } } return true; } // check the individual cap if (Basic.typeOf(refCaps[cap]) === 'function') { return refCaps[cap].call(this, value); } else { return (value === refCaps[cap]); } }, /** Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement} */ getShimContainer: function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }, /** Returns runtime as DOM element (if appropriate) @method getShim @return {DOMElement} */ getShim: function() { return _shim; }, /** Invokes a method within the runtime itself (might differ across the runtimes) @method shimExec @param {Mixed} [] @protected @return {Mixed} Depends on the action and component */ shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return self.getShim().exec.call(this, this.uid, component, action, args); }, /** Operaional interface that is used by components to invoke specific actions on the runtime (is invoked in the scope of component) @method exec @param {Mixed} []* @protected @return {Mixed} Depends on the action and component */ exec: function(component, action) { // this is called in the context of component, not runtime var args = [].slice.call(arguments, 2); if (self[component] && self[component][action]) { return self[component][action].apply(this, args); } return self.shimExec.apply(this, arguments); }, /** Destroys the runtime (removes all events and deletes DOM structures) @method destroy */ destroy: function() { if (!self) { return; // obviously already destroyed } var shimContainer = Dom.get(this.shimid); if (shimContainer) { shimContainer.parentNode.removeChild(shimContainer); } if (_shim) { _shim.removeAllInstances(); } this.unbindAll(); delete runtimes[this.uid]; this.uid = null; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null; } }); // once we got the mode, test against all caps if (this.mode && options.required_caps && !this.can(options.required_caps)) { this.mode = false; } } /** Default order to try different runtime types @property order @type String @static */ Runtime.order = 'html5,flash,silverlight,html4'; /** Retrieves runtime from private hash by it's uid @method getRuntime @private @static @param {String} uid Unique identifier of the runtime @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not */ Runtime.getRuntime = function(uid) { return runtimes[uid] ? runtimes[uid] : false; }; /** Register constructor for the Runtime of new (or perhaps modified) type @method addConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {Function} construct Constructor for the Runtime type */ Runtime.addConstructor = function(type, constructor) { constructor.prototype = EventTarget.instance; runtimeConstructors[type] = constructor; }; /** Get the constructor for the specified type. method getConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @return {Function} Constructor for the Runtime type */ Runtime.getConstructor = function(type) { return runtimeConstructors[type] || null; }; /** Get info about the runtime (uid, type, capabilities) @method getInfo @static @param {String} uid Unique identifier of the runtime @return {Mixed} Info object or null if runtime doesn't exist */ Runtime.getInfo = function(uid) { var runtime = Runtime.getRuntime(uid); if (runtime) { return { uid: runtime.uid, type: runtime.type, mode: runtime.mode, can: function() { return runtime.can.apply(runtime, arguments); } }; } return null; }; /** Convert caps represented by a comma-separated string to the object representation. @method parseCaps @static @param {String} capStr Comma-separated list of capabilities @return {Object} */ Runtime.parseCaps = function(capStr) { var capObj = {}; if (Basic.typeOf(capStr) !== 'string') { return capStr || {}; } Basic.each(capStr.split(','), function(key) { capObj[key] = true; // we assume it to be - true }); return capObj; }; /** Test the specified runtime for specific capabilities. @method can @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {String|Object} caps Set of capabilities to check @return {Boolean} Result of the test */ Runtime.can = function(type, caps) { var runtime , constructor = Runtime.getConstructor(type) , mode ; if (constructor) { runtime = new constructor({ required_caps: caps }); mode = runtime.mode; runtime.destroy(); return !!mode; } return false; }; /** Figure out a runtime that supports specified capabilities. @method thatCan @static @param {String|Object} caps Set of capabilities to check @param {String} [runtimeOrder] Comma-separated list of runtimes to check against @return {String} Usable runtime identifier or null */ Runtime.thatCan = function(caps, runtimeOrder) { var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/); for (var i in types) { if (Runtime.can(types[i], caps)) { return types[i]; } } return null; }; /** Figure out an operational mode for the specified set of capabilities. @method getMode @static @param {Object} modeCaps Set of capabilities that depend on particular runtime mode @param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for @param {String|Boolean} [defaultMode='browser'] Default mode to use @return {String|Boolean} Compatible operational mode */ Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) { var mode = null; if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified defaultMode = 'browser'; } if (requiredCaps && !Basic.isEmptyObj(modeCaps)) { // loop over required caps and check if they do require the same mode Basic.each(requiredCaps, function(value, cap) { if (modeCaps.hasOwnProperty(cap)) { var capMode = modeCaps[cap](value); // make sure we always have an array if (typeof(capMode) === 'string') { capMode = [capMode]; } if (!mode) { mode = capMode; } else if (!(mode = Basic.arrayIntersect(mode, capMode))) { // if cap requires conflicting mode - runtime cannot fulfill required caps return (mode = false); } } }); if (mode) { return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0]; } else if (mode === false) { return false; } } return defaultMode; }; /** Capability check that always returns true @private @static @return {True} */ Runtime.capTrue = function() { return true; }; /** Capability check that always returns false @private @static @return {False} */ Runtime.capFalse = function() { return false; }; /** Evaluate the expression to boolean value and create a function that always returns it. @private @static @param {Mixed} expr Expression to evaluate @return {Function} Function returning the result of evaluation */ Runtime.capTest = function(expr) { return function() { return !!expr; }; }; return Runtime; }); // Included from: src/javascript/runtime/RuntimeClient.js /** * RuntimeClient.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeClient', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/runtime/Runtime' ], function(x, Basic, Runtime) { /** Set of methods and properties, required by a component to acquire ability to connect to a runtime @class RuntimeClient */ return function RuntimeClient() { var runtime; Basic.extend(this, { /** Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one. Increments number of clients connected to the specified runtime. @method connectRuntime @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites */ connectRuntime: function(options) { var comp = this, ruid; function initialize(items) { var type, constructor; // if we ran out of runtimes if (!items.length) { comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); runtime = null; return; } type = items.shift(); constructor = Runtime.getConstructor(type); if (!constructor) { initialize(items); return; } // try initializing the runtime runtime = new constructor(options); runtime.bind('Init', function() { // mark runtime as initialized runtime.initialized = true; // jailbreak ... setTimeout(function() { runtime.clients++; // this will be triggered on component comp.trigger('RuntimeInit', runtime); }, 1); }); runtime.bind('Error', function() { runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here initialize(items); }); /*runtime.bind('Exception', function() { });*/ // check if runtime managed to pick-up operational mode if (!runtime.mode) { runtime.trigger('Error'); return; } runtime.init(); } // check if a particular runtime was requested if (Basic.typeOf(options) === 'string') { ruid = options; } else if (Basic.typeOf(options.ruid) === 'string') { ruid = options.ruid; } if (ruid) { runtime = Runtime.getRuntime(ruid); if (runtime) { runtime.clients++; return runtime; } else { // there should be a runtime and there's none - weird case throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR); } } // initialize a fresh one, that fits runtime list and required features best initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/)); }, /** Returns the runtime to which the client is currently connected. @method getRuntime @return {Runtime} Runtime or null if client is not connected */ getRuntime: function() { if (runtime && runtime.uid) { return runtime; } runtime = null; // make sure we do not leave zombies rambling around return null; }, /** Disconnects from the runtime. Decrements number of clients connected to the specified runtime. @method disconnectRuntime */ disconnectRuntime: function() { if (runtime && --runtime.clients <= 0) { runtime.destroy(); runtime = null; } } }); }; }); // Included from: src/javascript/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/Blob', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/runtime/RuntimeClient' ], function(Basic, Encode, RuntimeClient) { var blobpool = {}; /** @class Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} blob Object "Native" blob object, as it is represented in the runtime */ function Blob(ruid, blob) { function _sliceDetached(start, end, type) { var blob, data = blobpool[this.uid]; if (Basic.typeOf(data) !== 'string' || !data.length) { return null; // or throw exception } blob = new Blob(null, { type: type, size: end - start }); blob.detach(data.substr(start, blob.size)); return blob; } RuntimeClient.call(this); if (ruid) { this.connectRuntime(ruid); } if (!blob) { blob = {}; } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string blob = { data: blob }; } Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: blob.uid || Basic.guid('uid_'), /** Unique id of the connected runtime, if falsy, then runtime will have to be initialized before this Blob can be used, modified or sent @property ruid @type {String} */ ruid: ruid, /** Size of blob @property size @type {Number} @default 0 */ size: blob.size || 0, /** Mime type of blob @property type @type {String} @default '' */ type: blob.type || '', /** @method slice @param {Number} [start=0] */ slice: function(start, end, type) { if (this.isDetached()) { return _sliceDetached.apply(this, arguments); } return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type); }, /** Returns "native" blob object (as it is represented in connected runtime) or null if not found @method getSource @return {Blob} Returns "native" blob object or null if not found */ getSource: function() { if (!blobpool[this.uid]) { return null; } return blobpool[this.uid]; }, /** Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value */ detach: function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy'); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }, /** Checks if blob is standalone (detached of any runtime) @method isDetached @protected @return {Boolean} */ isDetached: function() { return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string'; }, /** Destroy Blob and free any resources it was using @method destroy */ destroy: function() { this.detach(); delete blobpool[this.uid]; } }); if (blob.data) { this.detach(blob.data); // auto-detach if payload has been passed } else { blobpool[this.uid] = blob; } } return Blob; }); // Included from: src/javascript/file/File.js /** * File.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/File', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/file/Blob' ], function(Basic, Mime, Blob) { /** @class File @extends Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} file Object "Native" file object, as it is represented in the runtime */ function File(ruid, file) { var name, type; if (!file) { // avoid extra errors in case we overlooked something file = {}; } // figure out the type if (file.type && file.type !== '') { type = file.type; } else { type = Mime.getFileMime(file.name); } // sanitize file name or generate new one if (file.name) { name = file.name.replace(/\\/g, '/'); name = name.substr(name.lastIndexOf('/') + 1); } else { var prefix = type.split('/')[0]; name = Basic.guid((prefix !== '' ? prefix : 'file') + '_'); if (Mime.extensions[type]) { name += '.' + Mime.extensions[type][0]; // append proper extension if possible } } Blob.apply(this, arguments); Basic.extend(this, { /** File mime type @property type @type {String} @default '' */ type: type || '', /** File name @property name @type {String} @default UID */ name: name || Basic.guid('file_'), /** Relative path to the file inside a directory @property relativePath @type {String} @default '' */ relativePath: '', /** Date of last modification @property lastModifiedDate @type {String} @default now */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) }); } File.prototype = Blob.prototype; return File; }); // Included from: src/javascript/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileInput', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/core/I18n', 'moxie/file/File', 'moxie/runtime/Runtime', 'moxie/runtime/RuntimeClient' ], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) { /** Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click, converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @class FileInput @constructor @extends EventTarget @uses RuntimeClient @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker. @param {Array} [options.accept] Array of mime types to accept. By default accepts all. @param {String} [options.file='file'] Name of the file field (not the filename). @param {Boolean} [options.multiple=false] Enable selection of multiple files. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time). @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode for _browse\_button_. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support. @example <div id="container"> <a id="file-picker" href="javascript:;">Browse...</a> </div> <script> var fileInput = new mOxie.FileInput({ browse_button: 'file-picker', // or document.getElementById('file-picker') container: 'container', accept: [ {title: "Image files", extensions: "jpg,gif,png"} // accept only images ], multiple: true // allow multiple file selection }); fileInput.onchange = function(e) { // do something to files array console.info(e.target.files); // or this.files or fileInput.files }; fileInput.init(); // initialize </script> */ var dispatches = [ /** Dispatched when runtime is connected and file-picker is ready to be used. @event ready @param {Object} event */ 'ready', /** Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. Check [corresponding documentation entry](#method_refresh) for more info. @event refresh @param {Object} event */ /** Dispatched when selection of files in the dialog is complete. @event change @param {Object} event */ 'change', 'cancel', // TODO: might be useful /** Dispatched when mouse cursor enters file-picker area. Can be used to style element accordingly. @event mouseenter @param {Object} event */ 'mouseenter', /** Dispatched when mouse cursor leaves file-picker area. Can be used to style element accordingly. @event mouseleave @param {Object} event */ 'mouseleave', /** Dispatched when functional mouse button is pressed on top of file-picker area. @event mousedown @param {Object} event */ 'mousedown', /** Dispatched when functional mouse button is released on top of file-picker area. @event mouseup @param {Object} event */ 'mouseup' ]; function FileInput(options) { var self = this, container, browseButton, defaults; // if flat argument passed it should be browse_button id if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) { options = { browse_button : options }; } // this will help us to find proper default container browseButton = Dom.get(options.browse_button); if (!browseButton) { // browse button is required throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], name: 'file', multiple: false, required_caps: false, container: browseButton.parentNode || document.body }; options = Basic.extend({}, defaults, options); // convert to object representation if (typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } container = Dom.get(options.container); // make sure we have container if (!container) { container = document.body; } // make container relative, if it's not if (Dom.getStyle(container, 'position') === 'static') { container.style.position = 'relative'; } container = browseButton = null; // IE RuntimeClient.call(self); Basic.extend(self, { /** Unique id of the component @property uid @protected @readOnly @type {String} @default UID */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @protected @type {String} */ ruid: null, /** Unique id of the runtime container. Useful to get hold of it for various manipulations. @property shimid @protected @type {String} */ shimid: null, /** Array of selected mOxie.File objects @property files @type {Array} @default null */ files: null, /** Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init */ init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }, /** Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false */ disable: function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }, /** Reposition and resize dialog trigger to match the position and size of browse_button element. @method refresh */ refresh: function() { self.trigger("Refresh"); }, /** Destroy component. @method destroy */ destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; } }); } FileInput.prototype = EventTarget.instance; return FileInput; }); // Included from: src/javascript/runtime/RuntimeTarget.js /** * RuntimeTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeTarget', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', "moxie/core/EventTarget" ], function(Basic, RuntimeClient, EventTarget) { /** Instance of this class can be used as a target for the events dispatched by shims, when allowing them onto components is for either reason inappropriate @class RuntimeTarget @constructor @protected @extends EventTarget */ function RuntimeTarget() { this.uid = Basic.guid('uid_'); RuntimeClient.call(this); this.destroy = function() { this.disconnectRuntime(); this.unbindAll(); }; } RuntimeTarget.prototype = EventTarget.instance; return RuntimeTarget; }); // Included from: src/javascript/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReader', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/file/Blob', 'moxie/file/File', 'moxie/runtime/RuntimeTarget' ], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) { /** Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader) interface. Where possible uses native FileReader, where - not falls back to shims. @class FileReader @constructor FileReader @extends EventTarget @uses RuntimeClient */ var dispatches = [ /** Dispatched when the read starts. @event loadstart @param {Object} event */ 'loadstart', /** Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total). @event progress @param {Object} event */ 'progress', /** Dispatched when the read has successfully completed. @event load @param {Object} event */ 'load', /** Dispatched when the read has been aborted. For instance, by invoking the abort() method. @event abort @param {Object} event */ 'abort', /** Dispatched when the read has failed. @event error @param {Object} event */ 'error', /** Dispatched when the request has completed (either in success or failure). @event loadend @param {Object} event */ 'loadend' ]; function FileReader() { var self = this, _fr; Basic.extend(this, { /** UID of the component instance. @property uid @type {String} */ uid: Basic.guid('uid_'), /** Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING and FileReader.DONE. @property readyState @type {Number} @default FileReader.EMPTY */ readyState: FileReader.EMPTY, /** Result of the successful read operation. @property result @type {String} */ result: null, /** Stores the error of failed asynchronous read operation. @property error @type {DOMError} */ error: null, /** Initiates reading of File/Blob object contents to binary string. @method readAsBinaryString @param {Blob|File} blob Object to preload */ readAsBinaryString: function(blob) { _read.call(this, 'readAsBinaryString', blob); }, /** Initiates reading of File/Blob object contents to dataURL string. @method readAsDataURL @param {Blob|File} blob Object to preload */ readAsDataURL: function(blob) { _read.call(this, 'readAsDataURL', blob); }, /** Initiates reading of File/Blob object contents to string. @method readAsText @param {Blob|File} blob Object to preload */ readAsText: function(blob) { _read.call(this, 'readAsText', blob); }, /** Aborts preloading process. @method abort */ abort: function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }, /** Destroy component and release resources. @method destroy */ destroy: function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; } }); function _read(op, blob) { _fr = new RuntimeTarget(); function error(err) { self.readyState = FileReader.DONE; self.error = err; self.trigger('error'); loadEnd(); } function loadEnd() { _fr.destroy(); _fr = null; self.trigger('loadend'); } function exec(runtime) { _fr.bind('Error', function(e, err) { error(err); }); _fr.bind('Progress', function(e) { self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); }); _fr.bind('Load', function(e) { self.readyState = FileReader.DONE; self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); loadEnd(); }); runtime.exec.call(_fr, 'FileReader', 'read', op, blob); } this.convertEventPropsToHandlers(dispatches); if (this.readyState === FileReader.LOADING) { return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR)); } this.readyState = FileReader.LOADING; this.trigger('loadstart'); // if source is o.Blob/o.File if (blob instanceof Blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsText': case 'readAsBinaryString': this.result = src; break; case 'readAsDataURL': this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src); break; } this.readyState = FileReader.DONE; this.trigger('load'); loadEnd(); } else { exec(_fr.connectRuntime(blob.ruid)); } } else { error(new x.DOMException(x.DOMException.NOT_FOUND_ERR)); } } } /** Initial FileReader state @property EMPTY @type {Number} @final @static @default 0 */ FileReader.EMPTY = 0; /** FileReader switches to this state when it is preloading the source @property LOADING @type {Number} @final @static @default 1 */ FileReader.LOADING = 1; /** Preloading is complete, this is a final state @property DONE @type {Number} @final @static @default 2 */ FileReader.DONE = 2; FileReader.prototype = EventTarget.instance; return FileReader; }); // Included from: src/javascript/core/utils/Url.js /** * Url.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Url', [], function() { /** Parse url into separate components and fill in absent parts with parts from current url, based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js @method parseUrl @for Utils @static @param {String} url Url to parse (defaults to empty string if undefined) @return {Object} Hash containing extracted uri components */ var parseUrl = function(url, currentUrl) { var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'] , i = key.length , ports = { http: 80, https: 443 } , uri = {} , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/ , m = regex.exec(url || '') ; while (i--) { if (m[i]) { uri[key[i]] = m[i]; } } // when url is relative, we set the origin and the path ourselves if (!uri.scheme) { // come up with defaults if (!currentUrl || typeof(currentUrl) === 'string') { currentUrl = parseUrl(currentUrl || document.location.href); } uri.scheme = currentUrl.scheme; uri.host = currentUrl.host; uri.port = currentUrl.port; var path = ''; // for urls without trailing slash we need to figure out the path if (/^[^\/]/.test(uri.path)) { path = currentUrl.path; // if path ends with a filename, strip it if (!/(\/|\/[^\.]+)$/.test(path)) { path = path.replace(/\/[^\/]+$/, '/'); } else { path += '/'; } } uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir } if (!uri.port) { uri.port = ports[uri.scheme] || 80; } uri.port = parseInt(uri.port, 10); if (!uri.path) { uri.path = "/"; } delete uri.source; return uri; }; /** Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url */ var resolveUrl = function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }; /** Check if specified url has the same origin as the current document @method hasSameOrigin @param {String|Object} url @return {Boolean} */ var hasSameOrigin = function(url) { function origin(url) { return [url.scheme, url.host, url.port].join('/'); } if (typeof url === 'string') { url = parseUrl(url); } return origin(parseUrl()) === origin(url); }; return { parseUrl: parseUrl, resolveUrl: resolveUrl, hasSameOrigin: hasSameOrigin }; }); // Included from: src/javascript/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReaderSync', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', 'moxie/core/utils/Encode' ], function(Basic, RuntimeClient, Encode) { /** Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be, but probably < 1mb). Not meant to be used directly by user. @class FileReaderSync @private @constructor */ return function() { RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), readAsBinaryString: function(blob) { return _read.call(this, 'readAsBinaryString', blob); }, readAsDataURL: function(blob) { return _read.call(this, 'readAsDataURL', blob); }, /*readAsArrayBuffer: function(blob) { return _read.call(this, 'readAsArrayBuffer', blob); },*/ readAsText: function(blob) { return _read.call(this, 'readAsText', blob); } }); function _read(op, blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsBinaryString': return src; case 'readAsDataURL': return 'data:' + blob.type + ';base64,' + Encode.btoa(src); case 'readAsText': var txt = ''; for (var i = 0, length = src.length; i < length; i++) { txt += String.fromCharCode(src[i]); } return txt; } } else { var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob); this.disconnectRuntime(); return result; } } }; }); // Included from: src/javascript/xhr/FormData.js /** * FormData.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/FormData", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/file/Blob" ], function(x, Basic, Blob) { /** FormData @class FormData @constructor */ function FormData() { var _blob, _fields = []; Basic.extend(this, { /** Append another key-value pair to the FormData object @method append @param {String} name Name for the new field @param {String|Blob|Array|Object} value Value for the field */ append: function(name, value) { var self = this, valueType = Basic.typeOf(value); // according to specs value might be either Blob or String if (value instanceof Blob) { _blob = { name: name, value: value // unfortunately we can only send single Blob in one FormData }; } else if ('array' === valueType) { name += '[]'; Basic.each(value, function(value) { self.append(name, value); }); } else if ('object' === valueType) { Basic.each(value, function(value, key) { self.append(name + '[' + key + ']', value); }); } else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) { self.append(name, "false"); } else { _fields.push({ name: name, value: value.toString() }); } }, /** Checks if FormData contains Blob. @method hasBlob @return {Boolean} */ hasBlob: function() { return !!this.getBlob(); }, /** Retrieves blob. @method getBlob @return {Object} Either Blob if found or null */ getBlob: function() { return _blob && _blob.value || null; }, /** Retrieves blob field name. @method getBlobName @return {String} Either Blob field name or null */ getBlobName: function() { return _blob && _blob.name || null; }, /** Loop over the fields in FormData and invoke the callback for each of them. @method each @param {Function} cb Callback to call for each field */ each: function(cb) { Basic.each(_fields, function(field) { cb(field.value, field.name); }); if (_blob) { cb(_blob.value, _blob.name); } }, destroy: function() { _blob = null; _fields = []; } }); } return FormData; }); // Included from: src/javascript/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/XMLHttpRequest", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/EventTarget", "moxie/core/utils/Encode", "moxie/core/utils/Url", "moxie/runtime/Runtime", "moxie/runtime/RuntimeTarget", "moxie/file/Blob", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/core/utils/Env", "moxie/core/utils/Mime" ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) { var httpCode = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Reserved', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 510: 'Not Extended' }; function XMLHttpRequestUpload() { this.uid = Basic.guid('uid_'); } XMLHttpRequestUpload.prototype = EventTarget.instance; /** Implementation of XMLHttpRequest @class XMLHttpRequest @constructor @uses RuntimeClient @extends EventTarget */ var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons) var NATIVE = 1, RUNTIME = 2; function XMLHttpRequest() { var self = this, // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible props = { /** The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout. @property timeout @type Number @default 0 */ timeout: 0, /** Current state, can take following values: UNSENT (numeric value 0) The object has been constructed. OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method. HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING (numeric value 3) The response entity body is being received. DONE (numeric value 4) @property readyState @type Number @default 0 (UNSENT) */ readyState: XMLHttpRequest.UNSENT, /** True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. @property withCredentials @type Boolean @default false */ withCredentials: false, /** Returns the HTTP status code. @property status @type Number @default 0 */ status: 0, /** Returns the HTTP status text. @property statusText @type String */ statusText: "", /** Returns the response type. Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". @property responseType @type String */ responseType: "", /** Returns the document response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "document". @property responseXML @type Document */ responseXML: null, /** Returns the text response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "text". @property responseText @type String */ responseText: null, /** Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body). Can become: ArrayBuffer, Blob, Document, JSON, Text @property response @type Mixed */ response: null }, _async = true, _url, _method, _headers = {}, _user, _password, _encoding = null, _mimeType = null, // flags _sync_flag = false, _send_flag = false, _upload_events_flag = false, _upload_complete_flag = false, _error_flag = false, _same_origin_flag = false, // times _start_time, _timeoutset_time, _finalMime = null, _finalCharset = null, _options = {}, _xhr, _responseHeaders = '', _responseHeadersBag ; Basic.extend(this, props, { /** Unique id of the component @property uid @type String */ uid: Basic.guid('uid_'), /** Target for Upload events @property upload @type XMLHttpRequestUpload */ upload: new XMLHttpRequestUpload(), /** Sets the request method, request URL, synchronous flag, request username, and request password. Throws a "SyntaxError" exception if one of the following is true: method is not a valid HTTP method. url cannot be resolved. url contains the "user:password" format in the userinfo production. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK. Throws an "InvalidAccessError" exception if one of the following is true: Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. There is an associated XMLHttpRequest document and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. @method open @param {String} method HTTP method to use on request @param {String} url URL to request @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default. @param {String} [user] Username to use in HTTP authentication process on server-side @param {String} [password] Password to use in HTTP authentication process on server-side */ open: function(method, url, async, user, password) { var urlp; // first two arguments are required if (!method || !url) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3 if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) { _method = method.toUpperCase(); } // 4 - allowing these methods poses a security risk if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) { throw new x.DOMException(x.DOMException.SECURITY_ERR); } // 5 url = Encode.utf8_encode(url); // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError". urlp = Url.parseUrl(url); _same_origin_flag = Url.hasSameOrigin(urlp); // 7 - manually build up absolute url _url = Url.resolveUrl(url); // 9-10, 12-13 if ((user || password) && !_same_origin_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } _user = user || urlp.user; _password = password || urlp.pass; // 11 _async = async || true; if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = !_async; _send_flag = false; _headers = {}; _reset.call(this); // 19 _p('readyState', XMLHttpRequest.OPENED); // 20 this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers this.dispatchEvent('readystatechange'); }, /** Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value. @method setRequestHeader @param {String} header @param {String|Number} value */ setRequestHeader: function(header, value) { var uaHeaders = [ // these headers are controlled by the user agent "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; // 1-2 if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); }*/ header = Basic.trim(header).toLowerCase(); // setting of proxy-* and sec-* headers is prohibited by spec if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) { return false; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); }); if (!_headers[header]) { _headers[header] = value; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers[header] += ', ' + value; } return true; }, /** Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2. @method getAllResponseHeaders @return {String} reponse headers or empty string */ getAllResponseHeaders: function() { return _responseHeaders || ''; }, /** Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2. @method getResponseHeader @param {String} header @return {String} value(s) for the specified header or null */ getResponseHeader: function(header) { header = header.toLowerCase(); if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) { return null; } if (_responseHeaders && _responseHeaders !== '') { // if we didn't parse response headers until now, do it and keep for later if (!_responseHeadersBag) { _responseHeadersBag = {}; Basic.each(_responseHeaders.split(/\r\n/), function(line) { var pair = line.split(/:\s+/); if (pair.length === 2) { // last line might be empty, omit pair[0] = Basic.trim(pair[0]); // just in case _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form header: pair[0], value: Basic.trim(pair[1]) }; } }); } if (_responseHeadersBag.hasOwnProperty(header)) { return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value; } } return null; }, /** Sets the Content-Type header for the response to mime. Throws an "InvalidStateError" exception if the state is LOADING or DONE. Throws a "SyntaxError" exception if mime is not a valid media type. @method overrideMimeType @param String mime Mime type to set */ overrideMimeType: function(mime) { var matches, charset; // 1 if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 mime = Basic.trim(mime.toLowerCase()); if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) { mime = matches[1]; if (matches[2]) { charset = matches[2]; } } if (!Mime.mimes[mime]) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3-4 _finalMime = mime; _finalCharset = charset; }, /** Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. @method send @param {Blob|Document|String|FormData} [data] Request entity body @param {Object} [options] Set of requirements and pre-requisities for runtime initialization */ send: function(data, options) { if (Basic.typeOf(options) === 'string') { _options = { ruid: options }; } else if (!options) { _options = {}; } else { _options = options; } this.convertEventPropsToHandlers(dispatches); this.upload.convertEventPropsToHandlers(dispatches); // 1-2 if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 // sending Blob if (data instanceof Blob) { _options.ruid = data.ruid; _mimeType = data.type || 'application/octet-stream'; } // FormData else if (data instanceof FormData) { if (data.hasBlob()) { var blob = data.getBlob(); _options.ruid = blob.ruid; _mimeType = blob.type || 'application/octet-stream'; } } // DOMString else if (typeof data === 'string') { _encoding = 'UTF-8'; _mimeType = 'text/plain;charset=UTF-8'; // data should be converted to Unicode and encoded as UTF-8 data = Encode.utf8_encode(data); } // if withCredentials not set, but requested, set it automatically if (!this.withCredentials) { this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag; } // 4 - storage mutex // 5 _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP // 6 _error_flag = false; // 7 _upload_complete_flag = !data; // 8 - Asynchronous steps if (!_sync_flag) { // 8.1 _send_flag = true; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 //if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr //} } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR.call(this, data); }, /** Cancels any network activity. @method abort */ abort: function() { _error_flag = true; _sync_flag = false; if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) { _p('readyState', XMLHttpRequest.DONE); _send_flag = false; if (_xhr) { _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag); } else { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _upload_complete_flag = true; } else { _p('readyState', XMLHttpRequest.UNSENT); } }, destroy: function() { if (_xhr) { if (Basic.typeOf(_xhr.destroy) === 'function') { _xhr.destroy(); } _xhr = null; } this.unbindAll(); if (this.upload) { this.upload.unbindAll(); this.upload = null; } } }); /* this is nice, but maybe too lengthy // if supported by JS version, set getters/setters for specific properties o.defineProperty(this, 'readyState', { configurable: false, get: function() { return _p('readyState'); } }); o.defineProperty(this, 'timeout', { configurable: false, get: function() { return _p('timeout'); }, set: function(value) { if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // timeout still should be measured relative to the start time of request _timeoutset_time = (new Date).getTime(); _p('timeout', value); } }); // the withCredentials attribute has no effect when fetching same-origin resources o.defineProperty(this, 'withCredentials', { configurable: false, get: function() { return _p('withCredentials'); }, set: function(value) { // 1-2 if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3-4 if (_anonymous_flag || _sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 5 _p('withCredentials', value); } }); o.defineProperty(this, 'status', { configurable: false, get: function() { return _p('status'); } }); o.defineProperty(this, 'statusText', { configurable: false, get: function() { return _p('statusText'); } }); o.defineProperty(this, 'responseType', { configurable: false, get: function() { return _p('responseType'); }, set: function(value) { // 1 if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 3 _p('responseType', value.toLowerCase()); } }); o.defineProperty(this, 'responseText', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'text'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseText'); } }); o.defineProperty(this, 'responseXML', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'document'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseXML'); } }); o.defineProperty(this, 'response', { configurable: false, get: function() { if (!!~o.inArray(_p('responseType'), ['', 'text'])) { if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { return ''; } } if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { return null; } return _p('response'); } }); */ function _p(prop, value) { if (!props.hasOwnProperty(prop)) { return; } if (arguments.length === 1) { // get return Env.can('define_property') ? props[prop] : self[prop]; } else { // set if (Env.can('define_property')) { props[prop] = value; } else { self[prop] = value; } } } /* function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) { // TODO: http://tools.ietf.org/html/rfc3490#section-4.1 return str.toLowerCase(); } */ function _doXHR(data) { var self = this; _start_time = new Date().getTime(); _xhr = new RuntimeTarget(); function loadEnd() { if (_xhr) { // it could have been destroyed by now _xhr.destroy(); _xhr = null; } self.dispatchEvent('loadend'); self = null; } function exec(runtime) { _xhr.bind('LoadStart', function(e) { _p('readyState', XMLHttpRequest.LOADING); self.dispatchEvent('readystatechange'); self.dispatchEvent(e); if (_upload_events_flag) { self.upload.dispatchEvent(e); } }); _xhr.bind('Progress', function(e) { if (_p('readyState') !== XMLHttpRequest.LOADING) { _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example) self.dispatchEvent('readystatechange'); } self.dispatchEvent(e); }); _xhr.bind('UploadProgress', function(e) { if (_upload_events_flag) { self.upload.dispatchEvent({ type: 'progress', lengthComputable: false, total: e.total, loaded: e.loaded }); } }); _xhr.bind('Load', function(e) { _p('readyState', XMLHttpRequest.DONE); _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0)); _p('statusText', httpCode[_p('status')] || ""); _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType'))); if (!!~Basic.inArray(_p('responseType'), ['text', ''])) { _p('responseText', _p('response')); } else if (_p('responseType') === 'document') { _p('responseXML', _p('response')); } _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders'); self.dispatchEvent('readystatechange'); if (_p('status') > 0) { // status 0 usually means that server is unreachable if (_upload_events_flag) { self.upload.dispatchEvent(e); } self.dispatchEvent(e); } else { _error_flag = true; self.dispatchEvent('error'); } loadEnd(); }); _xhr.bind('Abort', function(e) { self.dispatchEvent(e); loadEnd(); }); _xhr.bind('Error', function(e) { _error_flag = true; _p('readyState', XMLHttpRequest.DONE); self.dispatchEvent('readystatechange'); _upload_complete_flag = true; self.dispatchEvent(e); loadEnd(); }); runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', { url: _url, method: _method, async: _async, user: _user, password: _password, headers: _headers, mimeType: _mimeType, encoding: _encoding, responseType: self.responseType, withCredentials: self.withCredentials, options: _options }, data); } // clarify our requirements if (typeof(_options.required_caps) === 'string') { _options.required_caps = Runtime.parseCaps(_options.required_caps); } _options.required_caps = Basic.extend({}, _options.required_caps, { return_response_type: self.responseType }); if (data instanceof FormData) { _options.required_caps.send_multipart = true; } if (!_same_origin_flag) { _options.required_caps.do_cors = true; } if (_options.ruid) { // we do not need to wait if we can connect directly exec(_xhr.connectRuntime(_options)); } else { _xhr.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); _xhr.bind('RuntimeError', function(e, err) { self.dispatchEvent('RuntimeError', err); }); _xhr.connectRuntime(_options); } } function _reset() { _p('responseText', ""); _p('responseXML', null); _p('response', null); _p('status', 0); _p('statusText', ""); _start_time = _timeoutset_time = null; } } XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; XMLHttpRequest.DONE = 4; XMLHttpRequest.prototype = EventTarget.instance; return XMLHttpRequest; }); // Included from: src/javascript/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/runtime/Transporter", [ "moxie/core/utils/Basic", "moxie/core/utils/Encode", "moxie/runtime/RuntimeClient", "moxie/core/EventTarget" ], function(Basic, Encode, RuntimeClient, EventTarget) { function Transporter() { var mod, _runtime, _data, _size, _pos, _chunk_size; RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), state: Transporter.IDLE, result: null, transport: function(data, type, options) { var self = this; options = Basic.extend({ chunk_size: 204798 }, options); // should divide by three, base64 requires this if ((mod = options.chunk_size % 3)) { options.chunk_size += 3 - mod; } _chunk_size = options.chunk_size; _reset.call(this); _data = data; _size = data.length; if (Basic.typeOf(options) === 'string' || options.ruid) { _run.call(self, type, this.connectRuntime(options)); } else { // we require this to run only once var cb = function(e, runtime) { self.unbind("RuntimeInit", cb); _run.call(self, type, runtime); }; this.bind("RuntimeInit", cb); this.connectRuntime(options); } }, abort: function() { var self = this; self.state = Transporter.IDLE; if (_runtime) { _runtime.exec.call(self, 'Transporter', 'clear'); self.trigger("TransportingAborted"); } _reset.call(self); }, destroy: function() { this.unbindAll(); _runtime = null; this.disconnectRuntime(); _reset.call(this); } }); function _reset() { _size = _pos = 0; _data = this.result = null; } function _run(type, runtime) { var self = this; _runtime = runtime; //self.unbind("RuntimeInit"); self.bind("TransportingProgress", function(e) { _pos = e.loaded; if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) { _transport.call(self); } }, 999); self.bind("TransportingComplete", function() { _pos = _size; self.state = Transporter.DONE; _data = null; // clean a bit self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || ''); }, 999); self.state = Transporter.BUSY; self.trigger("TransportingStarted"); _transport.call(self); } function _transport() { var self = this, chunk, bytesLeft = _size - _pos; if (_chunk_size > bytesLeft) { _chunk_size = bytesLeft; } chunk = Encode.btoa(_data.substr(_pos, _chunk_size)); _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size); } } Transporter.IDLE = 0; Transporter.BUSY = 1; Transporter.DONE = 2; Transporter.prototype = EventTarget.instance; return Transporter; }); // Included from: src/javascript/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/image/Image", [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/file/FileReaderSync", "moxie/xhr/XMLHttpRequest", "moxie/runtime/Runtime", "moxie/runtime/RuntimeClient", "moxie/runtime/Transporter", "moxie/core/utils/Env", "moxie/core/EventTarget", "moxie/file/Blob", "moxie/file/File", "moxie/core/utils/Encode" ], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode) { /** Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data. @class Image @constructor @extends EventTarget */ var dispatches = [ 'progress', /** Dispatched when loading is complete. @event load @param {Object} event */ 'load', 'error', /** Dispatched when resize operation is complete. @event resize @param {Object} event */ 'resize', /** Dispatched when visual representation of the image is successfully embedded into the corresponsing container. @event embedded @param {Object} event */ 'embedded' ]; function Image() { RuntimeClient.call(this); Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @type {String} */ ruid: null, /** Name of the file, that was used to create an image, if available. If not equals to empty string. @property name @type {String} @default "" */ name: "", /** Size of the image in bytes. Actual value is set only after image is preloaded. @property size @type {Number} @default 0 */ size: 0, /** Width of the image. Actual value is set only after image is preloaded. @property width @type {Number} @default 0 */ width: 0, /** Height of the image. Actual value is set only after image is preloaded. @property height @type {Number} @default 0 */ height: 0, /** Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded. @property type @type {String} @default "" */ type: "", /** Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded. @property meta @type {Object} @default {} */ meta: {}, /** Alias for load method, that takes another mOxie.Image object as a source (see load). @method clone @param {Image} src Source for the image @param {Boolean} [exact=false] Whether to activate in-depth clone mode */ clone: function() { this.load.apply(this, arguments); }, /** Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File, native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL, Image will be downloaded from remote destination and loaded in memory. @example var img = new mOxie.Image(); img.onload = function() { var blob = img.getAsBlob(); var formData = new mOxie.FormData(); formData.append('file', blob); var xhr = new mOxie.XMLHttpRequest(); xhr.onload = function() { // upload complete }; xhr.open('post', 'upload.php'); xhr.send(formData); }; img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg) @method load @param {Image|Blob|File|String} src Source for the image @param {Boolean|Object} [mixed] */ load: function() { // this is here because to bind properly we need an uid first, which is created above this.bind('Load Resize', function() { _updateInfo.call(this); }, 999); this.convertEventPropsToHandlers(dispatches); _load.apply(this, arguments); }, /** Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions. @method downsize @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [crop=false] Whether to crop the image to exact dimensions @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ downsize: function(opts) { var defaults = { width: this.width, height: this.height, crop: false, preserveHeaders: true }; if (typeof(opts) === 'object') { opts = Basic.extend(defaults, opts); } else { opts = Basic.extend(defaults, { width: arguments[0], height: arguments[1], crop: arguments[2], preserveHeaders: arguments[3] }); } try { if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // no way to reliably intercept the crash due to high resolution, so we simply avoid it if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } this.getRuntime().exec.call(this, 'Image', 'downsize', opts.width, opts.height, opts.crop, opts.preserveHeaders); } catch(ex) { // for now simply trigger error event this.trigger('error', ex.code); } }, /** Alias for downsize(width, height, true). (see downsize) @method crop @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ crop: function(width, height, preserveHeaders) { this.downsize(width, height, true, preserveHeaders); }, getAsCanvas: function() { if (!Env.can('create_canvas')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } var runtime = this.connectRuntime(this.ruid); return runtime.exec.call(this, 'Image', 'getAsCanvas'); }, /** Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBlob @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {Blob} Image as Blob */ getAsBlob: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (!type) { type = 'image/jpeg'; } if (type === 'image/jpeg' && !quality) { quality = 90; } return this.getRuntime().exec.call(this, 'Image', 'getAsBlob', type, quality); }, /** Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsDataURL @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as dataURL string */ getAsDataURL: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return this.getRuntime().exec.call(this, 'Image', 'getAsDataURL', type, quality); }, /** Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBinaryString @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as binary string */ getAsBinaryString: function(type, quality) { var dataUrl = this.getAsDataURL(type, quality); return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)); }, /** Embeds a visual representation of the image into the specified node. Depending on the runtime, it might be a canvas, an img node or a thrid party shim object (Flash or SilverLight - very rare, can be used in legacy browsers that do not have canvas or proper dataURI support). @method embed @param {DOMElement} el DOM element to insert the image object into @param {Object} [options] @param {Number} [options.width] The width of an embed (defaults to the image width) @param {Number} [options.height] The height of an embed (defaults to the image height) @param {String} [type="image/jpeg"] Mime type @param {Number} [quality=90] Quality of an embed, if mime type is image/jpeg @param {Boolean} [crop=false] Whether to crop an embed to the specified dimensions */ embed: function(el) { var self = this , imgCopy , type, quality, crop , options = arguments[1] || {} , width = this.width , height = this.height , runtime // this has to be outside of all the closures to contain proper runtime ; function onResize() { // if possible, embed a canvas element directly if (Env.can('create_canvas')) { var canvas = imgCopy.getAsCanvas(); if (canvas) { el.appendChild(canvas); canvas = null; imgCopy.destroy(); self.trigger('embedded'); return; } } var dataUrl = imgCopy.getAsDataURL(type, quality); if (!dataUrl) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } if (Env.can('use_data_uri_of', dataUrl.length)) { el.innerHTML = '<img src="' + dataUrl + '" width="' + imgCopy.width + '" height="' + imgCopy.height + '" />'; imgCopy.destroy(); self.trigger('embedded'); } else { var tr = new Transporter(); tr.bind("TransportingComplete", function() { runtime = self.connectRuntime(this.result.ruid); self.bind("Embedded", function() { // position and size properly Basic.extend(runtime.getShimContainer().style, { //position: 'relative', top: '0px', left: '0px', width: imgCopy.width + 'px', height: imgCopy.height + 'px' }); // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and // sometimes 8 and they do not have this problem, we can comment this for now /*tr.bind("RuntimeInit", function(e, runtime) { tr.destroy(); runtime.destroy(); onResize.call(self); // re-feed our image data });*/ runtime = null; }, 999); runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height); imgCopy.destroy(); }); tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, Basic.extend({}, options, { required_caps: { display_media: true }, runtime_order: 'flash,silverlight', container: el })); } } try { if (!(el = Dom.get(el))) { throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR); } if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } type = options.type || this.type || 'image/jpeg'; quality = options.quality || 90; crop = Basic.typeOf(options.crop) !== 'undefined' ? options.crop : false; // figure out dimensions for the thumb if (options.width) { width = options.width; height = options.height || width; } else { // if container element has measurable dimensions, use them var dimensions = Dom.getSize(el); if (dimensions.w && dimensions.h) { // both should be > 0 width = dimensions.w; height = dimensions.h; } } imgCopy = new Image(); imgCopy.bind("Resize", function() { onResize.call(self); }); imgCopy.bind("Load", function() { imgCopy.downsize(width, height, crop, false); }); imgCopy.clone(this, false); return imgCopy; } catch(ex) { // for now simply trigger error event this.trigger('error', ex.code); } }, /** Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object. @method destroy */ destroy: function() { if (this.ruid) { this.getRuntime().exec.call(this, 'Image', 'destroy'); this.disconnectRuntime(); } this.unbindAll(); } }); function _updateInfo(info) { if (!info) { info = this.getRuntime().exec.call(this, 'Image', 'getInfo'); } this.size = info.size; this.width = info.width; this.height = info.height; this.type = info.type; this.meta = info.meta; // update file name, only if empty if (this.name === '') { this.name = info.name; } } function _load(src) { var srcType = Basic.typeOf(src); try { // if source is Image if (src instanceof Image) { if (!src.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _loadFromImage.apply(this, arguments); } // if source is o.Blob/o.File else if (src instanceof Blob) { if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } _loadFromBlob.apply(this, arguments); } // if native blob/file else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) { _load.call(this, new File(null, src), arguments[1]); } // if String else if (srcType === 'string') { // if dataUrl String if (/^data:[^;]*;base64,/.test(src)) { _load.call(this, new Blob(null, { data: src }), arguments[1]); } // else assume Url, either relative or absolute else { _loadFromUrl.apply(this, arguments); } } // if source seems to be an img node else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') { _load.call(this, src.src, arguments[1]); } else { throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR); } } catch(ex) { // for now simply trigger error event this.trigger('error', ex.code); } } function _loadFromImage(img, exact) { var runtime = this.connectRuntime(img.ruid); this.ruid = runtime.uid; runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact)); } function _loadFromBlob(blob, options) { var self = this; self.name = blob.name || ''; function exec(runtime) { self.ruid = runtime.uid; runtime.exec.call(self, 'Image', 'loadFromBlob', blob); } if (blob.isDetached()) { this.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); // convert to object representation if (options && typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } this.connectRuntime(Basic.extend({ required_caps: { access_image_binary: true, resize_image: true } }, options)); } else { exec(this.connectRuntime(blob.ruid)); } } function _loadFromUrl(url, options) { var self = this, xhr; xhr = new XMLHttpRequest(); xhr.open('get', url); xhr.responseType = 'blob'; xhr.onprogress = function(e) { self.trigger(e); }; xhr.onload = function() { _loadFromBlob.call(self, xhr.response, true); }; xhr.onerror = function(e) { self.trigger(e); }; xhr.onloadend = function() { xhr.destroy(); }; xhr.bind('RuntimeError', function(e, err) { self.trigger('RuntimeError', err); }); xhr.send(null, options); } } // virtual world will crash on you if image has a resolution higher than this: Image.MAX_RESIZE_WIDTH = 6500; Image.MAX_RESIZE_HEIGHT = 6500; Image.prototype = EventTarget.instance; return Image; }); // Included from: src/javascript/runtime/html4/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML4 runtime. @class moxie/runtime/html4/Runtime @private */ define("moxie/runtime/html4/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = 'html4', extensions = {}; function Html4Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; Runtime.call(this, options, type, { access_binary: Test(window.FileReader || window.File && File.getAsDataURL), access_image_binary: false, display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))), do_cors: false, drag_and_drop: false, filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), resize_image: function() { return extensions.Image && I.can('access_binary') && Env.can('create_canvas'); }, report_upload_progress: false, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !!~Basic.inArray(responseType, ['text', 'document', '']); }, return_status_code: function(code) { return !Basic.arrayDiff(code, [200, 404]); }, select_file: function() { return Env.can('use_fileinput'); }, select_multiple: false, send_binary_string: false, send_custom_headers: false, send_multipart: true, slice_blob: false, stream_upload: function() { return I.can('select_file'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html4Runtime); return extensions; }); // Included from: src/javascript/core/utils/Events.js /** * Events.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Events', [ 'moxie/core/utils/Basic' ], function(Basic) { var eventhash = {}, uid = 'moxie_' + Basic.guid(); // IE W3C like event funcs function preventDefault() { this.returnValue = false; } function stopPropagation() { this.cancelBubble = true; } /** Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry (@see removeEvent). @method addEvent @for Utils @static @param {Object} obj DOM element like object to add handler to. @param {String} name Name to add event listener to. @param {Function} callback Function to call when event occurs. @param {String} [key] that might be used to add specifity to the event record. */ var addEvent = function(obj, name, callback, key) { var func, events; name = name.toLowerCase(); // Add event listener if (obj.addEventListener) { func = callback; obj.addEventListener(name, func, false); } else if (obj.attachEvent) { func = function() { var evt = window.event; if (!evt.target) { evt.target = evt.srcElement; } evt.preventDefault = preventDefault; evt.stopPropagation = stopPropagation; callback(evt); }; obj.attachEvent('on' + name, func); } // Log event handler to objects internal mOxie registry if (!obj[uid]) { obj[uid] = Basic.guid(); } if (!eventhash.hasOwnProperty(obj[uid])) { eventhash[obj[uid]] = {}; } events = eventhash[obj[uid]]; if (!events.hasOwnProperty(name)) { events[name] = []; } events[name].push({ func: func, orig: callback, // store original callback for IE key: key }); }; /** Remove event handler from the specified object. If third argument (callback) is not specified remove all events with the specified name. @method removeEvent @static @param {Object} obj DOM element to remove event listener(s) from. @param {String} name Name of event listener to remove. @param {Function|String} [callback] might be a callback or unique key to match. */ var removeEvent = function(obj, name, callback) { var type, undef; name = name.toLowerCase(); if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) { type = eventhash[obj[uid]][name]; } else { return; } for (var i = type.length - 1; i >= 0; i--) { // undefined or not, key should match if (type[i].orig === callback || type[i].key === callback) { if (obj.removeEventListener) { obj.removeEventListener(name, type[i].func, false); } else if (obj.detachEvent) { obj.detachEvent('on'+name, type[i].func); } type[i].orig = null; type[i].func = null; type.splice(i, 1); // If callback was passed we are done here, otherwise proceed if (callback !== undef) { break; } } } // If event array got empty, remove it if (!type.length) { delete eventhash[obj[uid]][name]; } // If mOxie registry has become empty, remove it if (Basic.isEmptyObj(eventhash[obj[uid]])) { delete eventhash[obj[uid]]; // IE doesn't let you remove DOM object property with - delete try { delete obj[uid]; } catch(e) { obj[uid] = undef; } } }; /** Remove all kind of events from the specified object @method removeAllEvents @static @param {Object} obj DOM element to remove event listeners from. @param {String} [key] unique key to match, when removing events. */ var removeAllEvents = function(obj, key) { if (!obj || !obj[uid]) { return; } Basic.each(eventhash[obj[uid]], function(events, name) { removeEvent(obj, name, key); }); }; return { addEvent: addEvent, removeEvent: removeEvent, removeAllEvents: removeAllEvents }; }); // Included from: src/javascript/runtime/html4/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileInput @private */ define("moxie/runtime/html4/file/FileInput", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _uid, _files = [], _mimes = [], _options; function addInput() { var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid; uid = Basic.guid('uid_'); shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE if (_uid) { // move previous form out of the view currForm = Dom.get(_uid + '_form'); if (currForm) { Basic.extend(currForm.style, { top: '100%' }); } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', 'post'); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); Basic.extend(form.style, { overflow: 'hidden', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); input = document.createElement('input'); input.setAttribute('id', uid); input.setAttribute('type', 'file'); input.setAttribute('name', _options.name || 'Filedata'); input.setAttribute('accept', _mimes.join(',')); Basic.extend(input.style, { fontSize: '999px', opacity: 0 }); form.appendChild(input); shimContainer.appendChild(form); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); if (Env.browser === 'IE' && Env.version < 10) { Basic.extend(input.style, { filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)" }); } input.onchange = function() { // there should be only one handler for this var file; if (!this.value) { return; } if (this.files) { file = this.files[0]; } else { file = { name: this.value }; } _files = [file]; this.onchange = function() {}; // clear event handler addInput.call(comp); // after file is initialized as o.File, we need to update form and input ids comp.bind('change', function onChange() { var input = Dom.get(uid), form = Dom.get(uid + '_form'), file; comp.unbind('change', onChange); if (comp.files.length && input && form) { file = comp.files[0]; input.setAttribute('id', file.uid); form.setAttribute('id', file.uid + '_form'); // set upload target form.setAttribute('target', file.uid + '_iframe'); } input = form = null; }, 998); input = form = null; comp.trigger('change'); }; // route click event to the input if (I.can('summon_file_dialog')) { browseButton = Dom.get(_options.browse_button); Events.removeEvent(browseButton, 'click', comp.uid); Events.addEvent(browseButton, 'click', function(e) { if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } _uid = uid; shimContainer = currForm = browseButton = null; } Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), shimContainer; // figure out accept string _options = options; _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); (function() { var browseButton, zIndex, top; browseButton = Dom.get(options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); browseButton = null; }()); addInput.call(this); shimContainer = null; // trigger ready event asynchronously comp.trigger({ type: 'ready', async: true }); }, getFiles: function() { return _files; }, disable: function(state) { var input; if ((input = Dom.get(_uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime() , shim = I.getShim() , shimContainer = I.getShimContainer() ; Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } shim.removeInstance(this.uid); _uid = _files = _mimes = _options = shimContainer = shim = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html5/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML5 runtime. @class moxie/runtime/html5/Runtime @private */ define("moxie/runtime/html5/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = "html5", extensions = {}; function Html5Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; var caps = Basic.extend({ access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL), access_image_binary: function() { return I.can('access_binary') && !!extensions.Image; }, display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')), do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()), drag_and_drop: Test(function() { // this comes directly from Modernizr: http://www.modernizr.com/ var div = document.createElement('div'); // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9); }()), filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), return_response_headers: True, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported return true; } return Env.can('return_response_type', responseType); }, return_status_code: True, report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload), resize_image: function() { return I.can('access_binary') && Env.can('create_canvas'); }, select_file: function() { return Env.can('use_fileinput') && window.File; }, select_folder: function() { return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21; }, select_multiple: function() { // it is buggy on Safari Windows and iOS return I.can('select_file') && !(Env.browser === 'Safari' && Env.os === 'Windows') && !(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<')); }, send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))), send_custom_headers: Test(window.XMLHttpRequest), send_multipart: function() { return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string'); }, slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)), stream_upload: function(){ return I.can('slice_blob') && I.can('send_multipart'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True }, arguments[2] ); Runtime.call(this, options, (arguments[1] || type), caps); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html5Runtime); return extensions; }); // Included from: src/javascript/runtime/html5/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileReader @private */ define("moxie/runtime/html5/file/FileReader", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic" ], function(extensions, Encode, Basic) { function FileReader() { var _fr, _convertToBinary = false; Basic.extend(this, { read: function(op, blob) { var target = this; _fr = new window.FileReader(); _fr.addEventListener('progress', function(e) { target.trigger(e); }); _fr.addEventListener('load', function(e) { target.trigger(e); }); _fr.addEventListener('error', function(e) { target.trigger(e, _fr.error); }); _fr.addEventListener('loadend', function() { _fr = null; }); if (Basic.typeOf(_fr[op]) === 'function') { _convertToBinary = false; _fr[op](blob.getSource()); } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+ _convertToBinary = true; _fr.readAsDataURL(blob.getSource()); } }, getResult: function() { return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null; }, abort: function() { if (_fr) { _fr.abort(); } }, destroy: function() { _fr = null; } }); function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } } return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileReader @private */ define("moxie/runtime/html4/file/FileReader", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/file/FileReader" ], function(extensions, FileReader) { return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/xhr/XMLHttpRequest @private */ define("moxie/runtime/html4/xhr/XMLHttpRequest", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Url", "moxie/core/Exceptions", "moxie/core/utils/Events", "moxie/file/Blob", "moxie/xhr/FormData" ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) { function XMLHttpRequest() { var _status, _response, _iframe; function cleanup(cb) { var target = this, uid, form, inputs, i, hasFile = false; if (!_iframe) { return; } uid = _iframe.id.replace(/_iframe$/, ''); form = Dom.get(uid + '_form'); if (form) { inputs = form.getElementsByTagName('input'); i = inputs.length; while (i--) { switch (inputs[i].getAttribute('type')) { case 'hidden': inputs[i].parentNode.removeChild(inputs[i]); break; case 'file': hasFile = true; // flag the case for later break; } } inputs = []; if (!hasFile) { // we need to keep the form for sake of possible retries form.parentNode.removeChild(form); } form = null; } // without timeout, request is marked as canceled (in console) setTimeout(function() { Events.removeEvent(_iframe, 'load', target.uid); if (_iframe.parentNode) { // #382 _iframe.parentNode.removeChild(_iframe); } // check if shim container has any other children, if - not, remove it as well var shimContainer = target.getRuntime().getShimContainer(); if (!shimContainer.children.length) { shimContainer.parentNode.removeChild(shimContainer); } shimContainer = _iframe = null; cb(); }, 1); } Basic.extend(this, { send: function(meta, data) { var target = this, I = target.getRuntime(), uid, form, input, blob; _status = _response = null; function createIframe() { var container = I.getShimContainer() || document.body , temp = document.createElement('div') ; // IE 6 won't be able to set the name using setAttribute or iframe.name temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>'; _iframe = temp.firstChild; container.appendChild(_iframe); /* _iframe.onreadystatechange = function() { console.info(_iframe.readyState); };*/ Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8 var el; try { el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document; // try to detect some standard error pages if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error _status = el.title.replace(/^(\d+).*$/, '$1'); } else { _status = 200; // get result _response = Basic.trim(el.body.innerHTML); // we need to fire these at least once target.trigger({ type: 'progress', loaded: _response.length, total: _response.length }); if (blob) { // if we were uploading a file target.trigger({ type: 'uploadprogress', loaded: blob.size || 1025, total: blob.size || 1025 }); } } } catch (ex) { if (Url.hasSameOrigin(meta.url)) { // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm // which obviously results to cross domain error (wtf?) _status = 404; } else { cleanup.call(target, function() { target.trigger('error'); }); return; } } cleanup.call(target, function() { target.trigger('load'); }); }, target.uid); } // end createIframe // prepare data to be sent and convert if required if (data instanceof FormData && data.hasBlob()) { blob = data.getBlob(); uid = blob.uid; input = Dom.get(uid); form = Dom.get(uid + '_form'); if (!form) { throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } } else { uid = Basic.guid('uid_'); form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', meta.method); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute('target', uid + '_iframe'); I.getShimContainer().appendChild(form); } if (data instanceof FormData) { data.each(function(value, name) { if (value instanceof Blob) { if (input) { input.setAttribute('name', name); } } else { var hidden = document.createElement('input'); Basic.extend(hidden, { type : 'hidden', name : name, value : value }); // make sure that input[type="file"], if it's there, comes last if (input) { form.insertBefore(hidden, input); } else { form.appendChild(hidden); } } }); } // set destination url form.setAttribute("action", meta.url); createIframe(); form.submit(); target.trigger('loadstart'); }, getStatus: function() { return _status; }, getResponse: function(responseType) { if ('json' === responseType) { // strip off <pre>..</pre> tags that might be enclosing the response if (Basic.typeOf(_response) === 'string' && !!window.JSON) { try { return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, '')); } catch (ex) { return null; } } } else if ('document' === responseType) { } return _response; }, abort: function() { var target = this; if (_iframe && _iframe.contentWindow) { if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome _iframe.contentWindow.stop(); } else if (_iframe.contentWindow.document.execCommand) { // IE _iframe.contentWindow.document.execCommand('Stop'); } else { _iframe.src = "about:blank"; } } cleanup.call(this, function() { // target.dispatchEvent('readystatechange'); target.dispatchEvent('abort'); }); } }); } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html5/utils/BinaryReader.js /** * BinaryReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/utils/BinaryReader @private */ define("moxie/runtime/html5/utils/BinaryReader", [], function() { return function() { var II = false, bin; // Private functions function read(idx, size) { var mv = II ? 0 : -8 * (size - 1), sum = 0, i; for (i = 0; i < size; i++) { sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8)); } return sum; } function putstr(segment, idx, length) { length = arguments.length === 3 ? length : bin.length - idx - 1; bin = bin.substr(0, idx) + segment + bin.substr(length + idx); } function write(idx, num, size) { var str = '', mv = II ? 0 : -8 * (size - 1), i; for (i = 0; i < size; i++) { str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255); } putstr(str, idx, size); } // Public functions return { II: function(order) { if (order === undefined) { return II; } else { II = order; } }, init: function(binData) { II = false; bin = binData; }, SEGMENT: function(idx, length, segment) { switch (arguments.length) { case 1: return bin.substr(idx, bin.length - idx - 1); case 2: return bin.substr(idx, length); case 3: putstr(segment, idx, length); break; default: return bin; } }, BYTE: function(idx) { return read(idx, 1); }, SHORT: function(idx) { return read(idx, 2); }, LONG: function(idx, num) { if (num === undefined) { return read(idx, 4); } else { write(idx, num, 4); } }, SLONG: function(idx) { // 2's complement notation var num = read(idx, 4); return (num > 2147483647 ? num - 4294967296 : num); }, STRING: function(idx, size) { var str = ''; for (size += idx; idx < size; idx++) { str += String.fromCharCode(read(idx, 1)); } return str; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEGHeaders.js /** * JPEGHeaders.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEGHeaders @private */ define("moxie/runtime/html5/image/JPEGHeaders", [ "moxie/runtime/html5/utils/BinaryReader" ], function(BinaryReader) { return function JPEGHeaders(data) { var headers = [], read, idx, marker, length = 0; read = new BinaryReader(); read.init(data); // Check if data is jpeg if (read.SHORT(0) !== 0xFFD8) { return; } idx = 2; while (idx <= data.length) { marker = read.SHORT(idx); // omit RST (restart) markers if (marker >= 0xFFD0 && marker <= 0xFFD7) { idx += 2; continue; } // no headers allowed after SOS marker if (marker === 0xFFDA || marker === 0xFFD9) { break; } length = read.SHORT(idx + 2) + 2; // APPn marker detected if (marker >= 0xFFE1 && marker <= 0xFFEF) { headers.push({ hex: marker, name: 'APP' + (marker & 0x000F), start: idx, length: length, segment: read.SEGMENT(idx, length) }); } idx += length; } read.init(null); // free memory return { headers: headers, restore: function(data) { var max, i; read.init(data); idx = read.SHORT(2) == 0xFFE0 ? 4 + read.SHORT(4) : 2; for (i = 0, max = headers.length; i < max; i++) { read.SEGMENT(idx, 0, headers[i].segment); idx += headers[i].length; } data = read.SEGMENT(); read.init(null); return data; }, strip: function(data) { var headers, jpegHeaders, i; jpegHeaders = new JPEGHeaders(data); headers = jpegHeaders.headers; jpegHeaders.purge(); read.init(data); i = headers.length; while (i--) { read.SEGMENT(headers[i].start, headers[i].length, ''); } data = read.SEGMENT(); read.init(null); return data; }, get: function(name) { var array = []; for (var i = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { array.push(headers[i].segment); } } return array; }, set: function(name, segment) { var array = [], i, ii, max; if (typeof(segment) === 'string') { array.push(segment); } else { array = segment; } for (i = ii = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { headers[i].segment = array[ii]; headers[i].length = array[ii].length; ii++; } if (ii >= array.length) { break; } } }, purge: function() { headers = []; read.init(null); read = null; } }; }; }); // Included from: src/javascript/runtime/html5/image/ExifParser.js /** * ExifParser.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ExifParser @private */ define("moxie/runtime/html5/image/ExifParser", [ "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(Basic, BinaryReader) { return function ExifParser() { // Private ExifParser fields var data, tags, Tiff, offsets = {}, tagDescs; data = new BinaryReader(); tags = { tiff : { /* The image orientation viewed in terms of rows and columns. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ 0x0112: 'Orientation', 0x010E: 'ImageDescription', 0x010F: 'Make', 0x0110: 'Model', 0x0131: 'Software', 0x8769: 'ExifIFDPointer', 0x8825: 'GPSInfoIFDPointer' }, exif : { 0x9000: 'ExifVersion', 0xA001: 'ColorSpace', 0xA002: 'PixelXDimension', 0xA003: 'PixelYDimension', 0x9003: 'DateTimeOriginal', 0x829A: 'ExposureTime', 0x829D: 'FNumber', 0x8827: 'ISOSpeedRatings', 0x9201: 'ShutterSpeedValue', 0x9202: 'ApertureValue' , 0x9207: 'MeteringMode', 0x9208: 'LightSource', 0x9209: 'Flash', 0x920A: 'FocalLength', 0xA402: 'ExposureMode', 0xA403: 'WhiteBalance', 0xA406: 'SceneCaptureType', 0xA404: 'DigitalZoomRatio', 0xA408: 'Contrast', 0xA409: 'Saturation', 0xA40A: 'Sharpness' }, gps : { 0x0000: 'GPSVersionID', 0x0001: 'GPSLatitudeRef', 0x0002: 'GPSLatitude', 0x0003: 'GPSLongitudeRef', 0x0004: 'GPSLongitude' } }; tagDescs = { 'ColorSpace': { 1: 'sRGB', 0: 'Uncalibrated' }, 'MeteringMode': { 0: 'Unknown', 1: 'Average', 2: 'CenterWeightedAverage', 3: 'Spot', 4: 'MultiSpot', 5: 'Pattern', 6: 'Partial', 255: 'Other' }, 'LightSource': { 1: 'Daylight', 2: 'Fliorescent', 3: 'Tungsten', 4: 'Flash', 9: 'Fine weather', 10: 'Cloudy weather', 11: 'Shade', 12: 'Daylight fluorescent (D 5700 - 7100K)', 13: 'Day white fluorescent (N 4600 -5400K)', 14: 'Cool white fluorescent (W 3900 - 4500K)', 15: 'White fluorescent (WW 3200 - 3700K)', 17: 'Standard light A', 18: 'Standard light B', 19: 'Standard light C', 20: 'D55', 21: 'D65', 22: 'D75', 23: 'D50', 24: 'ISO studio tungsten', 255: 'Other' }, 'Flash': { 0x0000: 'Flash did not fire.', 0x0001: 'Flash fired.', 0x0005: 'Strobe return light not detected.', 0x0007: 'Strobe return light detected.', 0x0009: 'Flash fired, compulsory flash mode', 0x000D: 'Flash fired, compulsory flash mode, return light not detected', 0x000F: 'Flash fired, compulsory flash mode, return light detected', 0x0010: 'Flash did not fire, compulsory flash mode', 0x0018: 'Flash did not fire, auto mode', 0x0019: 'Flash fired, auto mode', 0x001D: 'Flash fired, auto mode, return light not detected', 0x001F: 'Flash fired, auto mode, return light detected', 0x0020: 'No flash function', 0x0041: 'Flash fired, red-eye reduction mode', 0x0045: 'Flash fired, red-eye reduction mode, return light not detected', 0x0047: 'Flash fired, red-eye reduction mode, return light detected', 0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode', 0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected', 0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected', 0x0059: 'Flash fired, auto mode, red-eye reduction mode', 0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode', 0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode' }, 'ExposureMode': { 0: 'Auto exposure', 1: 'Manual exposure', 2: 'Auto bracket' }, 'WhiteBalance': { 0: 'Auto white balance', 1: 'Manual white balance' }, 'SceneCaptureType': { 0: 'Standard', 1: 'Landscape', 2: 'Portrait', 3: 'Night scene' }, 'Contrast': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, 'Saturation': { 0: 'Normal', 1: 'Low saturation', 2: 'High saturation' }, 'Sharpness': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, // GPS related 'GPSLatitudeRef': { N: 'North latitude', S: 'South latitude' }, 'GPSLongitudeRef': { E: 'East longitude', W: 'West longitude' } }; function extractTags(IFD_offset, tags2extract) { var length = data.SHORT(IFD_offset), i, ii, tag, type, count, tagOffset, offset, value, values = [], hash = {}; for (i = 0; i < length; i++) { // Set binary reader pointer to beginning of the next tag offset = tagOffset = IFD_offset + 12 * i + 2; tag = tags2extract[data.SHORT(offset)]; if (tag === undefined) { continue; // Not the tag we requested } type = data.SHORT(offset+=2); count = data.LONG(offset+=2); offset += 4; values = []; switch (type) { case 1: // BYTE case 7: // UNDEFINED if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.BYTE(offset + ii); } break; case 2: // STRING if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } hash[tag] = data.STRING(offset, count - 1); continue; case 3: // SHORT if (count > 2) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.SHORT(offset + ii*2); } break; case 4: // LONG if (count > 1) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4); } break; case 5: // RATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4) / data.LONG(offset + ii*4 + 4); } break; case 9: // SLONG offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4); } break; case 10: // SRATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4) / data.SLONG(offset + ii*4 + 4); } break; default: continue; } value = (count == 1 ? values[0] : values); if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') { hash[tag] = tagDescs[tag][value]; } else { hash[tag] = value; } } return hash; } function getIFDOffsets() { var idx = offsets.tiffHeader; // Set read order of multi-byte data data.II(data.SHORT(idx) == 0x4949); // Check if always present bytes are indeed present if (data.SHORT(idx+=2) !== 0x002A) { return false; } offsets.IFD0 = offsets.tiffHeader + data.LONG(idx += 2); Tiff = extractTags(offsets.IFD0, tags.tiff); if ('ExifIFDPointer' in Tiff) { offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer; delete Tiff.ExifIFDPointer; } if ('GPSInfoIFDPointer' in Tiff) { offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer; delete Tiff.GPSInfoIFDPointer; } return true; } // At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported function setTag(ifd, tag, value) { var offset, length, tagOffset, valueOffset = 0; // If tag name passed translate into hex key if (typeof(tag) === 'string') { var tmpTags = tags[ifd.toLowerCase()]; for (var hex in tmpTags) { if (tmpTags[hex] === tag) { tag = hex; break; } } } offset = offsets[ifd.toLowerCase() + 'IFD']; length = data.SHORT(offset); for (var i = 0; i < length; i++) { tagOffset = offset + 12 * i + 2; if (data.SHORT(tagOffset) == tag) { valueOffset = tagOffset + 8; break; } } if (!valueOffset) { return false; } data.LONG(valueOffset, value); return true; } // Public functions return { init: function(segment) { // Reset internal data offsets = { tiffHeader: 10 }; if (segment === undefined || !segment.length) { return false; } data.init(segment); // Check if that's APP1 and that it has EXIF if (data.SHORT(0) === 0xFFE1 && data.STRING(4, 5).toUpperCase() === "EXIF\0") { return getIFDOffsets(); } return false; }, TIFF: function() { return Tiff; }, EXIF: function() { var Exif; // Populate EXIF hash Exif = extractTags(offsets.exifIFD, tags.exif); // Fix formatting of some tags if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') { for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) { exifVersion += String.fromCharCode(Exif.ExifVersion[i]); } Exif.ExifVersion = exifVersion; } return Exif; }, GPS: function() { var GPS; GPS = extractTags(offsets.gpsIFD, tags.gps); // iOS devices (and probably some others) do not put in GPSVersionID tag (why?..) if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') { GPS.GPSVersionID = GPS.GPSVersionID.join('.'); } return GPS; }, setExif: function(tag, value) { // Right now only setting of width/height is possible if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') {return false;} return setTag('exif', tag, value); }, getBinary: function() { return data.SEGMENT(); }, purge: function() { data.init(null); data = Tiff = null; offsets = {}; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEG.js /** * JPEG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEG @private */ define("moxie/runtime/html5/image/JPEG", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEGHeaders", "moxie/runtime/html5/utils/BinaryReader", "moxie/runtime/html5/image/ExifParser" ], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) { function JPEG(binstr) { var _binstr, _br, _hm, _ep, _info, hasExif; function _getDimensions() { var idx = 0, marker, length; // examine all through the end, since some images might have very large APP segments while (idx <= _binstr.length) { marker = _br.SHORT(idx += 2); if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte) return { height: _br.SHORT(idx), width: _br.SHORT(idx += 2) }; } length = _br.SHORT(idx += 2); idx += length - 2; } return null; } _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it is jpeg if (_br.SHORT(0) !== 0xFFD8) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } // backup headers _hm = new JPEGHeaders(binstr); // extract exif info _ep = new ExifParser(); hasExif = !!_ep.init(_hm.get('app1')[0]); // get dimensions _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/jpeg', size: _binstr.length, width: _info && _info.width || 0, height: _info && _info.height || 0, setExif: function(tag, value) { if (!hasExif) { return false; // or throw an exception } if (Basic.typeOf(tag) === 'object') { Basic.each(tag, function(value, tag) { _ep.setExif(tag, value); }); } else { _ep.setExif(tag, value); } // update internal headers _hm.set('app1', _ep.getBinary()); }, writeHeaders: function() { if (!arguments.length) { // if no arguments passed, update headers internally return (_binstr = _hm.restore(_binstr)); } return _hm.restore(arguments[0]); }, stripHeaders: function(binstr) { return _hm.strip(binstr); }, purge: function() { _purge.call(this); } }); if (hasExif) { this.meta = { tiff: _ep.TIFF(), exif: _ep.EXIF(), gps: _ep.GPS() }; } function _purge() { if (!_ep || !_hm || !_br) { return; // ignore any repeating purge requests } _ep.purge(); _hm.purge(); _br.init(null); _binstr = _info = _hm = _ep = _br = null; } } return JPEG; }); // Included from: src/javascript/runtime/html5/image/PNG.js /** * PNG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/PNG @private */ define("moxie/runtime/html5/image/PNG", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(x, Basic, BinaryReader) { function PNG(binstr) { var _binstr, _br, _hm, _ep, _info; _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it's png (function() { var idx = 0, i = 0 , signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A] ; for (i = 0; i < signature.length; i++, idx += 2) { if (signature[i] != _br.SHORT(idx)) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } } }()); function _getDimensions() { var chunk, idx; chunk = _getChunkAt.call(this, 8); if (chunk.type == 'IHDR') { idx = chunk.start; return { width: _br.LONG(idx), height: _br.LONG(idx += 4) }; } return null; } function _purge() { if (!_br) { return; // ignore any repeating purge requests } _br.init(null); _binstr = _info = _hm = _ep = _br = null; } _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/png', size: _binstr.length, width: _info.width, height: _info.height, purge: function() { _purge.call(this); } }); // for PNG we can safely trigger purge automatically, as we do not keep any data for later _purge.call(this); function _getChunkAt(idx) { var length, type, start, CRC; length = _br.LONG(idx); type = _br.STRING(idx += 4, 4); start = idx += 4; CRC = _br.LONG(idx + length); return { length: length, type: type, start: start, CRC: CRC }; } } return PNG; }); // Included from: src/javascript/runtime/html5/image/ImageInfo.js /** * ImageInfo.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ImageInfo @private */ define("moxie/runtime/html5/image/ImageInfo", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEG", "moxie/runtime/html5/image/PNG" ], function(Basic, x, JPEG, PNG) { /** Optional image investigation tool for HTML5 runtime. Provides the following features: - ability to distinguish image type (JPEG or PNG) by signature - ability to extract image width/height directly from it's internals, without preloading in memory (fast) - ability to extract APP headers from JPEGs (Exif, GPS, etc) - ability to replace width/height tags in extracted JPEG headers - ability to restore APP headers, that were for example stripped during image manipulation @class ImageInfo @constructor @param {String} binstr Image source as binary string */ return function(binstr) { var _cs = [JPEG, PNG], _img; // figure out the format, throw: ImageError.WRONG_FORMAT if not supported _img = (function() { for (var i = 0; i < _cs.length; i++) { try { return new _cs[i](binstr); } catch (ex) { // console.info(ex); } } throw new x.ImageError(x.ImageError.WRONG_FORMAT); }()); Basic.extend(this, { /** Image Mime Type extracted from it's depths @property type @type {String} @default '' */ type: '', /** Image size in bytes @property size @type {Number} @default 0 */ size: 0, /** Image width extracted from image source @property width @type {Number} @default 0 */ width: 0, /** Image height extracted from image source @property height @type {Number} @default 0 */ height: 0, /** Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs. @method setExif @param {String} tag Tag to set @param {Mixed} value Value to assign to the tag */ setExif: function() {}, /** Restores headers to the source. @method writeHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ writeHeaders: function(data) { return data; }, /** Strip all headers from the source. @method stripHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ stripHeaders: function(data) { return data; }, /** Dispose resources. @method purge */ purge: function() {} }); Basic.extend(this, _img); this.purge = function() { _img.purge(); _img = null; }; }; }); // Included from: src/javascript/runtime/html5/image/MegaPixel.js /** (The MIT License) Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.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. */ /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license */ /** @class moxie/runtime/html5/image/MegaPixel @private */ define("moxie/runtime/html5/image/MegaPixel", [], function() { /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options) { var iw = img.naturalWidth, ih = img.naturalHeight; var width = options.width, height = options.height; var x = options.x || 0, y = options.y || 0; var ctx = canvas.getContext('2d'); if (detectSubsampling(img)) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = detectVerticalSquash(img, iw, ih); var sy = 0; while (sy < ih) { var sh = sy + d > ih ? ih - sy : d; var sx = 0; while (sx < iw) { var sw = sx + d > iw ? iw - sx : d; tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); var dx = (sx * width / iw + x) << 0; var dw = Math.ceil(sw * width / iw); var dy = (sy * height / ih / vertSquashRatio + y) << 0; var dh = Math.ceil(sh * height / ih / vertSquashRatio); ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh); sx += d; } sy += d; } tmpCanvas = tmpCtx = null; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } canvas = null; var ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } return { isSubsampled: detectSubsampling, renderTo: renderImageToCanvas }; }); // Included from: src/javascript/runtime/html5/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/Image @private */ define("moxie/runtime/html5/image/Image", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/utils/Encode", "moxie/file/File", "moxie/runtime/html5/image/ImageInfo", "moxie/runtime/html5/image/MegaPixel", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, x, Encode, File, ImageInfo, MegaPixel, Mime, Env) { function HTML5Image() { var me = this , _img, _imgInfo, _canvas, _binStr, _blob , _modified = false // is set true whenever image is modified , _preserveHeaders = true ; Basic.extend(this, { loadFromBlob: function(blob) { var comp = this, I = comp.getRuntime() , asBinary = arguments.length > 1 ? arguments[1] : true ; if (!I.can('access_binary')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _blob = blob; if (blob.isDetached()) { _binStr = blob.getSource(); _preload.call(this, _binStr); return; } else { _readAsDataUrl.call(this, blob.getSource(), function(dataUrl) { if (asBinary) { _binStr = _toBinary(dataUrl); } _preload.call(comp, dataUrl); }); } }, loadFromImage: function(img, exact) { this.meta = img.meta; _blob = new File(null, { name: img.name, size: img.size, type: img.type }); _preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL()); }, getInfo: function() { var I = this.getRuntime(), info; if (!_imgInfo && _binStr && I.can('access_image_binary')) { _imgInfo = new ImageInfo(_binStr); } info = { width: _getImg().width || 0, height: _getImg().height || 0, type: _blob.type || Mime.getFileMime(_blob.name), size: _binStr && _binStr.length || _blob.size || 0, name: _blob.name || '', meta: _imgInfo && _imgInfo.meta || this.meta || {} }; return info; }, downsize: function() { _downsize.apply(this, arguments); }, getAsCanvas: function() { if (_canvas) { _canvas.id = this.uid + '_canvas'; } return _canvas; }, getAsBlob: function(type, quality) { if (type !== this.type) { // if different mime type requested prepare image for conversion _downsize.call(this, this.width, this.height, false); } return new File(null, { name: _blob.name || '', type: type, data: me.getAsBinaryString.call(this, type, quality) }); }, getAsDataURL: function(type) { var quality = arguments[1] || 90; // if image has not been modified, return the source right away if (!_modified) { return _img.src; } if ('image/jpeg' !== type) { return _canvas.toDataURL('image/png'); } else { try { // older Geckos used to result in an exception on quality argument return _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { return _canvas.toDataURL('image/jpeg'); } } }, getAsBinaryString: function(type, quality) { // if image has not been modified, return the source right away if (!_modified) { // if image was not loaded from binary string if (!_binStr) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } return _binStr; } if ('image/jpeg' !== type) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } else { var dataUrl; // if jpeg if (!quality) { quality = 90; } try { // older Geckos used to result in an exception on quality argument dataUrl = _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { dataUrl = _canvas.toDataURL('image/jpeg'); } _binStr = _toBinary(dataUrl); if (_imgInfo) { _binStr = _imgInfo.stripHeaders(_binStr); if (_preserveHeaders) { // update dimensions info in exif if (_imgInfo.meta && _imgInfo.meta.exif) { _imgInfo.setExif({ PixelXDimension: this.width, PixelYDimension: this.height }); } // re-inject the headers _binStr = _imgInfo.writeHeaders(_binStr); } // will be re-created from fresh on next getInfo call _imgInfo.purge(); _imgInfo = null; } } _modified = false; return _binStr; }, destroy: function() { me = null; _purge.call(this); this.getRuntime().getShim().removeInstance(this.uid); } }); function _getImg() { if (!_canvas && !_img) { throw new x.ImageError(x.DOMException.INVALID_STATE_ERR); } return _canvas || _img; } function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } function _toDataUrl(str, type) { return 'data:' + (type || '') + ';base64,' + Encode.btoa(str); } function _preload(str) { var comp = this; _img = new Image(); _img.onerror = function() { _purge.call(this); comp.trigger('error', x.ImageError.WRONG_FORMAT); }; _img.onload = function() { comp.trigger('load'); }; _img.src = /^data:[^;]*;base64,/.test(str) ? str : _toDataUrl(str, _blob.type); } function _readAsDataUrl(file, callback) { var comp = this, fr; // use FileReader if it's available if (window.FileReader) { fr = new FileReader(); fr.onload = function() { callback(this.result); }; fr.onerror = function() { comp.trigger('error', x.ImageError.WRONG_FORMAT); }; fr.readAsDataURL(file); } else { return callback(file.getAsDataURL()); } } function _downsize(width, height, crop, preserveHeaders) { var self = this , scale , mathFn , x = 0 , y = 0 , img , destWidth , destHeight , orientation ; _preserveHeaders = preserveHeaders; // we will need to check this on export (see getAsBinaryString()) // take into account orientation tag orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1; if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation // swap dimensions var tmp = width; width = height; height = tmp; } img = _getImg(); // unify dimensions if (!crop) { scale = Math.min(width/img.width, height/img.height); } else { // one of the dimensions may exceed the actual image dimensions - we need to take the smallest value width = Math.min(width, img.width); height = Math.min(height, img.height); scale = Math.max(width/img.width, height/img.height); } // we only downsize here if (scale > 1 && !crop && preserveHeaders) { this.trigger('Resize'); return; } // prepare canvas if necessary if (!_canvas) { _canvas = document.createElement("canvas"); } // calculate dimensions of proportionally resized image destWidth = Math.round(img.width * scale); destHeight = Math.round(img.height * scale); // scale image and canvas if (crop) { _canvas.width = width; _canvas.height = height; // if dimensions of the resulting image still larger than canvas, center it if (destWidth > width) { x = Math.round((destWidth - width) / 2); } if (destHeight > height) { y = Math.round((destHeight - height) / 2); } } else { _canvas.width = destWidth; _canvas.height = destHeight; } // rotate if required, according to orientation tag if (!_preserveHeaders) { _rotateToOrientaion(_canvas.width, _canvas.height, orientation); } _drawToCanvas.call(this, img, _canvas, -x, -y, destWidth, destHeight); this.width = _canvas.width; this.height = _canvas.height; _modified = true; self.trigger('Resize'); } function _drawToCanvas(img, canvas, x, y, w, h) { if (Env.OS === 'iOS') { // avoid squish bug in iOS6 MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y }); } else { var ctx = canvas.getContext('2d'); ctx.drawImage(img, x, y, w, h); } } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag * @author Shinichi Tomita <shinichi.tomita@gmail.com> */ function _rotateToOrientaion(width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: _canvas.width = height; _canvas.height = width; break; default: _canvas.width = width; _canvas.height = height; } /** 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ var ctx = _canvas.getContext('2d'); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; } } function _purge() { if (_imgInfo) { _imgInfo.purge(); _imgInfo = null; } _binStr = _img = _canvas = _blob = null; _modified = false; } } return (extensions.Image = HTML5Image); }); // Included from: src/javascript/runtime/html4/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/image/Image @private */ define("moxie/runtime/html4/image/Image", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/image/Image" ], function(extensions, Image) { return (extensions.Image = Image); }); expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/image/Image","moxie/core/utils/Events"]); })(this);/** * o.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global moxie:true */ /** Globally exposed namespace with the most frequently used public classes and handy methods. @class o @static @private */ (function(exports) { "use strict"; var o = {}, inArray = exports.moxie.core.utils.Basic.inArray; // directly add some public classes // (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included) (function addAlias(ns) { var name, itemType; for (name in ns) { itemType = typeof(ns[name]); if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) { addAlias(ns[name]); } else if (itemType === 'function') { o[name] = ns[name]; } } })(exports.moxie); // add some manually o.Env = exports.moxie.core.utils.Env; o.Mime = exports.moxie.core.utils.Mime; o.Exceptions = exports.moxie.core.Exceptions; // expose globally exports.mOxie = o; if (!exports.o) { exports.o = o; } return o; })(this);
docs/app/Examples/elements/Segment/Variations/SegmentExampleVeryPadded.js
mohammed88/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExampleVeryPadded = () => ( <Segment padded='very'> Very padded content. </Segment> ) export default SegmentExampleVeryPadded
docs/src/pages/collections/GridPage.js
gocreating/react-tocas
import React from 'react'; import DemoPageLayout from '../../utils/DemoPageLayout'; import PlayGround from '../../utils/PlayGround'; import { Grid, Row, Column, } from '../../../../lib'; import './GridPage.css'; let GridPage = () => ( <DemoPageLayout title="Grid"> <h1 className="ts dividing header">Tutorial</h1> <PlayGround title="Basic" component={( <Grid> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> </Grid> )} /> <PlayGround title="Column" component={( <Grid> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={2} /> <Column wide={8} /> <Column wide={6} /> </Grid> )} /> <PlayGround title="Row" component={( <Grid> <Row> <Column wide={3} /> <Column wide={3} /> <Column wide={3} /> <Column wide={3} /> </Row> <Column wide={2} /> <Column wide={5} /> <Column wide={9} /> <Row> <Column wide={16} /> <Column wide={16} /> <Column wide={16} /> <Column wide={16} /> </Row> </Grid> )} /> <PlayGround title="Relaxed Grid" component={( <Grid relaxed> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> </Grid> )} /> <h1 className="ts dividing header">Column</h1> <PlayGround title="Automatically Newline" component={( <Grid> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> </Grid> )} /> <PlayGround title="Content" component={( <Grid column={3}> <Column> <div className="ts segment">Moon,</div> </Column> <Column> <div className="ts secondary segment">dalan!</div> </Column> <Column> <div className="ts tertiary segment">Hello</div> </Column> </Grid> )} /> <PlayGround title="Wide" component={( <Grid> <Column wide={1} /> <Column wide={15} /> <Column wide={3} /> <Column wide={13} /> <Column wide={6} /> <Column wide={10} /> <Column wide={4} /> <Column wide={12} /> <Column wide={16} /> </Grid> )} /> <h1 className="ts dividing header">Row</h1> <PlayGround title="Wide Split" component={( <Grid> <Row column={2}> <Column /> <Column /> </Row> </Grid> )} /> <PlayGround title="Floated Column" component={( <Grid column={4}> <Row column={4}> <Column left floated /> <Column right floated /> </Row> <Column /> <Column /> <Column /> <Column /> </Grid> )} /> <h1 className="ts dividing header">Grid</h1> <PlayGround title="Multiple Grid" component={( <Grid column={2}> <Column> <Grid column={4}> <Column /> <Column /> <Column /> <Column /> </Grid> </Column> <Column /> </Grid> )} /> <PlayGround title="Wide Split" component={( <Grid column={4}> <Row column={2}> <Column /> </Row> <Column /> <Column /> <Column /> <Column /> </Grid> )} /> <PlayGround title="Centered" component={( <Grid column={4} centered> <Column /> <Column /> </Grid> )} /> <PlayGround title="Aligned Content" component={( <Grid column={4} right aligned> <Column>right-aligned text</Column> <Row column={2} left aligned> <Column>left-aligned text</Column> <Column right aligned>right-aligned text</Column> </Row> </Grid> )} /> <h1 className="ts dividing header">RWD Grid</h1> <PlayGround title="Automatically Stacked" component={( <Grid stackable> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> <Column wide={4} /> </Grid> )} /> <PlayGround title="Reversed" component={( <Grid column={3} reversed> <Column>First</Column> <Column>Second</Column> <Column>Third</Column> </Grid> )} /> <PlayGround title="Doubling" component={( <Grid> <Row column={8} doubling> <Column /> <Column /> <Column /> <Column /> <Column /> <Column /> <Column /> <Column /> </Row> <Row column={6} doubling> <Column /> <Column /> <Column /> <Column /> <Column /> <Column /> </Row> <Row column={4} doubling> <Column /> <Column /> <Column /> <Column /> </Row> </Grid> )} /> <PlayGround title="Manually Adjust" notImplemented /> <PlayGround title="Manually Hide" notImplemented /> </DemoPageLayout> ); export default GridPage;
src/index.js
globmont/espionage
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import Game from './Game' import './index.css'; import { Router, Route, hashHistory } from 'react-router' ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={App}></Route> <Route path="game/:serverName" component={Game}></Route> </Router>, document.getElementById('root') );
ajax/libs/forerunnerdb/1.4.31/fdb-core+views.min.js
BenjaminVanRyseghem/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("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":33,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":8,"../lib/Shim.IE8":32}],3:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.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),g<0&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;f<l;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(g.value===-1)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),c===-1?(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},g.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))},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),c===-1&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;b<g;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":28,"./Shared":31}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a&&(this._store.push(a),this)},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):d.value===-1&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):b===-1?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b&&(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0)):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),b===-1&&this._right?this._right.remove(a):!(1!==b||!this._left)&&this._left.remove(a))},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c,d){var e=this._compareFunc(this._data,a);return d=d||[],0===e&&(this._left&&this._left.lookup(a,b,c,d),d.push(this._data),this._right&&this._right.lookup(a,b,c,d)),e===-1&&this._right&&this._right.lookup(a,b,c,d),1===e&&this._left&&this._left.lookup(a,b,c,d),d},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return d=d||[],void 0===d._visitedCount&&(d._visitedCount=0),d._visitedCount++,d._visitedNodes=d._visitedNodes||[],d._visitedNodes.push(h),g=this.sortAsc(i,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),g===-1&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&j!==-1))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":28,"./Shared":31}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){b=b||{},this.sharedPathSolver=o,this._primaryKey=b.primaryKey||"_id",this._primaryIndex=new g("primary",{primaryKey:this.primaryKey()}),this._primaryCrc=new g("primaryCrc",{primaryKey:this.primaryKey()}),this._crcLookup=new g("crcLookup",{primaryKey:this.primaryKey()}),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),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=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=a("./Condition"),o=new h,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;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],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._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),p.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,g=!a||void 0===a.$violationCheck||a.$violationCheck,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 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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){var a;if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary",{primaryKey:this.primaryKey()}),this._primaryCrc=new g("primaryCrc",{primaryKey:this.primaryKey()}),this._crcLookup=new g("crcLookup",{primaryKey:this.primaryKey()});for(a in this._indexByName)this._indexByName.hasOwnProperty(a)&&this._indexByName[a].rebuild();return this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" 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(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),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,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},p.prototype.filter=function(a,b,c){var d;return"function"==typeof a&&(c=a,a={},b={}),"function"==typeof b&&(c&&(d=c),c=b,b=d||{}),this.find(a,b).filter(c)},p.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},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b.$replace&&(c=c||{},c.$replace=!0,b=b.$replace),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},p.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(g._removeFromIndexes(d),i=g.updateObject(d,e,f.query,f.options,""),g._insertIntoIndexes(d),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):(g._removeFromIndexes(d),i=g.updateObject(d,b,a,c,""),g._insertIntoIndexes(d)),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length?(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length?(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this,f||[]),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f})):d&&d.call(this,f||[])):d&&d.call(this,f||[]),h.stop(),f||[]},p.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 this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b,c,d){var e,f={};return f[this._primaryKey]=a,d&&(e=function(a){d(a[0])}),this.update(f,b,c,e)[0]},p.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,r,s,t=!1,u=!1;if(d&&d.$replace===!0){g=!0,n=b,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);return t}for(s in b)if(b.hasOwnProperty(s)){if(g=!1,!g&&"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;j<k;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(!g&&this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;j<k;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;j<k;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(k<0)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;w<B;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$splicePull":if(void 0!==a[s]){if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePull from a key that is not an array! ("+s+")";if(l=b[s].$index,void 0===l)throw this.logIdentifier()+" Cannot splicePull without a $index integer value!";l<a[s].length&&(this._updateSplicePull(a[s],l),t=!0)}break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else a[s]instanceof Date?this._updateProperty(a,s,b[s]):(u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u);else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),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.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};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);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" 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)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i,failed:j}),this.deferEmit("change",{type:"insert",data:i,failed:j}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();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),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},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"Trigger cancelled operation";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"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" 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},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;c<f;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0===a.$decouple||a.$decouple,a.$explain=void 0!==a.$explain&&a.$explain,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=[].concat(c.indexMatch[0].lookup)||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&D.indexOf(o)===-1&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),b.$groupBy&&(x.data("flag.group",!0),x.time("group"),e=this.group(b.$groupBy,e),x.time("group")),x.stop(),e.__fdbOp=x, e.$cursor=G,e},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b&&(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c))},p.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}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):f.value===-1&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype.group=function(a,b){var c,d,e,f=o.parse(a,!0),g=new h,i={};if(f.length)for(d=0;d<f.length;d++)for(g.path(f[d].path),e=0;e<b.length;e++)c=g.get(b[e]),i[c]=i[c]||[],i[c].push(b[e]);return i},p.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(f.value!==-1)throw this.logIdentifier()+" $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)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=[].concat(this._primaryIndex.lookup(a,b,c)),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=[].concat(m.lookup(a,b,c)),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.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(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=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._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;e<j;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.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()},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else 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"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){if(this._indexByName)return this._indexByName[a]},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" 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;c<e;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;c<e;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"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.dataSet),c.update({},e)):c.insert(d.data.dataSet);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.dataSet)}})},"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!"}}),p.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!"},p.prototype.when=function(a){var b=this.objectId();return this._when=this._when||{},this._when[b]=this._when[b]||new n(this,b,a),this._when[b]},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):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=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(!a||a.autoCreate!==!1){if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.deferEmit("create",b._collection[c],"collection",c),this._collection[c]}if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!"}else if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked&&b.isLinked()}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked&&b.isLinked()}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Condition":7,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[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"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),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"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&this._collections.indexOf(a)===-1){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" 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);c!==-1&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),b!==-1&&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.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);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(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.deferEmit("create",b._collectionGroup[a],"collectionGroup",a),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":5,"./Shared":31}],7:[function(a,b,c){"use strict";var d,e;d=a("./Shared"),e=function(){this.init.apply(this,arguments)},e.prototype.init=function(a,b,c){this._dataSource=a,this._id=b,this._query=[c],this._started=!1,this._state=[!1],this._satisfied=!1,this.earlyExit(!0)},d.addModule("Condition",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"id"),d.synthesize(e.prototype,"then"),d.synthesize(e.prototype,"else"),d.synthesize(e.prototype,"earlyExit"),d.synthesize(e.prototype,"debug"),e.prototype.and=function(a){return this._query.push(a),this._state.push(!1),this},e.prototype.start=function(a){if(!this._started){var b=this;0!==arguments.length&&(this._satisfied=a),this._updateStates(),b._onChange=function(){b._updateStates()},this._dataSource.on("change",b._onChange),this._started=!0}return this},e.prototype._updateStates=function(){var a,b=!0;for(a=0;a<this._query.length&&(this._state[a]=this._dataSource.count(this._query[a])>0,this._debug&&console.log(this.logIdentifier()+" Evaluating",this._query[a],"=",this._query[a]),this._state[a]||(b=!1,!this._earlyExit));a++);this._satisfied!==b&&(b?this._then&&this._then():this._else&&this._else(),this._satisfied=b)},e.prototype.stop=function(){return this._started&&(this._dataSource.off("change",this._onChange),delete this._onChange,this._started=!1),this},e.prototype.drop=function(){return this.stop(),delete this._dataSource.when[this._id],this},d.finishModule("Condition"),b.exports=e},{"./Shared":31}],8:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.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&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)&&(b&&b(),!0):d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.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=i},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],9:[function(a,b,c){"use strict";var d,e,f,g,h;d=a("./Shared"),h=a("./Overload");var i=function(a,b){this.init.apply(this,arguments)};i.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",i),i.prototype.moduleLoaded=new h({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)&&(b&&b(),!0):d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.shared=d,i.prototype.shared=d,d.addModule("Db",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Constants"),d.mixin(i.prototype,"Mixin.Tags"),d.mixin(i.prototype,"Mixin.Events"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),i.prototype._isServer=!1,d.synthesize(i.prototype,"core"),d.synthesize(i.prototype,"primaryKey"),d.synthesize(i.prototype,"state"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.arrayToCollection=function(a){return(new f).setData(a)},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},i.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},i.prototype.drop=new h({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;a<c;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},function:function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;b<d;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},boolean:function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;b<d;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;c<e;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof i?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new i(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),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},d.finishModule("Db"),b.exports=i},{"./Collection.js":5,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(a,b,c){"use strict";var d,e,f,g,h=Math.PI/180,i=180/Math.PI,j=6371;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var k=function(){};k.prototype.radians=function(a){return a*h},k.prototype.degrees=function(a){return a*i},k.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},k.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},k.prototype.calculateLatLngByDistanceBearing=function(a,b,c){var d=a[1],e=a[0],f=Math.asin(Math.sin(this.radians(e))*Math.cos(b/j)+Math.cos(this.radians(e))*Math.sin(b/j)*Math.cos(this.radians(c))),g=this.radians(d)+Math.atan2(Math.sin(this.radians(c))*Math.sin(b/j)*Math.cos(this.radians(e)),Math.cos(b/j)-Math.sin(this.radians(e))*Math.sin(f)),h=(g+3*Math.PI)%(2*Math.PI)-Math.PI;return{lat:this.degrees(f),lng:this.degrees(h)}},k.prototype.calculateExtentByRadius=function(a,b){var c,d,e,f,g=[],h=[];return e=this.calculateLatLngByDistanceBearing(a,b,0),d=this.calculateLatLngByDistanceBearing(a,b,90),f=this.calculateLatLngByDistanceBearing(a,b,180),c=this.calculateLatLngByDistanceBearing(a,b,270),g[0]=e.lat,g[1]=f.lat,h[0]=c.lng,h[1]=d.lng,{lat:g,lng:h}},k.prototype.calculateHashArrayByRadius=function(a,b,c){var d,e,f,g=this.calculateExtentByRadius(a,b),h=[g.lat[0],g.lng[0]],i=[g.lat[0],g.lng[1]],j=[g.lat[1],g.lng[0]],k=this.encode(h[0],h[1],c),l=this.encode(i[0],i[1],c),m=this.encode(j[0],j[1],c),n=0,o=0,p=[];for(d=k,p.push(d);d!==l;)d=this.calculateAdjacent(d,"right"),n++,p.push(d);for(d=k;d!==m;)d=this.calculateAdjacent(d,"bottom"),o++;for(e=0;e<=n;e++)for(d=p[e],f=0;f<o;f++)d=this.calculateAdjacent(d,"bottom"),p.push(d);return p},k.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return g[b][d].indexOf(c)!==-1&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},k.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;g<5;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{lat:l,lng:m}},k.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,j<4?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=!(!b||!b.debug)&&b.debug,this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.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.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return!!this._btree.insert(a)&&(this._size++,!0)},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),!!this._btree.remove(a)&&(this._size--,!0)},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b,c){var d,e,f,g,i=this._btree.keys();for(g=0;g<i.length;g++)if(d=i[g].path,e=h.get(a,d),"object"==typeof e)return e.$near&&(f=[],f=f.concat(this.near(d,e.$near,b,c))),e.$geoWithin&&(f=[],f=f.concat(this.geoWithin(d,e.$geoWithin,b,c))),f;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c,d){var e,f,g,k,l,m,n,o,p,q,r,s,t=this,u=[],v=this._collection.primaryKey();if("km"===b.$distanceUnits){for(o=b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}}else if("miles"===b.$distanceUnits)for(o=1.60934*b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}for(0===n&&(n=1),d&&d.time("index2d.calculateHashArea"),e=i.calculateHashArrayByRadius(b.$point,o,n),d&&d.time("index2d.calculateHashArea"),d&&(d.data("index2d.near.precision",n),d.data("index2d.near.hashArea",e),d.data("index2d.near.maxDistanceKm",o),d.data("index2d.near.centerPointCoords",[b.$point[0],b.$point[1]])),m=[],f=0,k={},g=[],d&&d.time("index2d.near.getDocsInsideHashArea"),s=0;s<e.length;s++)l=this._btree.startsWith(a,e[s]),k[e[s]]=l,f+=l._visitedCount,g=g.concat(l._visitedNodes),m=m.concat(l);if(d&&(d.time("index2d.near.getDocsInsideHashArea"),d.data("index2d.near.startsWith",k),d.data("index2d.near.visitedTreeNodes",g)),d&&d.time("index2d.near.lookupDocsById"),m=this._collection._primaryIndex.lookup(m),d&&d.time("index2d.near.lookupDocsById"),b.$distanceField&&(m=this.decouple(m)),m.length){for(p={},d&&d.time("index2d.near.calculateDistanceFromCenter"),s=0;s<m.length;s++)r=h.get(m[s],a),q=p[m[s][v]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],r[0],r[1]),q<=o&&(b.$distanceField&&h.set(m[s],b.$distanceField,"km"===b.$distanceUnits?q:Math.round(.621371*q)),b.$geoHashField&&h.set(m[s],b.$geoHashField,i.encode(r[0],r[1],n)),u.push(m[s]));d&&d.time("index2d.near.calculateDistanceFromCenter"),d&&d.time("index2d.near.sortResultsByDistance"),u.sort(function(a,b){return t.sortAsc(p[a[v]],p[b[v]])}),d&&d.time("index2d.near.sortResultsByDistance")}return u},k.prototype.geoWithin=function(a,b,c){return console.log("geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array."),[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.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},k.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},k.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.index["2d"]=k, d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=!(!b||!b.debug)&&b.debug,this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},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.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;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=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),!!this._btree.insert(a)&&(this._size++,!0)},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),!!this._btree.remove(a)&&(this._size--,!0)},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,b,c){return this._btree.lookup(a,b,c)},g.prototype.match=function(a,b){return this._btree.match(a,b)},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.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[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),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._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;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.update=function(a,b){},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]||[];c.indexOf(b)===-1&&(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;b<f;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],c.indexOf(b)===-1&&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.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":28,"./Shared":31}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b){this.init.apply(this,arguments)};e.prototype.init=function(a,b){b=b||{},this._name=a,this._data={},this._primaryKey=b.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,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;b<c;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(void 0!==a[e]&&null!==a[e])return this.lookup(a[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)},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":31}],15:[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":26,"./Shared":31}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);b===-1&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainEnabled:function(a){return void 0!==a?(this._chainDisabled=!a,this):!this._chainDisabled},chainWillSend:function(){return Boolean(this._chain&&!this._chainDisabled)},chainSend:function(a,b,c){if(this._chain&&!this._chainDisabled){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;e<g;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))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!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e,f=0,g=a("./Overload"),h=a("./Serialiser"),i=new h;e=function(){var a,b,c,d=[];for(b=0;b<256;b++){for(a=b,c=0;c<8;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),d={serialiser:i,make:function(a){return i.convert(a)},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]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;c<b;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,i.reviver())},jStringify:JSON.stringify,objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,e=0,g=a.length;for(d=0;d<g;d++)e+=a.charCodeAt(d)*c;b=e.toString(16)}else f++,b=(f+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new g([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}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d},checksum:function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^e[255&(c^a.charCodeAt(b))];return(c^-1)>>>0}},b.exports=d},{"./Overload":27,"./Serialiser":30}],19:[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},{}],20:[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}}),once:new d({"string, function":function(a,b){var c=this,d=!1,e=function(){d||(c.off(a,e),b.apply(c,arguments),d=!0)};return this.on(a,e)},"string, *, function":function(a,b,c){var d=this,e=!1,f=function(){e||(d.off(a,b,f),c.apply(d,arguments),e=!0)};return this.on(a,b,f)}}),off:new d({string:function(a){var b=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){b.off(a)})):this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d,e=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){e.off(a,b)})):"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){var d=this;if(this._emitting)this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){d.off(a,b,c)});else if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var e=this._listeners[a][b],f=e.indexOf(c);f>-1&&e.splice(f,1)}},"string, *":function(a,b){var c=this;this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){c.off(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||{},this._emitting=!0,a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;c<d;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;c<d;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;i<h;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this._emitting=!1,this._processRemovalQueue(),this},_processRemovalQueue:function(){var a;if(this._eventRemovalQueue&&this._eventRemovalQueue.length){for(a=0;a<this._eventRemovalQueue.length;a++)this._eventRemovalQueue[a]();this._eventRemovalQueue=[]}},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":27}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)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],c,l,e));h++);if(g){if("or"===d)return!0}else o=!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],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)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],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return b<c;case"$lte":return b<=c;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;h<j;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;k<m;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$fastIn":return c instanceof Array?c.indexOf(b)!==-1:(console.log(this.logIdentifier()+" Cannot use an $fastIn operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},!e.$rootData["//distinctLookup"][n][b[n]]&&(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],22:[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:a<b?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:a<b?1:0}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],24:[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),e===-1&&(f.triggerStack={},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)},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},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b.export,e=b.import,d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g.export,c=g.import,b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!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)}}),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)}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&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,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;g<h;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,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;f<e;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":27}],25:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_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(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updateSplicePull:function(a,b,c){c||(c=1),a.splice(b,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,d=!1;if(a.length>0)if(b>0){for(c=0;c<b;c++)a.pop();d=!0}else if(b<0){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],26:[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":28,"./Shared":31}],27:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),f.indexOf("*")===-1)e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;c<d;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","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},{}],28:[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.Common"),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 b?f.push({path:g,value:a[d]}):f.push({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]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},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.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&b.indexOf(".")===-1)return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;k<f;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},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;i<e;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},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.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":31}],29:[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)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 this.isDropped()||(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),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":31}],30:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date&&(a.toJSON=function(){return"$date:"+this.toISOString()},!0)},function(b){if("string"==typeof b&&0===b.indexOf("$date:"))return a.convert(new Date(b.substr(6)))}),this.registerHandler("$regexp",function(a){return a instanceof RegExp&&(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0)},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],31:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.935",modules:{},plugins:{},index:{},_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.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,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:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),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:d,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"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./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(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);c<e;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],33:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return("setData"===g||"insert"===g||"update"===g||"remove"===g)&&(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,!!(c||d||e)&&(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),!f.dataArr.length&&!f.removeArr.length||(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0)))},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(a,b,c,d){var e={$and:[this.query(),a]};this._from.update.call(this._from,e,b,c,d)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),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()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;d<c;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;d<c;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;d<c;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.addTrigger=function(){return this._data.addTrigger.apply(this._data,arguments)},o.prototype.removeTrigger=function(){return this._data.removeTrigger.apply(this._data,arguments)},o.prototype.ignoreTriggers=function(){return this._data.ignoreTriggers.apply(this._data,arguments)},o.prototype.addLinkIO=function(){return this._data.addLinkIO.apply(this._data,arguments)},o.prototype.removeLinkIO=function(){return this._data.removeLinkIO.apply(this._data,arguments)},o.prototype.willTrigger=function(){return this._data.willTrigger.apply(this._data,arguments)},o.prototype.processTrigger=function(){return this._data.processTrigger.apply(this._data,arguments)},o.prototype._triggerIndexOf=function(){return this._data._triggerIndexOf.apply(this._data,arguments)},o.prototype.drop=function(a){return!this.isDropped()&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)},o.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(),void 0!==e&&this.emit("queryChange",e)},o.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(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this.decouple(this._querySettings.query)},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.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},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.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,d<0&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.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),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;d<c;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),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 this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(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){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.deferEmit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked&&a.isLinked()}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
learnyourreact/node_modules/react/dist/react-with-addons.min.js
roth1002/nodejs-practice
/** * React (with addons) v0.13.3 * * Copyright 2013-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. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){"use strict";var r=e(25),o=e(31),i=e(42),a=e(34),s=e(67),u=e(95),l=e(97),c=e(124),p=e(119),d=e(165);o.addons={CSSTransitionGroup:a,LinkedStateMixin:r,PureRenderMixin:i,TransitionGroup:u,batchedUpdates:l.batchedUpdates,classSet:c,cloneWithProps:p,createFragment:s.create,update:d},t.exports=o},{119:119,124:124,165:165,25:25,31:31,34:34,42:42,67:67,95:95,97:97}],2:[function(e,t,n){"use strict";var r=e(131),o={componentDidMount:function(){this.props.autoFocus&&r(this.getDOMNode())}};t.exports=o},{131:131}],3:[function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case P.topCompositionStart:return I.compositionStart;case P.topCompositionEnd:return I.compositionEnd;case P.topCompositionUpdate:return I.compositionUpdate}}function a(e,t){return e===P.topKeyDown&&t.keyCode===b}function s(e,t){switch(e){case P.topKeyUp:return-1!==E.indexOf(t.keyCode);case P.topKeyDown:return t.keyCode!==b;case P.topKeyPress:case P.topMouseDown:case P.topBlur:return!0;default:return!1}}function u(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function l(e,t,n,r){var o,l;if(_?o=i(e):w?s(e,r)&&(o=I.compositionEnd):a(e,r)&&(o=I.compositionStart),!o)return null;M&&(w||o!==I.compositionStart?o===I.compositionEnd&&w&&(l=w.getData()):w=v.getPooled(t));var c=g.getPooled(o,n,r);if(l)c.data=l;else{var p=u(r);null!==p&&(c.data=p)}return h.accumulateTwoPhaseDispatches(c),c}function c(e,t){switch(e){case P.topCompositionEnd:return u(t);case P.topKeyPress:var n=t.which;return n!==T?null:(R=!0,N);case P.topTextInput:var r=t.data;return r===N&&R?null:r;default:return null}}function p(e,t){if(w){if(e===P.topCompositionEnd||s(e,t)){var n=w.getData();return v.release(w),w=null,n}return null}switch(e){case P.topPaste:return null;case P.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case P.topCompositionEnd:return M?null:t.data;default:return null}}function d(e,t,n,r){var o;if(o=D?c(e,r):p(e,r),!o)return null;var i=y.getPooled(I.beforeInput,n,r);return i.data=o,h.accumulateTwoPhaseDispatches(i),i}var f=e(16),h=e(21),m=e(22),v=e(23),g=e(103),y=e(107),C=e(154),E=[9,13,27,32],b=229,_=m.canUseDOM&&"CompositionEvent"in window,x=null;m.canUseDOM&&"documentMode"in document&&(x=document.documentMode);var D=m.canUseDOM&&"TextEvent"in window&&!x&&!r(),M=m.canUseDOM&&(!_||x&&x>8&&11>=x),T=32,N=String.fromCharCode(T),P=f.topLevelTypes,I={beforeInput:{phasedRegistrationNames:{bubbled:C({onBeforeInput:null}),captured:C({onBeforeInputCapture:null})},dependencies:[P.topCompositionEnd,P.topKeyPress,P.topTextInput,P.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:C({onCompositionEnd:null}),captured:C({onCompositionEndCapture:null})},dependencies:[P.topBlur,P.topCompositionEnd,P.topKeyDown,P.topKeyPress,P.topKeyUp,P.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:C({onCompositionStart:null}),captured:C({onCompositionStartCapture:null})},dependencies:[P.topBlur,P.topCompositionStart,P.topKeyDown,P.topKeyPress,P.topKeyUp,P.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:C({onCompositionUpdate:null}),captured:C({onCompositionUpdateCapture:null})},dependencies:[P.topBlur,P.topCompositionUpdate,P.topKeyDown,P.topKeyPress,P.topKeyUp,P.topMouseDown]}},R=!1,w=null,O={eventTypes:I,extractEvents:function(e,t,n,r){return[l(e,t,n,r),d(e,t,n,r)]}};t.exports=O},{103:103,107:107,154:154,16:16,21:21,22:22,23:23}],4:[function(e,t,n){var r=e(147),o={addClass:function(e,t){return r(!/\s/.test(t)),t&&(e.classList?e.classList.add(t):o.hasClass(e,t)||(e.className=e.className+" "+t)),e},removeClass:function(e,t){return r(!/\s/.test(t)),t&&(e.classList?e.classList.remove(t):o.hasClass(e,t)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e},conditionClass:function(e,t,n){return(n?o.addClass:o.removeClass)(e,t)},hasClass:function(e,t){return r(!/\s/.test(t)),e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1}};t.exports=o},{147:147}],5:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},i=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){i.forEach(function(t){o[r(t,e)]=o[e]})});var a={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!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}},s={isUnitlessNumber:o,shorthandPropertyExpansions:a};t.exports=s},{}],6:[function(e,t,n){"use strict";var r=e(5),o=e(22),i=(e(118),e(125)),a=e(145),s=e(156),u=(e(166),s(function(e){return a(e)})),l="cssFloat";o.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(l="styleFloat");var c={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=u(n)+":",t+=i(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var a=i(o,t[o]);if("float"===o&&(o=l),a)n[o]=a;else{var s=r.shorthandPropertyExpansions[o];if(s)for(var u in s)n[u]="";else n[o]=""}}}};t.exports=c},{118:118,125:125,145:145,156:156,166:166,22:22,5:5}],7:[function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=e(30),i=e(29),a=e(147);i(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){a(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),t.exports=r},{147:147,29:29,30:30}],8:[function(e,t,n){"use strict";function r(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function o(e){var t=x.getPooled(P.change,R,e);E.accumulateTwoPhaseDispatches(t),_.batchedUpdates(i,t)}function i(e){C.enqueueEvents(e),C.processEventQueue()}function a(e,t){I=e,R=t,I.attachEvent("onchange",o)}function s(){I&&(I.detachEvent("onchange",o),I=null,R=null)}function u(e,t,n){return e===N.topChange?n:void 0}function l(e,t,n){e===N.topFocus?(s(),a(t,n)):e===N.topBlur&&s()}function c(e,t){I=e,R=t,w=e.value,O=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(I,"value",k),I.attachEvent("onpropertychange",d)}function p(){I&&(delete I.value,I.detachEvent("onpropertychange",d),I=null,R=null,w=null,O=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==w&&(w=t,o(e))}}function f(e,t,n){return e===N.topInput?n:void 0}function h(e,t,n){e===N.topFocus?(p(),c(t,n)):e===N.topBlur&&p()}function m(e,t,n){return e!==N.topSelectionChange&&e!==N.topKeyUp&&e!==N.topKeyDown||!I||I.value===w?void 0:(w=I.value,R)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===N.topClick?n:void 0}var y=e(16),C=e(18),E=e(21),b=e(22),_=e(97),x=e(105),D=e(148),M=e(150),T=e(154),N=y.topLevelTypes,P={change:{phasedRegistrationNames:{bubbled:T({onChange:null}),captured:T({onChangeCapture:null})},dependencies:[N.topBlur,N.topChange,N.topClick,N.topFocus,N.topInput,N.topKeyDown,N.topKeyUp,N.topSelectionChange]}},I=null,R=null,w=null,O=null,S=!1;b.canUseDOM&&(S=D("change")&&(!("documentMode"in document)||document.documentMode>8));var A=!1;b.canUseDOM&&(A=D("input")&&(!("documentMode"in document)||document.documentMode>9));var k={get:function(){return O.get.call(this)},set:function(e){w=""+e,O.set.call(this,e)}},L={eventTypes:P,extractEvents:function(e,t,n,o){var i,a;if(r(t)?S?i=u:a=l:M(t)?A?i=f:(i=m,a=h):v(t)&&(i=g),i){var s=i(e,t,n);if(s){var c=x.getPooled(P.change,s,o);return E.accumulateTwoPhaseDispatches(c),c}}a&&a(e,t,n)}};t.exports=L},{105:105,148:148,150:150,154:154,16:16,18:18,21:21,22:22,97:97}],9:[function(e,t,n){"use strict";var r=0,o={createReactRootIndex:function(){return r++}};t.exports=o},{}],10:[function(e,t,n){"use strict";function r(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var o=e(13),i=e(77),a=e(160),s=e(147),u={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:a,processUpdates:function(e,t){for(var n,u=null,l=null,c=0;c<e.length;c++)if(n=e[c],n.type===i.MOVE_EXISTING||n.type===i.REMOVE_NODE){var p=n.fromIndex,d=n.parentNode.childNodes[p],f=n.parentID;s(d),u=u||{},u[f]=u[f]||[],u[f][p]=d,l=l||[],l.push(d)}var h=o.dangerouslyRenderMarkup(t);if(l)for(var m=0;m<l.length;m++)l[m].parentNode.removeChild(l[m]);for(var v=0;v<e.length;v++)switch(n=e[v],n.type){case i.INSERT_MARKUP:r(n.parentNode,h[n.markupIndex],n.toIndex);break;case i.MOVE_EXISTING:r(n.parentNode,u[n.parentID][n.fromIndex],n.toIndex);break;case i.TEXT_CONTENT:a(n.parentNode,n.textContent);break;case i.REMOVE_NODE:}}};t.exports=u},{13:13,147:147,160:160,77:77}],11:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=e(147),i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},n=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},u=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var l in t){o(!s.isStandardName.hasOwnProperty(l)),s.isStandardName[l]=!0;var c=l.toLowerCase();if(s.getPossibleStandardName[c]=l,n.hasOwnProperty(l)){var p=n[l];s.getPossibleStandardName[p]=l,s.getAttributeName[l]=p}else s.getAttributeName[l]=c;s.getPropertyName[l]=a.hasOwnProperty(l)?a[l]:l,u.hasOwnProperty(l)?s.getMutationMethod[l]=u[l]:s.getMutationMethod[l]=null;var d=t[l];s.mustUseAttribute[l]=r(d,i.MUST_USE_ATTRIBUTE),s.mustUseProperty[l]=r(d,i.MUST_USE_PROPERTY),s.hasSideEffects[l]=r(d,i.HAS_SIDE_EFFECTS),s.hasBooleanValue[l]=r(d,i.HAS_BOOLEAN_VALUE),s.hasNumericValue[l]=r(d,i.HAS_NUMERIC_VALUE),s.hasPositiveNumericValue[l]=r(d,i.HAS_POSITIVE_NUMERIC_VALUE),s.hasOverloadedBooleanValue[l]=r(d,i.HAS_OVERLOADED_BOOLEAN_VALUE),o(!s.mustUseAttribute[l]||!s.mustUseProperty[l]),o(s.mustUseProperty[l]||!s.hasSideEffects[l]),o(!!s.hasBooleanValue[l]+!!s.hasNumericValue[l]+!!s.hasOverloadedBooleanValue[l]<=1)}}},a={},s={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=a[e];return r||(a[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:i};t.exports=s},{147:147}],12:[function(e,t,n){"use strict";function r(e,t){return null==t||o.hasBooleanValue[e]&&!t||o.hasNumericValue[e]&&isNaN(t)||o.hasPositiveNumericValue[e]&&1>t||o.hasOverloadedBooleanValue[e]&&t===!1}var o=e(11),i=e(158),a=(e(166),{createMarkupForID:function(e){return o.ID_ATTRIBUTE_NAME+"="+i(e)},createMarkupForProperty:function(e,t){if(o.isStandardName.hasOwnProperty(e)&&o.isStandardName[e]){if(r(e,t))return"";var n=o.getAttributeName[e];return o.hasBooleanValue[e]||o.hasOverloadedBooleanValue[e]&&t===!0?n:n+"="+i(t)}return o.isCustomAttribute(e)?null==t?"":e+"="+i(t):null},setValueForProperty:function(e,t,n){if(o.isStandardName.hasOwnProperty(t)&&o.isStandardName[t]){var i=o.getMutationMethod[t];if(i)i(e,n);else if(r(t,n))this.deleteValueForProperty(e,t);else if(o.mustUseAttribute[t])e.setAttribute(o.getAttributeName[t],""+n);else{var a=o.getPropertyName[t];o.hasSideEffects[t]&&""+e[a]==""+n||(e[a]=n)}}else o.isCustomAttribute(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){if(o.isStandardName.hasOwnProperty(t)&&o.isStandardName[t]){var n=o.getMutationMethod[t];if(n)n(e,void 0);else if(o.mustUseAttribute[t])e.removeAttribute(o.getAttributeName[t]);else{var r=o.getPropertyName[t],i=o.getDefaultValueForProperty(e.nodeName,r);o.hasSideEffects[t]&&""+e[r]===i||(e[r]=i)}}else o.isCustomAttribute(t)&&e.removeAttribute(t)}});t.exports=a},{11:11,158:158,166:166}],13:[function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=e(22),i=e(123),a=e(126),s=e(139),u=e(147),l=/^(<[^ \/>]+)/,c="data-danger-index",p={dangerouslyRenderMarkup:function(e){u(o.canUseDOM);for(var t,n={},p=0;p<e.length;p++)u(e[p]),t=r(e[p]),t=s(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var d=[],f=0;for(t in n)if(n.hasOwnProperty(t)){var h,m=n[t];for(h in m)if(m.hasOwnProperty(h)){var v=m[h];m[h]=v.replace(l,"$1 "+c+'="'+h+'" ')}for(var g=i(m.join(""),a),y=0;y<g.length;++y){var C=g[y];C.hasAttribute&&C.hasAttribute(c)&&(h=+C.getAttribute(c),C.removeAttribute(c),u(!d.hasOwnProperty(h)),d[h]=C,f+=1)}}return u(f===d.length),u(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){u(o.canUseDOM),u(t),u("html"!==e.tagName.toLowerCase());var n=i(t,a)[0];e.parentNode.replaceChild(n,e)}};t.exports=p},{123:123,126:126,139:139,147:147,22:22}],14:[function(e,t,n){"use strict";var r=e(154),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null}),r({AnalyticsEventPlugin:null}),r({MobileSafariClickEventPlugin:null})];t.exports=o},{154:154}],15:[function(e,t,n){"use strict";var r=e(16),o=e(21),i=e(109),a=e(75),s=e(154),u=r.topLevelTypes,l=a.getFirstReactDOM,c={mouseEnter:{registrationName:s({onMouseEnter:null}),dependencies:[u.topMouseOut,u.topMouseOver]},mouseLeave:{registrationName:s({onMouseLeave:null}),dependencies:[u.topMouseOut,u.topMouseOver]}},p=[null,null],d={eventTypes:c,extractEvents:function(e,t,n,r){if(e===u.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==u.topMouseOut&&e!==u.topMouseOver)return null;var s;if(t.window===t)s=t;else{var d=t.ownerDocument;s=d?d.defaultView||d.parentWindow:window}var f,h;if(e===u.topMouseOut?(f=t,h=l(r.relatedTarget||r.toElement)||s):(f=s,h=t),f===h)return null;var m=f?a.getID(f):"",v=h?a.getID(h):"",g=i.getPooled(c.mouseLeave,m,r);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=i.getPooled(c.mouseEnter,v,r);return y.type="mouseenter",y.target=h,y.relatedTarget=f,o.accumulateEnterLeaveDispatches(g,y,m,v),p[0]=g,p[1]=y,p}};t.exports=d},{109:109,154:154,16:16,21:21,75:75}],16:[function(e,t,n){"use strict";var r=e(153),o=r({bubbled:null,captured:null}),i=r({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,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};t.exports=a},{153:153}],17:[function(e,t,n){var r=e(126),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};t.exports=o},{126:126}],18:[function(e,t,n){"use strict";var r=e(19),o=e(20),i=e(115),a=e(132),s=e(147),u={},l=null,c=function(e){if(e){var t=o.executeDispatch,n=r.getPluginModuleForEvent(e);n&&n.executeDispatch&&(t=n.executeDispatch),o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},p=null,d={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){p=e},getInstanceHandle:function(){return p},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){s(!n||"function"==typeof n);var r=u[t]||(u[t]={});r[e]=n},getListener:function(e,t){var n=u[t];return n&&n[e]},deleteListener:function(e,t){var n=u[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in u)delete u[t][e]},extractEvents:function(e,t,n,o){for(var a,s=r.plugins,u=0,l=s.length;l>u;u++){var c=s[u];if(c){var p=c.extractEvents(e,t,n,o);p&&(a=i(a,p))}}return a},enqueueEvents:function(e){e&&(l=i(l,e))},processEventQueue:function(){var e=l;l=null,a(e,c),s(!l)},__purge:function(){u={}},__getListenerBank:function(){return u}};t.exports=d},{115:115,132:132,147:147,19:19,20:20}],19:[function(e,t,n){"use strict";function r(){if(s)for(var e in u){var t=u[e],n=s.indexOf(e);if(a(n>-1),!l.plugins[n]){a(t.extractEvents),l.plugins[n]=t;var r=t.eventTypes;for(var i in r)a(o(r[i],t,i))}}}function o(e,t,n){a(!l.eventNameDispatchConfigs.hasOwnProperty(n)),l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var s=r[o];i(s,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){a(!l.registrationNameModules[e]),l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=e(147),s=null,u={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){a(!s),s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];u.hasOwnProperty(n)&&u[n]===o||(a(!u[n]),u[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=l.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=l},{147:147}],20:[function(e,t,n){"use strict";function r(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function o(e){return e===v.topMouseMove||e===v.topTouchMove}function i(e){return e===v.topMouseDown||e===v.topTouchStart}function a(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function s(e,t,n){e.currentTarget=m.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function u(e,t){a(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=l(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function p(e){var t=e._dispatchListeners,n=e._dispatchIDs;h(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function d(e){return!!e._dispatchListeners}var f=e(16),h=e(147),m={Mount:null,injectMount:function(e){m.Mount=e}},v=f.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:p,executeDispatch:s,executeDispatchesInOrder:u,executeDispatchesInOrderStopAtTrue:c,hasDispatches:d,injection:m,useTouchEvents:!1};t.exports=g},{147:147,16:16}],21:[function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return v(e,r)}function o(e,t,n){var o=t?m.bubbled:m.captured,i=r(e,n,o);i&&(n._dispatchListeners=f(n._dispatchListeners,i),n._dispatchIDs=f(n._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function a(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=v(e,r);o&&(n._dispatchListeners=f(n._dispatchListeners,o),n._dispatchIDs=f(n._dispatchIDs,e))}}function s(e){e&&e.dispatchConfig.registrationName&&a(e.dispatchMarker,null,e)}function u(e){h(e,i)}function l(e,t,n,r){d.injection.getInstanceHandle().traverseEnterLeave(n,r,a,e,t)}function c(e){h(e,s)}var p=e(16),d=e(18),f=e(115),h=e(132),m=p.PropagationPhases,v=d.getListener,g={accumulateTwoPhaseDispatches:u,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:l};t.exports=g},{115:115,132:132,16:16,18:18}],22:[function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=o},{}],23:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=e(30),i=e(29),a=e(142);i(r.prototype,{getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),o.addPoolingTo(r),t.exports=r},{142:142,29:29,30:30}],24:[function(e,t,n){"use strict";var r,o=e(11),i=e(22),a=o.injection.MUST_USE_ATTRIBUTE,s=o.injection.MUST_USE_PROPERTY,u=o.injection.HAS_BOOLEAN_VALUE,l=o.injection.HAS_SIDE_EFFECTS,c=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,d=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var f=document.implementation;r=f&&f.hasFeature&&f.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|u,allowTransparency:a,alt:null,async:u,autoComplete:null,autoPlay:u,cellPadding:null,cellSpacing:null,charSet:a,checked:s|u,classID:a,className:r?a:s,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:s|u,coords:null,crossOrigin:null,data:null,dateTime:a,defer:u,dir:null,disabled:a|u,download:d,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:u,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|u,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:s,label:null,lang:null,list:a,loop:s|u,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,multiple:s|u,muted:s|u,name:null,noValidate:u,open:u,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:s|u,rel:null,required:u,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:u,scrolling:null,seamless:a|u,selected:s|u,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:s,srcSet:a,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:s|l,width:a,wmode:a,autoCapitalize:null,autoCorrect:null,itemProp:a,itemScope:a|u,itemType:a,itemID:a,itemRef:a,property:null,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=h},{11:11,22:22}],25:[function(e,t,n){"use strict";var r=e(73),o=e(92),i={linkState:function(e){return new r(this.state[e],o.createStateKeySetter(this,e))}};t.exports=i},{73:73,92:92}],26:[function(e,t,n){"use strict";function r(e){l(null==e.props.checkedLink||null==e.props.valueLink)}function o(e){r(e),l(null==e.props.value&&null==e.props.onChange)}function i(e){r(e),l(null==e.props.checked&&null==e.props.onChange)}function a(e){this.props.valueLink.requestChange(e.target.value)}function s(e){this.props.checkedLink.requestChange(e.target.checked)}var u=e(84),l=e(147),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},p={Mixin:{propTypes:{value:function(e,t,n){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:u.func}},getValue:function(e){return e.props.valueLink?(o(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(i(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(o(e),a):e.props.checkedLink?(i(e),s):e.props.onChange}};t.exports=p},{147:147,84:84}],27:[function(e,t,n){"use strict";function r(e){e.remove()}var o=e(33),i=e(115),a=e(132),s=e(147),u={trapBubbledEvent:function(e,t){s(this.isMounted());var n=this.getDOMNode();s(n);var r=o.trapBubbledEvent(e,t,n);this._localEventListeners=i(this._localEventListeners,r)},componentWillUnmount:function(){this._localEventListeners&&a(this._localEventListeners,r)}};t.exports=u},{115:115,132:132,147:147,33:33}],28:[function(e,t,n){"use strict";var r=e(16),o=e(126),i=r.topLevelTypes,a={eventTypes:null,extractEvents:function(e,t,n,r){if(e===i.topTouchStart){var a=r.target;a&&!a.onclick&&(a.onclick=o)}}};t.exports=a},{126:126,16:16}],29:[function(e,t,n){"use strict";function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i){var a=Object(i);for(var s in a)r.call(a,s)&&(n[s]=a[s])}}return n}t.exports=r},{}],30:[function(e,t,n){"use strict";var r=e(147),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},s=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},u=function(e){var t=this;r(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,c=o,p=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=l),n.release=u,n},d={addPoolingTo:p,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fiveArgumentPooler:s};t.exports=d},{147:147}],31:[function(e,t,n){"use strict";var r=e(20),o=e(37),i=e(39),a=e(38),s=e(44),u=e(45),l=e(61),c=(e(62),e(46)),p=e(57),d=e(60),f=e(70),h=e(75),m=e(80),v=e(84),g=e(87),y=e(90),C=e(29),E=e(129),b=e(157);d.inject();var _=l.createElement,x=l.createFactory,D=l.cloneElement,M=m.measure("React","render",h.render),T={Children:{map:o.map,forEach:o.forEach,count:o.count,only:b},Component:i,DOM:c,PropTypes:v,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:a.createClass,createElement:_,cloneElement:D,createFactory:x,createMixin:function(e){return e},constructAndRenderComponent:h.constructAndRenderComponent,constructAndRenderComponentByID:h.constructAndRenderComponentByID,findDOMNode:E,render:M,renderToString:y.renderToString,renderToStaticMarkup:y.renderToStaticMarkup,unmountComponentAtNode:h.unmountComponentAtNode,isValidElement:l.isValidElement,withContext:s.withContext,__spread:C};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:u,InstanceHandles:f,Mount:h,Reconciler:g,TextComponent:p});T.version="0.13.3",t.exports=T},{129:129,157:157,20:20,29:29,37:37,38:38,39:39,44:44,45:45,46:46,57:57,60:60,61:61,62:62,70:70,75:75,80:80,84:84,87:87,90:90}],32:[function(e,t,n){"use strict";var r=e(129),o={getDOMNode:function(){return r(this)}};t.exports=o},{129:129}],33:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=f++,p[e[m]]={}),p[e[m]]}var o=e(16),i=e(18),a=e(19),s=e(65),u=e(114),l=e(29),c=e(148),p={},d=!1,f=0,h={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",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),v=l({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e; }},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),s=a.registrationNameDependencies[e],u=o.topLevelTypes,l=0,p=s.length;p>l;l++){var d=s[l];i.hasOwnProperty(d)&&i[d]||(d===u.topWheel?c("wheel")?v.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",n):c("mousewheel")?v.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",n):v.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",n):d===u.topScroll?c("scroll",!0)?v.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",n):v.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",v.ReactEventListener.WINDOW_HANDLE):d===u.topFocus||d===u.topBlur?(c("focus",!0)?(v.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",n),v.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",n)):c("focusin")&&(v.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",n),v.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",n)),i[u.topBlur]=!0,i[u.topFocus]=!0):h.hasOwnProperty(d)&&v.ReactEventListener.trapBubbledEvent(d,h[d],n),i[d]=!0)}},trapBubbledEvent:function(e,t,n){return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!d){var e=u.refreshScrollValues;v.ReactEventListener.monitorScrollValue(e),d=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});t.exports=v},{114:114,148:148,16:16,18:18,19:19,29:29,65:65}],34:[function(e,t,n){"use strict";var r=e(31),o=e(29),i=r.createFactory(e(95)),a=r.createFactory(e(35)),s=r.createClass({displayName:"ReactCSSTransitionGroup",propTypes:{transitionName:r.PropTypes.string.isRequired,transitionAppear:r.PropTypes.bool,transitionEnter:r.PropTypes.bool,transitionLeave:r.PropTypes.bool},getDefaultProps:function(){return{transitionAppear:!1,transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(e){return a({name:this.props.transitionName,appear:this.props.transitionAppear,enter:this.props.transitionEnter,leave:this.props.transitionLeave},e)},render:function(){return i(o({},this.props,{childFactory:this._wrapChild}))}});t.exports=s},{29:29,31:31,35:35,95:95}],35:[function(e,t,n){"use strict";var r=e(31),o=e(4),i=e(94),a=e(157),s=(e(166),17),u=r.createClass({displayName:"ReactCSSTransitionGroupChild",transition:function(e,t){var n=this.getDOMNode(),r=this.props.name+"-"+e,a=r+"-active",s=function(e){e&&e.target!==n||(o.removeClass(n,r),o.removeClass(n,a),i.removeEndEventListener(n,s),t&&t())};i.addEndEventListener(n,s),o.addClass(n,r),this.queueClass(a)},queueClass:function(e){this.classNameQueue.push(e),this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,s))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(o.addClass.bind(o,this.getDOMNode())),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout)},componentWillAppear:function(e){this.props.appear?this.transition("appear",e):e()},componentWillEnter:function(e){this.props.enter?this.transition("enter",e):e()},componentWillLeave:function(e){this.props.leave?this.transition("leave",e):e()},render:function(){return a(this.props.children)}});t.exports=u},{157:157,166:166,31:31,4:4,94:94}],36:[function(e,t,n){"use strict";var r=e(87),o=e(130),i=e(146),a=e(162),s={instantiateChildren:function(e,t,n){var r=o(e);for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=i(s,null);r[a]=u}return r},updateChildren:function(e,t,n,s){var u=o(t);if(!u&&!e)return null;var l;for(l in u)if(u.hasOwnProperty(l)){var c=e&&e[l],p=c&&c._currentElement,d=u[l];if(a(p,d))r.receiveComponent(c,d,n,s),u[l]=c;else{c&&r.unmountComponent(c,l);var f=i(d,null);u[l]=f}}for(l in e)!e.hasOwnProperty(l)||u&&u.hasOwnProperty(l)||r.unmountComponent(e[l]);return u},unmountChildren:function(e){for(var t in e){var n=e[t];r.unmountComponent(n)}}};t.exports=s},{130:130,146:146,162:162,87:87}],37:[function(e,t,n){"use strict";function r(e,t){this.forEachFunction=e,this.forEachContext=t}function o(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function i(e,t,n){if(null==e)return e;var i=r.getPooled(t,n);f(e,o,i),r.release(i)}function a(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function s(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var s=o.mapFunction.call(o.mapContext,t,r);i[n]=s}}function u(e,t,n){if(null==e)return e;var r={},o=a.getPooled(r,t,n);return f(e,s,o),a.release(o),d.create(r)}function l(e,t,n,r){return null}function c(e,t){return f(e,l,null)}var p=e(30),d=e(67),f=e(164),h=(e(166),p.twoArgumentPooler),m=p.threeArgumentPooler;p.addPoolingTo(r,h),p.addPoolingTo(a,m);var v={forEach:i,map:u,count:c};t.exports=v},{164:164,166:166,30:30,67:67}],38:[function(e,t,n){"use strict";function r(e,t){var n=D.hasOwnProperty(t)?D[t]:null;T.hasOwnProperty(t)&&y(n===_.OVERRIDE_BASE),e.hasOwnProperty(t)&&y(n===_.DEFINE_MANY||n===_.DEFINE_MANY_MERGED)}function o(e,t){if(t){y("function"!=typeof t),y(!d.isValidElement(t));var n=e.prototype;t.hasOwnProperty(b)&&M.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==b){var i=t[o];if(r(n,o),M.hasOwnProperty(o))M[o](e,i);else{var a=D.hasOwnProperty(o),l=n.hasOwnProperty(o),c=i&&i.__reactDontBind,p="function"==typeof i,f=p&&!a&&!l&&!c;if(f)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=i,n[o]=i;else if(l){var h=D[o];y(a&&(h===_.DEFINE_MANY_MERGED||h===_.DEFINE_MANY)),h===_.DEFINE_MANY_MERGED?n[o]=s(n[o],i):h===_.DEFINE_MANY&&(n[o]=u(n[o],i))}else n[o]=i}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in M;y(!o);var i=n in e;y(!i),e[n]=r}}}function a(e,t){y(e&&t&&"object"==typeof e&&"object"==typeof t);for(var n in t)t.hasOwnProperty(n)&&(y(void 0===e[n]),e[n]=t[n]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function u(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function c(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=l(e,f.guard(n,e.constructor.displayName+"."+t))}}var p=e(39),d=(e(45),e(61)),f=e(64),h=e(71),m=e(72),v=(e(83),e(82),e(96)),g=e(29),y=e(147),C=e(153),E=e(154),b=(e(166),E({mixins:null})),_=C({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],D={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},M={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=g({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=g({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=s(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=g({},e.propTypes,t)},statics:function(e,t){i(e,t)}},T={replaceState:function(e,t){v.enqueueReplaceState(this,e),t&&v.enqueueCallback(this,t)},isMounted:function(){var e=h.get(this);return e&&e!==m.currentlyMountingInstance},setProps:function(e,t){v.enqueueSetProps(this,e),t&&v.enqueueCallback(this,t)},replaceProps:function(e,t){v.enqueueReplaceProps(this,e),t&&v.enqueueCallback(this,t)}},N=function(){};g(N.prototype,p.prototype,T);var P={createClass:function(e){var t=function(e,t){this.__reactAutoBindMap&&c(this),this.props=e,this.context=t,this.state=null;var n=this.getInitialState?this.getInitialState():null;y("object"==typeof n&&!Array.isArray(n)),this.state=n};t.prototype=new N,t.prototype.constructor=t,x.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),y(t.prototype.render);for(var n in D)t.prototype[n]||(t.prototype[n]=null);return t.type=t,t},injection:{injectMixin:function(e){x.push(e)}}};t.exports=P},{147:147,153:153,154:154,166:166,29:29,39:39,45:45,61:61,64:64,71:71,72:72,82:82,83:83,96:96}],39:[function(e,t,n){"use strict";function r(e,t){this.props=e,this.context=t}{var o=e(96),i=e(147);e(166)}r.prototype.setState=function(e,t){i("object"==typeof e||"function"==typeof e||null==e),o.enqueueSetState(this,e),t&&o.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){o.enqueueForceUpdate(this),e&&o.enqueueCallback(this,e)};t.exports=r},{147:147,166:166,96:96}],40:[function(e,t,n){"use strict";var r=e(50),o=e(75),i={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};t.exports=i},{50:50,75:75}],41:[function(e,t,n){"use strict";var r=e(147),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){r(!o),i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};t.exports=i},{147:147}],42:[function(e,t,n){"use strict";var r=e(161),o={shouldComponentUpdate:function(e,t){return!r(this.props,e)||!r(this.state,t)}};t.exports=o},{161:161}],43:[function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}var o=e(41),i=e(44),a=e(45),s=e(61),u=(e(62),e(71)),l=e(72),c=e(78),p=e(80),d=e(83),f=(e(82),e(87)),h=e(97),m=e(29),v=e(127),g=e(147),y=e(162),C=(e(166),1),E={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=C++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),o=this._processContext(this._currentElement._context),i=c.getComponentClassForElement(this._currentElement),a=new i(r,o);a.props=r,a.context=o,a.refs=v,this._instance=a,u.set(a,this);var s=a.state;void 0===s&&(a.state=s=null),g("object"==typeof s&&!Array.isArray(s)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var p,d,h=l.currentlyMountingInstance;l.currentlyMountingInstance=this;try{a.componentWillMount&&(a.componentWillMount(),this._pendingStateQueue&&(a.state=this._processPendingState(a.props,a.context))),p=this._getValidatedChildContext(n),d=this._renderValidatedComponent(p)}finally{l.currentlyMountingInstance=h}this._renderedComponent=this._instantiateReactComponent(d,this._currentElement.type);var m=f.mountComponent(this._renderedComponent,e,t,this._mergeChildContext(n,p));return a.componentDidMount&&t.getReactMountReady().enqueue(a.componentDidMount,a),m},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=l.currentlyUnmountingInstance;l.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{l.currentlyUnmountingInstance=t}}f.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,u.remove(e)},_setPropsInternal:function(e,t){var n=this._pendingElement||this._currentElement;this._pendingElement=s.cloneAndReplaceProps(n,m({},n.props,e)),h.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return v;var n=this._currentElement.type.contextTypes;if(!n)return v;t={};for(var r in n)t[r]=e[r];return t},_processContext:function(e){var t=this._maskContext(e);return t},_getValidatedChildContext:function(e){var t=this._instance,n=t.getChildContext&&t.getChildContext();if(n){g("object"==typeof t.constructor.childContextTypes);for(var r in n)g(r in t.constructor.childContextTypes);return n}return null},_mergeChildContext:function(e,t){return t?m({},e,t):e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{g("function"==typeof e[i]),a=e[i](t,i,o,n)}catch(s){a=s}a instanceof Error&&(r(this),n===d.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&f.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},_warnIfContextsDiffer:function(e,t){e=this._maskContext(e),t=this._maskContext(t);for(var n=Object.keys(t).sort(),r=(this.getName()||"ReactCompositeComponent",0);r<n.length;r++)n[r]},updateComponent:function(e,t,n,r,o){var i=this._instance,a=i.context,s=i.props;t!==n&&(a=this._processContext(n._context),s=this._processProps(n.props),i.componentWillReceiveProps&&i.componentWillReceiveProps(s,a));var u=this._processPendingState(s,a),l=this._pendingForceUpdate||!i.shouldComponentUpdate||i.shouldComponentUpdate(s,u,a);l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,s,u,a,e,o)):(this._currentElement=n,this._context=o,i.props=s,i.state=u,i.context=a)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=m({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];m(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a=this._instance,s=a.props,u=a.state,l=a.context;a.componentWillUpdate&&a.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,a.props=t,a.state=n,a.context=r,this._updateRenderedComponent(o,i),a.componentDidUpdate&&o.getReactMountReady().enqueue(a.componentDidUpdate.bind(a,s,u,l),a)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._getValidatedChildContext(),i=this._renderValidatedComponent(o);if(y(r,i))f.receiveComponent(n,i,e,this._mergeChildContext(t,o));else{var a=this._rootNodeID,s=n._rootNodeID;f.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(i,this._currentElement.type);var u=f.mountComponent(this._renderedComponent,a,e,this._mergeChildContext(t,o));this._replaceNodeWithMarkupByID(s,u)}},_replaceNodeWithMarkupByID:function(e,t){o.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(e){var t,n=i.current;i.current=this._mergeChildContext(this._currentElement._context,e),a.current=this;try{t=this._renderValidatedComponentWithoutOwnerOrContext()}finally{i.current=n,a.current=null}return g(null===t||t===!1||s.isValidElement(t)),t},attachRef:function(e,t){var n=this.getPublicInstance(),r=n.refs===v?n.refs={}:n.refs;r[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};p.measureMethods(E,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var b={Mixin:E};t.exports=b},{127:127,147:147,162:162,166:166,29:29,41:41,44:44,45:45,61:61,62:62,71:71,72:72,78:78,80:80,82:82,83:83,87:87,97:97}],44:[function(e,t,n){"use strict";var r=e(29),o=e(127),i=(e(166),{current:o,withContext:function(e,t){var n,o=i.current;i.current=r({},o,e);try{n=t()}finally{i.current=o}return n}});t.exports=i},{127:127,166:166,29:29}],45:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],46:[function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=e(61),i=(e(62),e(155)),a=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",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",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);t.exports=a},{155:155,61:61,62:62}],47:[function(e,t,n){"use strict";var r=e(2),o=e(32),i=e(38),a=e(61),s=e(153),u=a.createFactory("button"),l=s({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=i.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[r,o],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&l[t]||(e[t]=this.props[t]);return u(e,this.props.children)}});t.exports=c},{153:153,2:2,32:32,38:38,61:61}],48:[function(e,t,n){"use strict";function r(e){e&&(null!=e.dangerouslySetInnerHTML&&(g(null==e.children),g("object"==typeof e.dangerouslySetInnerHTML&&"__html"in e.dangerouslySetInnerHTML)),g(null==e.style||"object"==typeof e.style))}function o(e,t,n,r){var o=d.findReactContainerForID(e);if(o){var i=o.nodeType===D?o.ownerDocument:o;E(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function i(e){I.call(P,e)||(g(N.test(e)),P[e]=!0)}function a(e){i(e),this._tag=e,this._renderedChildren=null,this._previousStyleCopy=null,this._rootNodeID=null}var s=e(6),u=e(11),l=e(12),c=e(33),p=e(40),d=e(75),f=e(76),h=e(80),m=e(29),v=e(128),g=e(147),y=(e(148),e(154)),C=(e(166),c.deleteListener),E=c.listenTo,b=c.registrationNameModules,_={string:!0,number:!0},x=y({style:null}),D=1,M=null,T={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},N=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,P={},I={}.hasOwnProperty;a.displayName="ReactDOMComponent",a.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e,r(this._currentElement.props);var o=T[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t,n)+o},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,n="<"+this._tag;for(var r in t)if(t.hasOwnProperty(r)){var i=t[r];if(null!=i)if(b.hasOwnProperty(r))o(this._rootNodeID,r,i,e);else{r===x&&(i&&(i=this._previousStyleCopy=m({},t.style)),i=s.createMarkupForStyles(i));var a=l.createMarkupForProperty(r,i);a&&(n+=" "+a)}}if(e.renderToStaticMarkup)return n+">";var u=l.createMarkupForID(this._rootNodeID);return n+" "+u+">"},_createContentMarkup:function(e,t){var n="";("listing"===this._tag||"pre"===this._tag||"textarea"===this._tag)&&(n="\n");var r=this._currentElement.props,o=r.dangerouslySetInnerHTML;if(null!=o){if(null!=o.__html)return n+o.__html}else{var i=_[typeof r.children]?r.children:null,a=null!=i?null:r.children;if(null!=i)return n+v(i);if(null!=a){var s=this.mountChildren(a,e,t);return n+s.join("")}}return n},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,o){r(this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,o)},_updateDOMProperties:function(e,t){var n,r,i,a=this._currentElement.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===x){var s=this._previousStyleCopy;for(r in s)s.hasOwnProperty(r)&&(i=i||{},i[r]="");this._previousStyleCopy=null}else b.hasOwnProperty(n)?C(this._rootNodeID,n):(u.isStandardName[n]||u.isCustomAttribute(n))&&M.deletePropertyByID(this._rootNodeID,n);for(n in a){var l=a[n],c=n===x?this._previousStyleCopy:e[n];if(a.hasOwnProperty(n)&&l!==c)if(n===x)if(l?l=this._previousStyleCopy=m({},l):this._previousStyleCopy=null,c){for(r in c)!c.hasOwnProperty(r)||l&&l.hasOwnProperty(r)||(i=i||{},i[r]="");for(r in l)l.hasOwnProperty(r)&&c[r]!==l[r]&&(i=i||{},i[r]=l[r])}else i=l;else b.hasOwnProperty(n)?o(this._rootNodeID,n,l,t):(u.isStandardName[n]||u.isCustomAttribute(n))&&M.updatePropertyByID(this._rootNodeID,n,l)}i&&M.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t,n){var r=this._currentElement.props,o=_[typeof e.children]?e.children:null,i=_[typeof r.children]?r.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=r.dangerouslySetInnerHTML&&r.dangerouslySetInnerHTML.__html,u=null!=o?null:e.children,l=null!=i?null:r.children,c=null!=o||null!=a,p=null!=i||null!=s;null!=u&&null==l?this.updateChildren(null,t,n):c&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=s?a!==s&&M.updateInnerHTMLByID(this._rootNodeID,s):null!=l&&this.updateChildren(l,t,n)},unmountComponent:function(){this.unmountChildren(),c.deleteAllListeners(this._rootNodeID),p.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},h.measureMethods(a,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),m(a.prototype,a.Mixin,f.Mixin),a.injection={injectIDOperations:function(e){a.BackendIDOperations=M=e}},t.exports=a},{11:11,12:12,128:128,147:147,148:148,154:154,166:166,29:29,33:33,40:40,6:6,75:75,76:76,80:80}],49:[function(e,t,n){"use strict";var r=e(16),o=e(27),i=e(32),a=e(38),s=e(61),u=s.createFactory("form"),l=a.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[i,o],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(r.topLevelTypes.topSubmit,"submit")}});t.exports=l},{16:16,27:27,32:32,38:38,61:61}],50:[function(e,t,n){"use strict";var r=e(6),o=e(10),i=e(12),a=e(75),s=e(80),u=e(147),l=e(159),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},p={updatePropertyByID:function(e,t,n){var r=a.getNode(e);u(!c.hasOwnProperty(t)),null!=n?i.setValueForProperty(r,t,n):i.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=a.getNode(e);u(!c.hasOwnProperty(t)),i.deleteValueForProperty(r,t,n)},updateStylesByID:function(e,t){var n=a.getNode(e);r.setValueForStyles(n,t)},updateInnerHTMLByID:function(e,t){var n=a.getNode(e);l(n,t)},updateTextContentByID:function(e,t){var n=a.getNode(e);o.updateTextContent(n,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=a.getNode(e);o.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);o.processUpdates(e,t)}};s.measureMethods(p,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=p},{10:10,12:12,147:147,159:159,6:6,75:75,80:80}],51:[function(e,t,n){"use strict";var r=e(16),o=e(27),i=e(32),a=e(38),s=e(61),u=s.createFactory("iframe"),l=a.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[i,o],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load")}});t.exports=l},{16:16,27:27,32:32,38:38,61:61}],52:[function(e,t,n){"use strict";var r=e(16),o=e(27),i=e(32),a=e(38),s=e(61),u=s.createFactory("img"),l=a.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[i,o],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(r.topLevelTypes.topError,"error")}});t.exports=l},{16:16,27:27,32:32,38:38,61:61}],53:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var o=e(2),i=e(12),a=e(26),s=e(32),u=e(38),l=e(61),c=e(75),p=e(97),d=e(29),f=e(147),h=l.createFactory("input"),m={},v=u.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[o,a.Mixin,s],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=a.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=a.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,h(e,this.props.children)},componentDidMount:function(){var e=c.getID(this.getDOMNode());m[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=c.getID(e);delete m[t]},componentDidUpdate:function(e,t,n){var r=this.getDOMNode();null!=this.props.checked&&i.setValueForProperty(r,"checked",this.props.checked||!1);var o=a.getValue(this);null!=o&&i.setValueForProperty(r,"value",""+o)},_handleChange:function(e){var t,n=a.getOnChange(this);n&&(t=n.call(this,e)),p.asap(r,this);var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var i=this.getDOMNode(),s=i;s.parentNode;)s=s.parentNode;for(var u=s.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),l=0,d=u.length;d>l;l++){var h=u[l];if(h!==i&&h.form===i.form){var v=c.getID(h);f(v);var g=m[v];f(g),p.asap(r,g)}}}return t}});t.exports=v},{12:12,147:147,2:2,26:26,29:29,32:32,38:38,61:61,75:75,97:97}],54:[function(e,t,n){"use strict";var r=e(32),o=e(38),i=e(61),a=(e(166),i.createFactory("option")),s=o.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[r],componentWillMount:function(){},render:function(){return a(this.props,this.props.children)}});t.exports=s},{166:166,32:32,38:38,61:61}],55:[function(e,t,n){"use strict";function r(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=s.getValue(this);null!=e&&this.isMounted()&&i(this,e)}}function o(e,t,n){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function i(e,t){var n,r,o,i=e.getDOMNode().options;if(e.props.multiple){for(n={},r=0,o=t.length;o>r;r++)n[""+t[r]]=!0;for(r=0,o=i.length;o>r;r++){var a=n.hasOwnProperty(i[r].value);i[r].selected!==a&&(i[r].selected=a)}}else{for(n=""+t,r=0,o=i.length;o>r;r++)if(i[r].value===n)return void(i[r].selected=!0);i.length&&(i[0].selected=!0)}}var a=e(2),s=e(26),u=e(32),l=e(38),c=e(61),p=e(97),d=e(29),f=c.createFactory("select"),h=l.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[a,s.Mixin,u],propTypes:{defaultValue:o,value:o},render:function(){var e=d({},this.props);return e.onChange=this._handleChange,e.value=null,f(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentDidMount:function(){var e=s.getValue(this);null!=e?i(this,e):null!=this.props.defaultValue&&i(this,this.props.defaultValue)},componentDidUpdate:function(e){var t=s.getValue(this);null!=t?(this._pendingUpdate=!1,i(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?i(this,this.props.defaultValue):i(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,n=s.getOnChange(this);return n&&(t=n.call(this,e)),this._pendingUpdate=!0,p.asap(r,this),t}});t.exports=h},{2:2,26:26,29:29,32:32,38:38,61:61,97:97}],56:[function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0),u=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=u?0:s.toString().length,c=s.cloneRange();c.selectNodeContents(e),c.setEnd(s.startContainer,s.startOffset);var p=r(c.startContainer,c.startOffset,c.endContainer,c.endOffset),d=p?0:c.toString().length,f=d+l,h=document.createRange();h.setStart(n,o),h.setEnd(i,a);var m=h.collapsed;return{start:m?f:d,end:m?d:f}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=l(e,o),u=l(e,i);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=e(22),l=e(140),c=e(142),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:i,setOffsets:p?a:s};t.exports=d},{140:140,142:142,22:22}],57:[function(e,t,n){"use strict";var r=e(12),o=e(40),i=e(48),a=e(29),s=e(128),u=function(e){};a(u.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){this._rootNodeID=e;var o=s(this._stringText);return t.renderToStaticMarkup?o:"<span "+r.createMarkupForID(e)+">"+o+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e; n!==this._stringText&&(this._stringText=n,i.BackendIDOperations.updateTextContentByID(this._rootNodeID,n))}},unmountComponent:function(){o.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=u},{12:12,128:128,29:29,40:40,48:48}],58:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var o=e(2),i=e(12),a=e(26),s=e(32),u=e(38),l=e(61),c=e(97),p=e(29),d=e(147),f=(e(166),l.createFactory("textarea")),h=u.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[o,a.Mixin,s],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(d(null==e),Array.isArray(t)&&(d(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=a.getValue(this);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=p({},this.props);return d(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,f(e,this.state.initialValue)},componentDidUpdate:function(e,t,n){var r=a.getValue(this);if(null!=r){var o=this.getDOMNode();i.setValueForProperty(o,"value",""+r)}},_handleChange:function(e){var t,n=a.getOnChange(this);return n&&(t=n.call(this,e)),c.asap(r,this),t}});t.exports=h},{12:12,147:147,166:166,2:2,26:26,29:29,32:32,38:38,61:61,97:97}],59:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=e(97),i=e(113),a=e(29),s=e(126),u={initialize:s,close:function(){d.isBatchingUpdates=!1}},l={initialize:s,close:o.flushBatchedUpdates.bind(o)},c=[l,u];a(r.prototype,i.Mixin,{getTransactionWrappers:function(){return c}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o){var i=d.isBatchingUpdates;d.isBatchingUpdates=!0,i?e(t,n,r,o):p.perform(e,null,t,n,r,o)}};t.exports=d},{113:113,126:126,29:29,97:97}],60:[function(e,t,n){"use strict";function r(e){return h.createClass({tagName:e.toUpperCase(),render:function(){return new P(e,null,null,null,null,this.props)}})}function o(){R.EventEmitter.injectReactEventListener(I),R.EventPluginHub.injectEventPluginOrder(u),R.EventPluginHub.injectInstanceHandle(w),R.EventPluginHub.injectMount(O),R.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:L,EnterLeaveEventPlugin:l,ChangeEventPlugin:a,MobileSafariClickEventPlugin:d,SelectEventPlugin:A,BeforeInputEventPlugin:i}),R.NativeComponent.injectGenericComponentClass(g),R.NativeComponent.injectTextComponentClass(N),R.NativeComponent.injectAutoWrapper(r),R.Class.injectMixin(f),R.NativeComponent.injectComponentClasses({button:y,form:C,iframe:_,img:E,input:x,option:D,select:M,textarea:T,html:F("html"),head:F("head"),body:F("body")}),R.DOMProperty.injectDOMPropertyConfig(p),R.DOMProperty.injectDOMPropertyConfig(U),R.EmptyComponent.injectEmptyComponent("noscript"),R.Updates.injectReconcileTransaction(S),R.Updates.injectBatchingStrategy(v),R.RootIndex.injectCreateReactRootIndex(c.canUseDOM?s.createReactRootIndex:k.createReactRootIndex),R.Component.injectEnvironment(m),R.DOMComponent.injectIDOperations(b)}var i=e(3),a=e(8),s=e(9),u=e(14),l=e(15),c=e(22),p=e(24),d=e(28),f=e(32),h=e(38),m=e(40),v=e(59),g=e(48),y=e(47),C=e(49),E=e(52),b=e(50),_=e(51),x=e(53),D=e(54),M=e(55),T=e(58),N=e(57),P=e(61),I=e(66),R=e(68),w=e(70),O=e(75),S=e(86),A=e(99),k=e(100),L=e(101),U=e(98),F=e(122);t.exports={inject:o}},{100:100,101:101,122:122,14:14,15:15,22:22,24:24,28:28,3:3,32:32,38:38,40:40,47:47,48:48,49:49,50:50,51:51,52:52,53:53,54:54,55:55,57:57,58:58,59:59,61:61,66:66,68:68,70:70,75:75,8:8,86:86,9:9,98:98,99:99}],61:[function(e,t,n){"use strict";var r=e(44),o=e(45),i=e(29),a=(e(166),{key:!0,ref:!0}),s=function(e,t,n,r,o,i){this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=o,this.props=i};s.prototype={_isReactElement:!0},s.createElement=function(e,t,n){var i,u={},l=null,c=null;if(null!=t){c=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(u[i]=t[i])}var p=arguments.length-2;if(1===p)u.children=n;else if(p>1){for(var d=Array(p),f=0;p>f;f++)d[f]=arguments[f+2];u.children=d}if(e&&e.defaultProps){var h=e.defaultProps;for(i in h)"undefined"==typeof u[i]&&(u[i]=h[i])}return new s(e,l,c,o.current,r.current,u)},s.createFactory=function(e){var t=s.createElement.bind(null,e);return t.type=e,t},s.cloneAndReplaceProps=function(e,t){var n=new s(e.type,e.key,e.ref,e._owner,e._context,t);return n},s.cloneElement=function(e,t,n){var r,u=i({},e.props),l=e.key,c=e.ref,p=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,p=o.current),void 0!==t.key&&(l=""+t.key);for(r in t)t.hasOwnProperty(r)&&!a.hasOwnProperty(r)&&(u[r]=t[r])}var d=arguments.length-2;if(1===d)u.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];u.children=f}return new s(e.type,l,c,p,e._context,u)},s.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=s},{166:166,29:29,44:44,45:45}],62:[function(e,t,n){"use strict";function r(){if(y.current){var e=y.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e){var t=e&&e.getPublicInstance();if(!t)return void 0;var n=t.constructor;return n?n.displayName||n.name||void 0:void 0}function i(){var e=y.current;return e&&o(e)||void 0}function a(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,u('Each child in an array or iterator should have a unique "key" prop.',e,t))}function s(e,t,n){D.test(e)&&u("Child objects should have non-numeric keys so ordering is preserved.",t,n)}function u(e,t,n){var r=i(),a="string"==typeof n?n:n.displayName||n.name,s=r||a,u=_[e]||(_[e]={});if(!u.hasOwnProperty(s)){u[s]=!0;var l="";if(t&&t._owner&&t._owner!==y.current){var c=o(t._owner);l=" It was passed a child from "+c+"."}}}function l(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];m.isValidElement(r)&&a(r,t)}else if(m.isValidElement(e))e._store.validated=!0;else if(e){var o=E(e);if(o){if(o!==e.entries)for(var i,u=o.call(e);!(i=u.next()).done;)m.isValidElement(i.value)&&a(i.value,t)}else if("object"==typeof e){var l=v.extractIfFragment(e);for(var c in l)l.hasOwnProperty(c)&&s(c,l[c],t)}}}function c(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{b("function"==typeof t[i]),a=t[i](n,i,e,o)}catch(s){a=s}a instanceof Error&&!(a.message in x)&&(x[a.message]=!0,r(this))}}function p(e,t){var n=t.type,r="string"==typeof n?n:n.displayName,o=t._owner?t._owner.getPublicInstance().constructor.displayName:null,i=e+"|"+r+"|"+o;if(!M.hasOwnProperty(i)){M[i]=!0;var a="";r&&(a=" <"+r+" />");var s="";o&&(s=" The element was created by "+o+".")}}function d(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function f(e){if(e._store){var t=e._store.originalProps,n=e.props;for(var r in n)n.hasOwnProperty(r)&&(t.hasOwnProperty(r)&&d(t[r],n[r])||(p(r,e),t[r]=n[r]))}}function h(e){if(null!=e.type){var t=C.getComponentClassForElement(e),n=t.displayName||t.name;t.propTypes&&c(n,t.propTypes,e.props,g.prop),"function"==typeof t.getDefaultProps}}var m=e(61),v=e(67),g=e(83),y=(e(82),e(45)),C=e(78),E=e(138),b=e(147),_=(e(166),{}),x={},D=/^\d+$/,M={},T={checkAndWarnForMutatedProps:f,createElement:function(e,t,n){var r=m.createElement.apply(this,arguments);if(null==r)return r;for(var o=2;o<arguments.length;o++)l(arguments[o],e);return h(r),r},createFactory:function(e){var t=T.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=m.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)l(arguments[o],r.type);return h(r),r}};t.exports=T},{138:138,147:147,166:166,45:45,61:61,67:67,78:78,82:82,83:83}],63:[function(e,t,n){"use strict";function r(e){c[e]=!0}function o(e){delete c[e]}function i(e){return!!c[e]}var a,s=e(61),u=e(71),l=e(147),c={},p={injectEmptyComponent:function(e){a=s.createFactory(e)}},d=function(){};d.prototype.componentDidMount=function(){var e=u.get(this);e&&r(e._rootNodeID)},d.prototype.componentWillUnmount=function(){var e=u.get(this);e&&o(e._rootNodeID)},d.prototype.render=function(){return l(a),a()};var f=s.createElement(d),h={emptyElement:f,injection:p,isNullComponentID:i};t.exports=h},{147:147,61:61,71:71}],64:[function(e,t,n){"use strict";var r={guard:function(e,t){return e}};t.exports=r},{}],65:[function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue()}var o=e(18),i={handleTopLevel:function(e,t,n,i){var a=o.extractEvents(e,t,n,i);r(a)}};t.exports=i},{18:18}],66:[function(e,t,n){"use strict";function r(e){var t=p.getID(e),n=c.getReactRootIDFromNodeID(t),r=p.findReactContainerForID(n),o=p.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){for(var t=p.getFirstReactDOM(h(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=p.getID(t)||"";v._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function a(e){var t=m(window);e(t)}var s=e(17),u=e(22),l=e(30),c=e(70),p=e(75),d=e(97),f=e(29),h=e(137),m=e(143);f(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:u.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?s.listen(r,t,v.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?s.capture(r,t,v.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);s.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(v._enabled){var n=o.getPooled(e,t);try{d.batchedUpdates(i,n)}finally{o.release(n)}}}};t.exports=v},{137:137,143:143,17:17,22:22,29:29,30:30,70:70,75:75,97:97}],67:[function(e,t,n){"use strict";var r=(e(61),e(166),{create:function(e){return e},extract:function(e){return e},extractIfFragment:function(e){return e}});t.exports=r},{166:166,61:61}],68:[function(e,t,n){"use strict";var r=e(11),o=e(18),i=e(41),a=e(38),s=e(63),u=e(33),l=e(78),c=e(48),p=e(80),d=e(89),f=e(97),h={Component:i.injection,Class:a.injection,DOMComponent:c.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:o.injection,EventEmitter:u.injection,NativeComponent:l.injection,Perf:p.injection,RootIndex:d.injection,Updates:f.injection};t.exports=h},{11:11,18:18,33:33,38:38,41:41,48:48,63:63,78:78,80:80,89:89,97:97}],69:[function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=e(56),i=e(120),a=e(131),s=e(133),u={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:u.hasSelectionCapabilities(e)?u.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(u.hasSelectionCapabilities(n)&&u.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};t.exports=u},{120:120,131:131,133:133,56:56}],70:[function(e,t,n){"use strict";function r(e){return f+e.toString(36)}function o(e,t){return e.charAt(t)===f||t===e.length}function i(e){return""===e||e.charAt(0)===f&&e.charAt(e.length-1)!==f}function a(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function s(e){return e?e.substr(0,e.lastIndexOf(f)):""}function u(e,t){if(d(i(e)&&i(t)),d(a(e,t)),e===t)return e;var n,r=e.length+h;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function l(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))r=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,r);return d(i(s)),s}function c(e,t,n,r,o,i){e=e||"",t=t||"",d(e!==t);var l=a(t,e);d(l||a(e,t));for(var c=0,p=l?s:u,f=e;;f=p(f,t)){var h;if(o&&f===e||i&&f===t||(h=n(f,l,r)),h===!1||f===t)break;d(c++<m)}}var p=e(89),d=e(147),f=".",h=f.length,m=100,v={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===f&&e.length>1){var t=e.indexOf(f,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=l(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:l,_getNextDescendantID:u,isAncestorIDOf:a,SEPARATOR:f};t.exports=v},{147:147,89:89}],71:[function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=r},{}],72:[function(e,t,n){"use strict";var r={currentlyMountingInstance:null,currentlyUnmountingInstance:null};t.exports=r},{}],73:[function(e,t,n){"use strict";function r(e,t){this.value=e,this.requestChange=t}function o(e){var t={value:"undefined"==typeof e?i.PropTypes.any.isRequired:e.isRequired,requestChange:i.PropTypes.func.isRequired};return i.PropTypes.shape(t)}var i=e(31);r.PropTypes={link:o},t.exports=r},{31:31}],74:[function(e,t,n){"use strict";var r=e(116),o={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(">"," "+o.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var n=t.getAttribute(o.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=r(e);return i===n}};t.exports=o},{116:116}],75:[function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){var t=I(e);return t&&K.getID(t)}function i(e){var t=a(e);if(t)if(L.hasOwnProperty(t)){var n=L[t];n!==e&&(w(!c(n,t)),L[t]=e)}else L[t]=e;return t}function a(e){return e&&e.getAttribute&&e.getAttribute(k)||""}function s(e,t){var n=a(e);n!==t&&delete L[n],e.setAttribute(k,t),L[t]=e}function u(e){return L.hasOwnProperty(e)&&c(L[e],e)||(L[e]=K.findReactNodeByID(e)),L[e]}function l(e){var t=b.get(e)._rootNodeID;return C.isNullComponentID(t)?null:(L.hasOwnProperty(t)&&c(L[t],t)||(L[t]=K.findReactNodeByID(t)),L[t])}function c(e,t){if(e){w(a(e)===t);var n=K.findReactContainerForID(t);if(n&&P(n,e))return!0}return!1}function p(e){delete L[e]}function d(e){var t=L[e];return t&&c(t,e)?void(W=t):!1}function f(e){W=null,E.traverseAncestors(e,d);var t=W;return W=null,t}function h(e,t,n,r,o){var i=D.mountComponent(e,t,r,N);e._isTopLevel=!0,K._mountImageIntoNode(i,n,o)}function m(e,t,n,r){var o=T.ReactReconcileTransaction.getPooled();o.perform(h,null,e,t,n,o,r),T.ReactReconcileTransaction.release(o)}var v=e(11),g=e(33),y=(e(45),e(61)),C=(e(62),e(63)),E=e(70),b=e(71),_=e(74),x=e(80),D=e(87),M=e(96),T=e(97),N=e(127),P=e(120),I=e(141),R=e(146),w=e(147),O=e(159),S=e(162),A=(e(166),E.SEPARATOR),k=v.ID_ATTRIBUTE_NAME,L={},U=1,F=9,B={},j={},V=[],W=null,K={_instancesByReactRootID:B,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return K.scrollMonitor(n,function(){M.enqueueElementInternal(e,t),r&&M.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){w(t&&(t.nodeType===U||t.nodeType===F)),g.ensureScrollValueMonitoring();var n=K.registerContainer(t);return B[n]=e,n},_renderNewRootComponent:function(e,t,n){var r=R(e,null),o=K._registerComponent(r,t);return T.batchedUpdates(m,r,o,t,n),r},render:function(e,t,n){w(y.isValidElement(e));var r=B[o(t)];if(r){var i=r._currentElement;if(S(i,e))return K._updateRootComponent(r,e,t,n).getPublicInstance();K.unmountComponentAtNode(t)}var a=I(t),s=a&&K.isRenderedByReact(a),u=s&&!r,l=K._renderNewRootComponent(e,t,u).getPublicInstance();return n&&n.call(l),l},constructAndRenderComponent:function(e,t,n){var r=y.createElement(e,t);return K.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return w(r),K.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=o(e);return t&&(t=E.getReactRootIDFromNodeID(t)),t||(t=E.createReactRootID()),j[t]=e,t},unmountComponentAtNode:function(e){w(e&&(e.nodeType===U||e.nodeType===F));var t=o(e),n=B[t];return n?(K.unmountComponentFromNode(n,e),delete B[t],delete j[t],!0):!1},unmountComponentFromNode:function(e,t){for(D.unmountComponent(e),t.nodeType===F&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=E.getReactRootIDFromNodeID(e),n=j[t];return n},findReactNodeByID:function(e){var t=K.findReactContainerForID(e);return K.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=K.getID(e);return t?t.charAt(0)===A:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(K.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=V,r=0,o=f(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=K.getID(a);s?t===s?i=a:E.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,w(!1)},_mountImageIntoNode:function(e,t,n){if(w(t&&(t.nodeType===U||t.nodeType===F)),n){var o=I(t);if(_.canReuseMarkup(e,o))return;var i=o.getAttribute(_.CHECKSUM_ATTR_NAME);o.removeAttribute(_.CHECKSUM_ATTR_NAME);var a=o.outerHTML;o.setAttribute(_.CHECKSUM_ATTR_NAME,i);var s=r(e,a);" (client) "+e.substring(s-20,s+20)+"\n (server) "+a.substring(s-20,s+20),w(t.nodeType!==F)}w(t.nodeType!==F),O(t,e)},getReactRootID:o,getID:i,setID:s,getNode:u,getNodeFromInstance:l,purgeID:p};x.measureMethods(K,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=K},{11:11,120:120,127:127,141:141,146:146,147:147,159:159,162:162,166:166,33:33,45:45,61:61,62:62,63:63,70:70,71:71,74:74,80:80,87:87,96:96,97:97}],76:[function(e,t,n){"use strict";function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function o(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function a(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function s(){h.length&&(l.processChildrenUpdates(h,m),u())}function u(){h.length=0,m.length=0}var l=e(41),c=e(77),p=e(87),d=e(36),f=0,h=[],m=[],v={Mixin:{mountChildren:function(e,t,n){var r=d.instantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=this._rootNodeID+a,l=p.mountComponent(s,u,t,n);s._mountIndex=i,o.push(l),i++}return o},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;d.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?u():s())}},updateChildren:function(e,t,n){f++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{f--,f||(r?u():s())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=d.updateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,s=0;for(i in o)if(o.hasOwnProperty(i)){var u=r&&r[i],l=o[i];u===l?(this.moveChild(u,s,a),a=Math.max(u._mountIndex,a),u._mountIndex=s):(u&&(a=Math.max(u._mountIndex,a),this._unmountChildByName(u,i)),this._mountChildByNameAtIndex(l,i,s,t,n)),s++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChildByName(r[i],i)}},unmountChildren:function(){var e=this._renderedChildren;d.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=p.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null}}};t.exports=v},{36:36,41:41,77:77,87:87}],77:[function(e,t,n){"use strict";var r=e(153),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=o},{153:153}],78:[function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=l(t)),n}function o(e){return u(c),new c(e.type,e.props)}function i(e){return new d(e)}function a(e){return e instanceof d}var s=e(29),u=e(147),l=null,c=null,p={},d=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){s(p,e)},injectAutoWrapper:function(e){l=e}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:f};t.exports=h},{147:147,29:29}],79:[function(e,t,n){"use strict";var r=e(147),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};t.exports=o},{147:147}],80:[function(e,t,n){"use strict";function r(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:r,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){o.storedMeasure=e}}};t.exports=o},{}],81:[function(e,t,n){"use strict";function r(e){return function(t,n,r){t.hasOwnProperty(n)?t[n]=e(t[n],r):t[n]=r}}function o(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=l[n];r&&l.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var i=e(29),a=e(126),s=e(152),u=r(function(e,t){return i({},t,e)}),l={children:a,className:r(s),style:u},c={mergeProps:function(e,t){return o(i({},e),t)}};t.exports=c},{126:126,152:152,29:29}],82:[function(e,t,n){"use strict";var r={};t.exports=r},{}],83:[function(e,t,n){"use strict";var r=e(153),o=r({prop:null,context:null,childContext:null});t.exports=o},{153:153}],84:[function(e,t,n){"use strict";function r(e){function t(t,n,r,o,i){if(o=o||b,null==n[r]){var a=C[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o){var i=t[n],a=m(i);if(a!==e){var s=C[o],u=v(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}return null}return r(t)}function i(){return r(E.thatReturns(null))}function a(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=C[o],s=m(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<i.length;u++){var l=e(i,u,r,o);if(l instanceof Error)return l}return null}return r(t)}function s(){function e(e,t,n,r){if(!g.isValidElement(e[t])){var o=C[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}return null}return r(e)}function u(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=C[o],a=e.name||b;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}return null}return r(t)}function l(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return null;var s=C[o],u=JSON.stringify(e);return new Error("Invalid "+s+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+u+"."))}return r(t)}function c(e){function t(t,n,r,o){var i=t[n],a=m(i);if("object"!==a){var s=C[o];return new Error("Invalid "+s+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var u in i)if(i.hasOwnProperty(u)){var l=e(i,u,r,o);if(l instanceof Error)return l}return null}return r(t)}function p(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return null}var s=C[o];return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`."))}return r(t)}function d(){function e(e,t,n,r){if(!h(e[t])){var o=C[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function f(e){function t(t,n,r,o){var i=t[n],a=m(i);if("object"!==a){var s=C[o];return new Error("Invalid "+s+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var l=e[u];if(l){var c=l(i,u,r,o);if(c)return c}}return null}return r(t)}function h(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(h);if(null===e||g.isValidElement(e))return!0;e=y.extractIfFragment(e);for(var t in e)if(!h(e[t]))return!1;return!0;default:return!1}}function m(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function v(e){var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var g=e(61),y=e(67),C=e(82),E=e(126),b="<<anonymous>>",_=s(),x=d(),D={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:a,element:_,instanceOf:u,node:x,objectOf:c,oneOf:l,oneOfType:p,shape:f};t.exports=D},{126:126,61:61,67:67,82:82}],85:[function(e,t,n){"use strict";function r(){this.listenersToPut=[]}var o=e(30),i=e(33),a=e(29);a(r.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];i.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),o.addPoolingTo(r),t.exports=r},{29:29,30:30,33:33}],86:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.putListenerQueue=u.getPooled()}var o=e(7),i=e(30),a=e(33),s=e(69),u=e(85),l=e(113),c=e(29),p={initialize:s.getSelectionInformation,close:s.restoreSelection},d={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},m=[h,p,d,f],v={getTransactionWrappers:function(){return m},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,u.release(this.putListenerQueue),this.putListenerQueue=null}};c(r.prototype,l.Mixin,v),i.addPoolingTo(r),t.exports=r},{113:113,29:29,30:30,33:33,69:69,7:7,85:85}],87:[function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=e(88),i=(e(62),{mountComponent:function(e,t,n,o){var i=e.mountComponent(t,n,o);return n.getReactMountReady().enqueue(r,e),i},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||null==t._owner){var s=o.shouldUpdateRefs(a,t);s&&o.detachRefs(e,a),e.receiveComponent(t,n,i),s&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}});t.exports=i},{62:62,88:88}],88:[function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=e(79),a={};a.attachRefs=function(e,t){var n=t.ref;null!=n&&r(n,e,t._owner)},a.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){var n=t.ref;null!=n&&o(n,e,t._owner)},t.exports=a},{79:79}],89:[function(e,t,n){"use strict";var r={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:r};t.exports=o},{}],90:[function(e,t,n){"use strict";function r(e){p(i.isValidElement(e));var t;try{var n=a.createReactRootID();return t=u.getPooled(!1),t.perform(function(){var r=c(e,null),o=r.mountComponent(n,t,l);return s.addChecksumToMarkup(o)},null)}finally{u.release(t)}}function o(e){p(i.isValidElement(e));var t;try{var n=a.createReactRootID();return t=u.getPooled(!0),t.perform(function(){var r=c(e,null);return r.mountComponent(n,t,l)},null)}finally{u.release(t)}}var i=e(61),a=e(70),s=e(74),u=e(91),l=e(127),c=e(146),p=e(147);t.exports={renderToString:r,renderToStaticMarkup:o}},{127:127,146:146,147:147,61:61,70:70,74:74,91:91}],91:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.putListenerQueue=a.getPooled()}var o=e(30),i=e(7),a=e(85),s=e(113),u=e(29),l=e(126),c={initialize:function(){this.reactMountReady.reset()},close:l},p={initialize:function(){this.putListenerQueue.reset()},close:l},d=[p,c],f={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null,a.release(this.putListenerQueue),this.putListenerQueue=null}};u(r.prototype,s.Mixin,f),o.addPoolingTo(r),t.exports=r},{113:113,126:126,29:29,30:30,7:7,85:85}],92:[function(e,t,n){"use strict";function r(e,t){var n={};return function(r){n[t]=r,e.setState(n)}}var o={createStateSetter:function(e,t){return function(n,r,o,i,a,s){var u=t.call(e,n,r,o,i,a,s);u&&e.setState(u)}},createStateKeySetter:function(e,t){var n=e.__keySetters||(e.__keySetters={});return n[t]||(n[t]=r(e,t))}};o.Mixin={createStateSetter:function(e){return o.createStateSetter(this,e)},createStateKeySetter:function(e){return o.createStateKeySetter(this,e)}},t.exports=o},{}],93:[function(e,t,n){"use strict";var r=e(37),o=e(67),i={getChildMapping:function(e){return e?o.extract(r.map(e,function(e){return e})):e},mergeChildMappings:function(e,t){function n(n){return t.hasOwnProperty(n)?t[n]:e[n]}e=e||{},t=t||{};var r={},o=[];for(var i in e)t.hasOwnProperty(i)?o.length&&(r[i]=o,o=[]):o.push(i);var a,s={};for(var u in t){if(r.hasOwnProperty(u))for(a=0;a<r[u].length;a++){var l=r[u][a];s[r[u][a]]=n(l)}s[u]=n(u)}for(a=0;a<o.length;a++)s[o[a]]=n(o[a]);return s}};t.exports=i},{37:37,67:67}],94:[function(e,t,n){"use strict";function r(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete s.animationend.animation,"TransitionEvent"in window||delete s.transitionend.transition;for(var n in s){var r=s[n];for(var o in r)if(o in t){u.push(r[o]);break}}}function o(e,t,n){e.addEventListener(t,n,!1)}function i(e,t,n){e.removeEventListener(t,n,!1)}var a=e(22),s={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},u=[];a.canUseDOM&&r();var l={addEndEventListener:function(e,t){ return 0===u.length?void window.setTimeout(t,0):void u.forEach(function(n){o(e,n,t)})},removeEndEventListener:function(e,t){0!==u.length&&u.forEach(function(n){i(e,n,t)})}};t.exports=l},{22:22}],95:[function(e,t,n){"use strict";var r=e(31),o=e(93),i=e(29),a=e(119),s=e(126),u=r.createClass({displayName:"ReactTransitionGroup",propTypes:{component:r.PropTypes.any,childFactory:r.PropTypes.func},getDefaultProps:function(){return{component:"span",childFactory:s.thatReturnsArgument}},getInitialState:function(){return{children:o.getChildMapping(this.props.children)}},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidMount:function(){var e=this.state.children;for(var t in e)e[t]&&this.performAppear(t)},componentWillReceiveProps:function(e){var t=o.getChildMapping(e.children),n=this.state.children;this.setState({children:o.mergeChildMappings(n,t)});var r;for(r in t){var i=n&&n.hasOwnProperty(r);!t[r]||i||this.currentlyTransitioningKeys[r]||this.keysToEnter.push(r)}for(r in n){var a=t&&t.hasOwnProperty(r);!n[r]||a||this.currentlyTransitioningKeys[r]||this.keysToLeave.push(r)}},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performAppear:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillAppear?t.componentWillAppear(this._handleDoneAppearing.bind(this,e)):this._handleDoneAppearing(e)},_handleDoneAppearing:function(e){var t=this.refs[e];t.componentDidAppear&&t.componentDidAppear(),delete this.currentlyTransitioningKeys[e];var n=o.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performEnter:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillEnter?t.componentWillEnter(this._handleDoneEntering.bind(this,e)):this._handleDoneEntering(e)},_handleDoneEntering:function(e){var t=this.refs[e];t.componentDidEnter&&t.componentDidEnter(),delete this.currentlyTransitioningKeys[e];var n=o.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performLeave:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillLeave?t.componentWillLeave(this._handleDoneLeaving.bind(this,e)):this._handleDoneLeaving(e)},_handleDoneLeaving:function(e){var t=this.refs[e];t.componentDidLeave&&t.componentDidLeave(),delete this.currentlyTransitioningKeys[e];var n=o.getChildMapping(this.props.children);if(n&&n.hasOwnProperty(e))this.performEnter(e);else{var r=i({},this.state.children);delete r[e],this.setState({children:r})}},render:function(){var e=[];for(var t in this.state.children){var n=this.state.children[t];n&&e.push(a(this.props.childFactory(n),{ref:t,key:t}))}return r.createElement(this.props.component,this.props,e)}});t.exports=u},{119:119,126:126,29:29,31:31,93:93}],96:[function(e,t,n){"use strict";function r(e){e!==i.currentlyMountingInstance&&l.enqueueUpdate(e)}function o(e,t){p(null==a.current);var n=u.get(e);return n?n===i.currentlyUnmountingInstance?null:n:null}var i=e(72),a=e(45),s=e(61),u=e(71),l=e(97),c=e(29),p=e(147),d=(e(166),{enqueueCallback:function(e,t){p("function"==typeof t);var n=o(e);return n&&n!==i.currentlyMountingInstance?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){p("function"==typeof t),e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");if(n){p(n._isTopLevel);var i=n._pendingElement||n._currentElement,a=c({},i.props,t);n._pendingElement=s.cloneAndReplaceProps(i,a),r(n)}},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");if(n){p(n._isTopLevel);var i=n._pendingElement||n._currentElement;n._pendingElement=s.cloneAndReplaceProps(i,t),r(n)}},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});t.exports=d},{147:147,166:166,29:29,45:45,61:61,71:71,72:72,97:97}],97:[function(e,t,n){"use strict";function r(){v(T.ReactReconcileTransaction&&E)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=T.ReactReconcileTransaction.getPooled()}function i(e,t,n,o,i){r(),E.batchedUpdates(e,t,n,o,i)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;v(t===g.length),g.sort(a);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,f.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var i=0;i<o.length;i++)e.callbackQueue.enqueue(o[i],r.getPublicInstance())}}function u(e){return r(),E.isBatchingUpdates?void g.push(e):void E.batchedUpdates(u,e)}function l(e,t){v(E.isBatchingUpdates),y.enqueue(e,t),C=!0}var c=e(7),p=e(30),d=(e(45),e(80)),f=e(87),h=e(113),m=e(29),v=e(147),g=(e(166),[]),y=c.getPooled(),C=!1,E=null,b={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),D()):g.length=0}},_={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[b,_];m(o.prototype,h.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,T.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var D=function(){for(;g.length||C;){if(g.length){var e=o.getPooled();e.perform(s,null,e),o.release(e)}if(C){C=!1;var t=y;y=c.getPooled(),t.notifyAll(),c.release(t)}}};D=d.measure("ReactUpdates","flushBatchedUpdates",D);var M={injectReconcileTransaction:function(e){v(e),T.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){v(e),v("function"==typeof e.batchedUpdates),v("boolean"==typeof e.isBatchingUpdates),E=e}},T={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:u,flushBatchedUpdates:D,injection:M,asap:l};t.exports=T},{113:113,147:147,166:166,29:29,30:30,45:45,7:7,80:80,87:87}],98:[function(e,t,n){"use strict";var r=e(11),o=r.injection.MUST_USE_ATTRIBUTE,i={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,y1:o,y2:o,y:o},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};t.exports=i},{11:11}],99:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&s.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e){if(y||null==m||m!==l())return null;var t=r(m);if(!g||!d(g,t)){g=t;var n=u.getPooled(h.select,v,e);return n.type="select",n.target=m,a.accumulateTwoPhaseDispatches(n),n}}var i=e(16),a=e(21),s=e(69),u=e(105),l=e(133),c=e(150),p=e(154),d=e(161),f=i.topLevelTypes,h={select:{phasedRegistrationNames:{bubbled:p({onSelect:null}),captured:p({onSelectCapture:null})},dependencies:[f.topBlur,f.topContextMenu,f.topFocus,f.topKeyDown,f.topMouseDown,f.topMouseUp,f.topSelectionChange]}},m=null,v=null,g=null,y=!1,C={eventTypes:h,extractEvents:function(e,t,n,r){switch(e){case f.topFocus:(c(t)||"true"===t.contentEditable)&&(m=t,v=n,g=null);break;case f.topBlur:m=null,v=null,g=null;break;case f.topMouseDown:y=!0;break;case f.topContextMenu:case f.topMouseUp:return y=!1,o(r);case f.topSelectionChange:case f.topKeyDown:case f.topKeyUp:return o(r)}}};t.exports=C},{105:105,133:133,150:150,154:154,16:16,161:161,21:21,69:69}],100:[function(e,t,n){"use strict";var r=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*r)}};t.exports=o},{}],101:[function(e,t,n){"use strict";var r=e(16),o=e(20),i=e(21),a=e(102),s=e(105),u=e(106),l=e(108),c=e(109),p=e(104),d=e(110),f=e(111),h=e(112),m=e(134),v=e(147),g=e(154),y=(e(166),r.topLevelTypes),C={blur:{phasedRegistrationNames:{bubbled:g({onBlur:!0}),captured:g({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:g({onClick:!0}),captured:g({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:g({onContextMenu:!0}),captured:g({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:g({onCopy:!0}),captured:g({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:g({onCut:!0}),captured:g({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:g({onDoubleClick:!0}),captured:g({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:g({onDrag:!0}),captured:g({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:g({onDragEnd:!0}),captured:g({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:g({onDragEnter:!0}),captured:g({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:g({onDragExit:!0}),captured:g({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:g({onDragLeave:!0}),captured:g({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:g({onDragOver:!0}),captured:g({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:g({onDragStart:!0}),captured:g({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:g({onDrop:!0}),captured:g({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:g({onFocus:!0}),captured:g({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:g({onInput:!0}),captured:g({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:g({onKeyDown:!0}),captured:g({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:g({onKeyPress:!0}),captured:g({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:g({onKeyUp:!0}),captured:g({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:g({onLoad:!0}),captured:g({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:g({onError:!0}),captured:g({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:g({onMouseDown:!0}),captured:g({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:g({onMouseMove:!0}),captured:g({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:g({onMouseOut:!0}),captured:g({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:g({onMouseOver:!0}),captured:g({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:g({onMouseUp:!0}),captured:g({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:g({onPaste:!0}),captured:g({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:g({onReset:!0}),captured:g({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:g({onScroll:!0}),captured:g({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:g({onSubmit:!0}),captured:g({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:g({onTouchCancel:!0}),captured:g({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:g({onTouchEnd:!0}),captured:g({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:g({onTouchMove:!0}),captured:g({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:g({onTouchStart:!0}),captured:g({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:g({onWheel:!0}),captured:g({onWheelCapture:!0})}}},E={topBlur:C.blur,topClick:C.click,topContextMenu:C.contextMenu,topCopy:C.copy,topCut:C.cut,topDoubleClick:C.doubleClick,topDrag:C.drag,topDragEnd:C.dragEnd,topDragEnter:C.dragEnter,topDragExit:C.dragExit,topDragLeave:C.dragLeave,topDragOver:C.dragOver,topDragStart:C.dragStart,topDrop:C.drop,topError:C.error,topFocus:C.focus,topInput:C.input,topKeyDown:C.keyDown,topKeyPress:C.keyPress,topKeyUp:C.keyUp,topLoad:C.load,topMouseDown:C.mouseDown,topMouseMove:C.mouseMove,topMouseOut:C.mouseOut,topMouseOver:C.mouseOver,topMouseUp:C.mouseUp,topPaste:C.paste,topReset:C.reset,topScroll:C.scroll,topSubmit:C.submit,topTouchCancel:C.touchCancel,topTouchEnd:C.touchEnd,topTouchMove:C.touchMove,topTouchStart:C.touchStart,topWheel:C.wheel};for(var b in E)E[b].dependencies=[b];var _={eventTypes:C,executeDispatch:function(e,t,n){var r=o.executeDispatch(e,t,n);r===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var o=E[e];if(!o)return null;var g;switch(e){case y.topInput:case y.topLoad:case y.topError:case y.topReset:case y.topSubmit:g=s;break;case y.topKeyPress:if(0===m(r))return null;case y.topKeyDown:case y.topKeyUp:g=l;break;case y.topBlur:case y.topFocus:g=u;break;case y.topClick:if(2===r.button)return null;case y.topContextMenu:case y.topDoubleClick:case y.topMouseDown:case y.topMouseMove:case y.topMouseOut:case y.topMouseOver:case y.topMouseUp:g=c;break;case y.topDrag:case y.topDragEnd:case y.topDragEnter:case y.topDragExit:case y.topDragLeave:case y.topDragOver:case y.topDragStart:case y.topDrop:g=p;break;case y.topTouchCancel:case y.topTouchEnd:case y.topTouchMove:case y.topTouchStart:g=d;break;case y.topScroll:g=f;break;case y.topWheel:g=h;break;case y.topCopy:case y.topCut:case y.topPaste:g=a}v(g);var C=g.getPooled(o,n,r);return i.accumulateTwoPhaseDispatches(C),C}};t.exports=_},{102:102,104:104,105:105,106:106,108:108,109:109,110:110,111:111,112:112,134:134,147:147,154:154,16:16,166:166,20:20,21:21}],102:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(105),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),t.exports=r},{105:105}],103:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(105),i={data:null};o.augmentClass(r,i),t.exports=r},{105:105}],104:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(109),i={dataTransfer:null};o.augmentClass(r,i),t.exports=r},{109:109}],105:[function(e,t,n){"use strict";function r(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var o in r)if(r.hasOwnProperty(o)){var i=r[o];i?this[o]=i(n):this[o]=n[o]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;s?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var o=e(30),i=e(29),a=e(126),s=e(137),u={type:null,target:s,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=u,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);i(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.threeArgumentPooler)},o.addPoolingTo(r,o.threeArgumentPooler),t.exports=r},{126:126,137:137,29:29,30:30}],106:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(111),i={relatedTarget:null};o.augmentClass(r,i),t.exports=r},{111:111}],107:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(105),i={data:null};o.augmentClass(r,i),t.exports=r},{105:105}],108:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(111),i=e(134),a=e(135),s=e(136),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,u),t.exports=r},{111:111,134:134,135:135,136:136}],109:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(111),i=e(114),a=e(136),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,s),t.exports=r},{111:111,114:114,136:136}],110:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(111),i=e(136),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),t.exports=r},{111:111,136:136}],111:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(105),i=e(137),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),t.exports=r},{105:105,137:137}],112:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(109),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),t.exports=r},{109:109}],113:[function(e,t,n){"use strict";var r=e(147),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,s,u){r(!this.isInTransaction());var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,n,o,i,a,s,u),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){r(this.isInTransaction());for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],s=this.wrapperInitData[n];try{o=!0,s!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,s),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(u){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};t.exports=i},{147:147}],114:[function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{}],115:[function(e,t,n){"use strict";function r(e,t){if(o(null!=t),null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=e(147);t.exports=r},{147:147}],116:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0;r<e.length;r++)t=(t+e.charCodeAt(r))%o,n=(n+t)%o;return t|n<<16}var o=65521;t.exports=r},{}],117:[function(e,t,n){function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;t.exports=r},{}],118:[function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=e(117),i=/^-ms-/;t.exports=r},{117:117}],119:[function(e,t,n){"use strict";function r(e,t){var n=i.mergeProps(t,e.props);return!n.hasOwnProperty(s)&&e.props.hasOwnProperty(s)&&(n.children=e.props.children),o.createElement(e.type,n)}var o=e(61),i=e(81),a=e(154),s=(e(166),a({children:null}));t.exports=r},{154:154,166:166,61:61,81:81}],120:[function(e,t,n){function r(e,t){return e&&t?e===t?!0:o(e)?!1:o(t)?r(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var o=e(151);t.exports=r},{151:151}],121:[function(e,t,n){function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return r(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=e(163);t.exports=o},{163:163}],122:[function(e,t,n){"use strict";function r(e){var t=i.createFactory(e),n=o.createClass({tagName:e.toUpperCase(),displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){a(!1)},render:function(){return t(this.props)}});return n}var o=e(38),i=e(61),a=e(147);t.exports=r},{147:147,38:38,61:61}],123:[function(e,t,n){function r(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,t){var n=l;u(!!l);var o=r(e),i=o&&s(o);if(i){n.innerHTML=i[1]+e+i[2];for(var c=i[0];c--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(u(t),a(p).forEach(t));for(var d=a(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return d}var i=e(22),a=e(121),s=e(139),u=e(147),l=i.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=o},{121:121,139:139,147:147,22:22}],124:[function(e,t,n){"use strict";function r(e){return"object"==typeof e?Object.keys(e).filter(function(t){return e[t]}).join(" "):Array.prototype.join.call(arguments," ")}e(166);t.exports=r},{166:166}],125:[function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=e(5),i=o.isUnitlessNumber;t.exports=r},{5:5}],126:[function(e,t,n){function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},t.exports=o},{}],127:[function(e,t,n){"use strict";var r={};t.exports=r},{}],128:[function(e,t,n){"use strict";function r(e){return i[e]}function o(e){return(""+e).replace(a,r)}var i={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},a=/[&><"']/g;t.exports=o},{}],129:[function(e,t,n){"use strict";function r(e){return null==e?null:s(e)?e:o.has(e)?i.getNodeFromInstance(e):(a(null==e.render||"function"!=typeof e.render),void a(!1))}{var o=(e(45),e(71)),i=e(75),a=e(147),s=e(149);e(166)}t.exports=r},{147:147,149:149,166:166,45:45,71:71,75:75}],130:[function(e,t,n){"use strict";function r(e,t,n){var r=e,o=!r.hasOwnProperty(n);o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}{var i=e(164);e(166)}t.exports=o},{164:164,166:166}],131:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],132:[function(e,t,n){"use strict";var r=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=r},{}],133:[function(e,t,n){function r(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],134:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],135:[function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=e(134),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=r},{134:134}],136:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=i[e];return r?!!n[r]:!1}function o(e){return r}var i={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=o},{}],137:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=r},{}],138:[function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);return"function"==typeof t?t:void 0}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";t.exports=r},{}],139:[function(e,t,n){function r(e){return i(!!a),d.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?d[e]:null}var o=e(22),i=e(147),a=o.canUseDOM?document.createElement("div"):null,s={circle:!0,clipPath:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},u=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,"<svg>","</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:u,option:u,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c,circle:p,clipPath:p,defs:p,ellipse:p,g:p,line:p,linearGradient:p,path:p,polygon:p,polyline:p,radialGradient:p,rect:p,stop:p,text:p};t.exports=r},{147:147,22:22}],140:[function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function i(e,t){for(var n=r(e),i=0,a=0;n;){if(3===n.nodeType){if(a=i+n.textContent.length,t>=i&&a>=t)return{node:n,offset:t-i};i=a}n=r(o(n))}}t.exports=i},{}],141:[function(e,t,n){"use strict";function r(e){return e?e.nodeType===o?e.documentElement:e.firstChild:null}var o=9;t.exports=r},{}],142:[function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=e(22),i=null;t.exports=r},{22:22}],143:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],144:[function(e,t,n){function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=r},{}],145:[function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=e(144),i=/^ms-/;t.exports=r},{144:144}],146:[function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e,t){var n;if((null===e||e===!1)&&(e=a.emptyElement),"object"==typeof e){var o=e;n=t===o.type&&"string"==typeof o.type?s.createInternalComponent(o):r(o.type)?new o.type(o):new c}else"string"==typeof e||"number"==typeof e?n=s.createInstanceForText(e):l(!1);return n.construct(e),n._mountIndex=0,n._mountImage=null,n}var i=e(43),a=e(63),s=e(78),u=e(29),l=e(147),c=(e(166),function(){});u(c.prototype,i.Mixin,{_instantiateReactComponent:o}),t.exports=o},{147:147,166:166,29:29,43:43,63:63,78:78}],147:[function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,s],c=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return l[c++]}))}throw u.framesToPop=1,u}};t.exports=r},{}],148:[function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=e(22);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{22:22}],149:[function(e,t,n){function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=r},{}],150:[function(e,t,n){"use strict";function r(e){return e&&("INPUT"===e.nodeName&&o[e.type]||"TEXTAREA"===e.nodeName)}var o={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};t.exports=r},{}],151:[function(e,t,n){function r(e){return o(e)&&3==e.nodeType}var o=e(149);t.exports=r},{149:149}],152:[function(e,t,n){"use strict";function r(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e=(e?e+" ":"")+t);return e}t.exports=r},{}],153:[function(e,t,n){"use strict";var r=e(147),o=function(e){var t,n={};r(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};t.exports=o},{147:147}],154:[function(e,t,n){var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=r},{}],155:[function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var i in e)o.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}var o=Object.prototype.hasOwnProperty;t.exports=r},{}],156:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],157:[function(e,t,n){"use strict";function r(e){return i(o.isValidElement(e)),e}var o=e(61),i=e(147);t.exports=r},{147:147,61:61}],158:[function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=e(128);t.exports=r},{128:128}],159:[function(e,t,n){"use strict";var r=e(22),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){ e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var s=document.createElement("div");s.innerHTML=" ",""===s.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML="\ufeff"+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=a},{22:22}],160:[function(e,t,n){"use strict";var r=e(22),o=e(128),i=e(159),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),t.exports=a},{128:128,159:159,22:22}],161:[function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=r},{}],162:[function(e,t,n){"use strict";function r(e,t){if(null!=e&&null!=t){var n=typeof e,r=typeof t;if("string"===n||"number"===n)return"string"===r||"number"===r;if("object"===r&&e.type===t.type&&e.key===t.key){var o=e._owner===t._owner;return o}}return!1}e(166);t.exports=r},{166:166}],163:[function(e,t,n){function r(e){var t=e.length;if(o(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),o("number"==typeof t),o(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=e(147);t.exports=r},{147:147}],164:[function(e,t,n){"use strict";function r(e){return v[e]}function o(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(g,r)}function a(e){return"$"+i(e)}function s(e,t,n,r,i){var u=typeof e;if(("undefined"===u||"boolean"===u)&&(e=null),null===e||"string"===u||"number"===u||l.isValidElement(e))return r(i,e,""===t?h+o(e,0):t,n),1;var p,v,g,y=0;if(Array.isArray(e))for(var C=0;C<e.length;C++)p=e[C],v=(""!==t?t+m:h)+o(p,C),g=n+y,y+=s(p,v,g,r,i);else{var E=d(e);if(E){var b,_=E.call(e);if(E!==e.entries)for(var x=0;!(b=_.next()).done;)p=b.value,v=(""!==t?t+m:h)+o(p,x++),g=n+y,y+=s(p,v,g,r,i);else for(;!(b=_.next()).done;){var D=b.value;D&&(p=D[1],v=(""!==t?t+m:h)+a(D[0])+m+o(p,0),g=n+y,y+=s(p,v,g,r,i))}}else if("object"===u){f(1!==e.nodeType);var M=c.extract(e);for(var T in M)M.hasOwnProperty(T)&&(p=M[T],v=(""!==t?t+m:h)+a(T)+m+o(p,0),g=n+y,y+=s(p,v,g,r,i))}}return y}function u(e,t,n){return null==e?0:s(e,"",0,t,n)}var l=e(61),c=e(67),p=e(70),d=e(138),f=e(147),h=(e(166),p.SEPARATOR),m=":",v={"=":"=0",".":"=1",":":"=2"},g=/[=.:]/g;t.exports=u},{138:138,147:147,166:166,61:61,67:67,70:70}],165:[function(e,t,n){"use strict";function r(e){return Array.isArray(e)?e.concat():e&&"object"==typeof e?a(new e.constructor,e):e}function o(e,t,n){u(Array.isArray(e));var r=t[n];u(Array.isArray(r))}function i(e,t){if(u("object"==typeof t),l.call(t,f))return u(1===Object.keys(t).length),t[f];var n=r(e);if(l.call(t,h)){var s=t[h];u(s&&"object"==typeof s),u(n&&"object"==typeof n),a(n,t[h])}l.call(t,c)&&(o(e,t,c),t[c].forEach(function(e){n.push(e)})),l.call(t,p)&&(o(e,t,p),t[p].forEach(function(e){n.unshift(e)})),l.call(t,d)&&(u(Array.isArray(e)),u(Array.isArray(t[d])),t[d].forEach(function(e){u(Array.isArray(e)),n.splice.apply(n,e)})),l.call(t,m)&&(u("function"==typeof t[m]),n=t[m](n));for(var v in t)g.hasOwnProperty(v)&&g[v]||(n[v]=i(e[v],t[v]));return n}var a=e(29),s=e(154),u=e(147),l={}.hasOwnProperty,c=s({$push:null}),p=s({$unshift:null}),d=s({$splice:null}),f=s({$set:null}),h=s({$merge:null}),m=s({$apply:null}),v=[c,p,d,f,h,m],g={};v.forEach(function(e){g[e]=!0}),t.exports=i},{147:147,154:154,29:29}],166:[function(e,t,n){"use strict";var r=e(126),o=r;t.exports=o},{126:126}]},{},[1])(1)});
app/screen/Favorite.js
shuiszhang/fanfou
/** * Created by shuis on 2017/5/29. */ import React, { Component } from 'react'; import { Button, Text, View } from 'react-native'; class Favorite extends Component{ static navigationOptions = ({ navigation }) => ({ tabBarLabel: '收藏', }); constructor(props){ super(props); } render(){ return ( <View> <Text>我的收藏</Text> </View> ) } } export default Favorite;
src/components/ui/FormCard.js
ntxcode/react-base
import React from 'react'; import './FormCard.css'; const FormCard = props => <div className="FormCard"> <h2 className="FormTitle">{props.title}</h2> {props.children} </div>; export default FormCard;
ajax/libs/analytics.js/2.8.14/analytics.min.js
coupang/cdnjs
(function umd(require){if("object"==typeof exports){module.exports=require("1")}else if("function"==typeof define&&define.amd){define(function(){return require("1")})}else{this["analytics"]=require("1")}})(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require}({1:[function(require,module,exports){var _analytics=window.analytics;var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("../bower.json").version;each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"../bower.json":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}if(val===null)return"null";if(val===undefined)return"undefined";if(val!==val)return"nan";if(val&&val.nodeType===1)return"element";val=val.valueOf?val.valueOf():Object.prototype.valueOf.apply(val);return typeof val}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/atatus"),require("./lib/autosend"),require("./lib/awesm"),require("./lib/bing-ads"),require("./lib/blueshift"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/extole"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/fullstory"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/nudgespot"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/outbound"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/satismeter"),require("./lib/segmentio"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/supporthero"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/userlike"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/atatus":13,"./lib/autosend":14,"./lib/awesm":15,"./lib/bing-ads":16,"./lib/blueshift":17,"./lib/bronto":18,"./lib/bugherd":19,"./lib/bugsnag":20,"./lib/chartbeat":21,"./lib/churnbee":22,"./lib/clicktale":23,"./lib/clicky":24,"./lib/comscore":25,"./lib/crazy-egg":26,"./lib/curebit":27,"./lib/customerio":28,"./lib/drip":29,"./lib/errorception":30,"./lib/evergage":31,"./lib/extole":32,"./lib/facebook-conversion-tracking":33,"./lib/foxmetrics":34,"./lib/frontleaf":35,"./lib/fullstory":36,"./lib/gauges":37,"./lib/get-satisfaction":38,"./lib/google-analytics":39,"./lib/google-tag-manager":40,"./lib/gosquared":41,"./lib/heap":42,"./lib/hellobar":43,"./lib/hittail":44,"./lib/hubspot":45,"./lib/improvely":46,"./lib/insidevault":47,"./lib/inspectlet":48,"./lib/intercom":49,"./lib/keen-io":50,"./lib/kenshoo":51,"./lib/kissmetrics":52,"./lib/klaviyo":53,"./lib/livechat":54,"./lib/lucky-orange":55,"./lib/lytics":56,"./lib/mixpanel":57,"./lib/mojn":58,"./lib/mouseflow":59,"./lib/mousestats":60,"./lib/navilytics":61,"./lib/nudgespot":62,"./lib/olark":63,"./lib/optimizely":64,"./lib/outbound":65,"./lib/perfect-audience":66,"./lib/pingdom":67,"./lib/piwik":68,"./lib/preact":69,"./lib/qualaroo":70,"./lib/quantcast":71,"./lib/rollbar":72,"./lib/saasquatch":73,"./lib/satismeter":74,"./lib/segmentio":75,"./lib/sentry":76,"./lib/snapengage":77,"./lib/spinnakr":78,"./lib/supporthero":79,"./lib/tapstream":80,"./lib/trakio":81,"./lib/twitter-ads":82,"./lib/userlike":83,"./lib/uservoice":84,"./lib/vero":85,"./lib/visual-website-optimizer":86,"./lib/webengage":87,"./lib/woopra":88,"./lib/yandex-metrica":89}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var del=require("obj-case").del;var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;var productId=track.id();var sku=track.sku();var customProps=track.properties();var data={};if(user.id())data.user_id=user.id();if(orderId)data.order_id=orderId;if(productId)data.product_id=productId;if(sku)data.sku=sku;if(total)data.adroll_conversion_value_in_dollars=total;del(customProps,"revenue");del(customProps,"total");del(customProps,"orderId");del(customProps,"id");del(customProps,"sku");if(!is.empty(customProps))data.adroll_custom_data=customProps;each(events,function(event){data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":90,"to-snake-case":91,"use-https":92,each:4,is:93,"obj-case":94}],90:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{bind:95,callback:96,clone:97,debug:98,defaults:99,"./protos":100,slug:101,"./statics":102}],95:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:103,"bind-all":104}],103:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],104:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:103,type:7}],96:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":105}],105:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],97:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],98:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":106,"./debug":107}],106:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],107:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],99:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],100:[function(require,module,exports){var loadScript=require("load-script");var loadIframe=require("load-iframe");var events=require("analytics-events");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var after=require("after");var each=require("each");var type=require("type");var fmt=require("fmt");function noop(){}var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=window.onerror;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];if(!template)throw new Error(fmt('template "%s" not defined.',name));var attrs=render(template,locals);var fn=fn||noop;var self=this;var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,function(err){if(!err)return fn();self.debug('error loading "%s" error="%s"',self.name,err)});delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"load-script":108,"load-iframe":109,"analytics-events":110,"to-no-case":111,callback:96,emitter:112,"next-tick":105,after:113,each:114,type:115,fmt:116}],108:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":117,"next-tick":105,type:7}],117:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('script error "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)});el.attachEvent("onerror",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e||window.event;fn(err)})}},{}],109:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadIframe(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var iframe=document.createElement("iframe");iframe.src=options.src;iframe.width=options.width||1;iframe.height=options.height||1;iframe.style.display="none";if("function"==type(fn)){onload(iframe,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(iframe,firstScript)});return iframe}},{"script-onload":117,"next-tick":105,type:7}],110:[function(require,module,exports){module.exports={removedProduct:/^[ _]?removed[ _]?product[ _]?$/i,viewedProduct:/^[ _]?viewed[ _]?product[ _]?$/i,viewedProductCategory:/^[ _]?viewed[ _]?product[ _]?category[ _]?$/i,addedProduct:/^[ _]?added[ _]?product[ _]?$/i,completedOrder:/^[ _]?completed[ _]?order[ _]?$/i,startedOrder:/^[ _]?started[ _]?order[ _]?$/i,updatedOrder:/^[ _]?updated[ _]?order[ _]?$/i,refundedOrder:/^[ _]?refunded?[ _]?order[ _]?$/i,viewedProductDetails:/^[ _]?viewed[ _]?product[ _]?details?[ _]?$/i,clickedProduct:/^[ _]?clicked[ _]?product[ _]?$/i,viewedPromotion:/^[ _]?viewed[ _]?promotion?[ _]?$/i,clickedPromotion:/^[ _]?clicked[ _]?promotion?[ _]?$/i,viewedCheckoutStep:/^[ _]?viewed[ _]?checkout[ _]?step[ _]?$/i,completedCheckoutStep:/^[ _]?completed[ _]?checkout[ _]?step[ _]?$/i}},{}],111:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],112:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:118}],118:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],113:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],114:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:115,"component-type":115,"to-function":119}],115:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],119:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:120,"component-props":120}],120:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],116:[function(require,module,exports){var toString=window.JSON?JSON.stringify:function(_){return String(_)};module.exports=fmt;fmt.o=toString;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],101:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],102:[function(require,module,exports){var after=require("after");var domify=require("domify");var each=require("each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;if(!~str.indexOf(attr.name+"="))return;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:113,domify:121,each:114,emitter:112}],121:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.polyline=map.ellipse=map.polygon=map.circle=map.text=map.line=map.path=map.rect=map.g=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html"); el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],91:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":122}],122:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":123}],123:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],92:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],93:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":124,type:7,"component-type":7}],124:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],94:[function(require,module,exports){var identity=function(_){return _};module.exports=multiple(find);module.exports.find=module.exports;module.exports.replace=function(obj,key,val,options){multiple(replace).call(this,obj,key,val,options);return obj};module.exports.del=function(obj,key,options){multiple(del).call(this,obj,key,null,options);return obj};function multiple(fn){return function(obj,path,val,options){var normalize=options&&isFunction(options.normalizer)?options.normalizer:defaultNormalize;path=normalize(path);var key;var finished=false;while(!finished)loop();function loop(){for(key in obj){var normalizedKey=normalize(key);if(0===path.indexOf(normalizedKey)){var temp=path.substr(normalizedKey.length);if(temp.charAt(0)==="."||temp.length===0){path=temp.substr(1);var child=obj[key];if(null==child){finished=true;return}if(!path.length){finished=true;return}obj=child;return}}}key=undefined;finished=true}if(!key)return;if(null==obj)return obj;return fn(obj,key,val)}}function find(obj,key){if(obj.hasOwnProperty(key))return obj[key]}function del(obj,key){if(obj.hasOwnProperty(key))delete obj[key];return obj}function replace(obj,key,val){if(obj.hasOwnProperty(key))obj[key]=val;return obj}function defaultNormalize(path){return path.replace(/[^a-zA-Z0-9\.]+/g,"").toLowerCase()}function isFunction(val){return typeof val==="function"}},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();delete props.revenue;window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":90,domify:121,each:4}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":90}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var utm=require("utm-params");var top=require("top-domain");var umd="function"==typeof define&&define.amd;var src="//d24n15hnbwhuhn.cloudfront.net/libs/amplitude-2.1.0-min.js";var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).option("trackUtmProperties",true).tag('<script src="'+src+'">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function a(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var i=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];for(var o=0;o<i.length;o++){a(i[o])}e.amplitude=r})(window,document);this.setDomain(window.location.href);window.amplitude.init(this.options.apiKey,null,{includeUtm:this.options.trackUtmProperties});var self=this;if(umd){window.require([src],function(amplitude){window.amplitude=amplitude;self.ready()});return}this.load(function(){self.ready()})};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();var revenue=track.revenue();window.amplitude.logEvent(event,props);if(revenue){window.amplitude.logRevenue(revenue,props.quantity,props.productId)}};Amplitude.prototype.setDomain=function(href){var domain=top(href);window.amplitude.setDomain(domain)};Amplitude.prototype.setDeviceId=function(deviceId){if(deviceId)window.amplitude.setDeviceId(deviceId)}},{"analytics.js-integration":90,"utm-params":125,"top-domain":126}],125:[function(require,module,exports){var parse=require("querystring").parse;module.exports=utm;function utm(query){if("?"==query.charAt(0))query=query.substring(1);var query=query.replace(/\?/g,"&");var params=parse(query);var param;var ret={};for(var key in params){if(~key.indexOf("utm_")){param=key.substr(4);if("campaign"==param)param="name";ret[param]=params[key]}}return ret}},{querystring:127}],127:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");var pattern=/(\w+)\[(\d+)\]/;exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=pattern.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:128,type:7}],128:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],126:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:129}],129:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host||location.host,port:"0"===a.port||""===a.port?port(a.protocol):a.port,hash:a.hash,hostname:a.hostname||location.hostname,pathname:a.pathname.charAt(0)!="/"?"/"+a.pathname:a.pathname,protocol:!a.protocol||":"==a.protocol?location.protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){return 0==url.indexOf("//")||!!~url.indexOf("://")};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);var location=exports.parse(window.location.href);return url.hostname!==location.hostname||url.port!==location.port||url.protocol!==location.protocol};function port(protocol){switch(protocol){case"http:":return 80;case"https:":return 443;default:return location.port}}},{}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").option("appcuesId","");Appcues.prototype.initialize=function(){this.load(this.ready)};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var id=this.options.appcuesId||"appcues";var script=load("//fast.appcues.com/"+id+".js",callback)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.userId(),identify.traits())}},{"analytics.js-integration":90,"load-script":130,is:93}],130:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":117,"next-tick":105,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Atatus=module.exports=integration("Atatus").global("atatus").option("apiKey","").tag('<script src="//www.atatus.com/atatus.js">');Atatus.prototype.initialize=function(page){var self=this;this.load(function(){window.atatus.config(self.options.apiKey).install();self.ready()})};Atatus.prototype.loaded=function(){return is.object(window.atatus)};Atatus.prototype.identify=function(identify){window.atatus.setCustomData({person:identify.traits()})}},{"analytics.js-integration":90,is:93}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var Autosend=module.exports=integration("Autosend").global("_autosend").option("appKey","").tag('<script id="asnd-tracker" src="https://d2zjxodm1cz8d6.cloudfront.net/js/v1/autosend.js" data-auth-key="{{ appKey }}">');Autosend.prototype.initialize=function(page){window._autosend=window._autosend||[];(function(){var a,b,c;a=function(f){return function(){window._autosend.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track","cb"];for(c=0;c<b.length;c++){window._autosend[b[c]]=a(b[c])}})();this.load(this.ready)};Autosend.prototype.loaded=function(){return!!window._autosend};Autosend.prototype.identify=function(identify){var id=identify.userId();if(!id)return;var traits=identify.traits();traits.id=id;window._autosend.identify(traits)};Autosend.prototype.track=function(track){window._autosend.track(track.event())}},{"analytics.js-integration":90}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":90,each:4}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").global("uetq").option("tagId","").tag('<script src="//bat.bing.com/bat.js">');Bing.prototype.initialize=function(){window.uetq=window.uetq||[];var self=this;self.load(function(){var setup={ti:self.options.tagId,q:window.uetq};window.uetq=new UET(setup);self.ready()})};Bing.prototype.loaded=function(){return!!(window.uetq&&window.uetq.push!==Array.prototype.push)};Bing.prototype.page=function(){window.uetq.push("pageLoad")};Bing.prototype.track=function(track){var event={ea:"track",el:track.event()};if(track.category())event.ec=track.category();if(track.revenue())event.ev=track.revenue();window.uetq.push(event)}},{"analytics.js-integration":90,"on-body":131,domify:121,extend:132,bind:103,when:133,each:4}],131:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:114}],132:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],133:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:96}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var Blueshift=module.exports=integration("Blueshift").global("blueshift").global("_blueshiftid").option("apiKey","").option("retarget",false).tag('<script src="https://cdn.getblueshift.com/blueshift.js">');Blueshift.prototype.initialize=function(page){window.blueshift=window.blueshift||[];window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click","pageload","capture","retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])};window.blueshift.load(this.options.apiKey);this.load(this.ready)};Blueshift.prototype.loaded=function(){return!!(window.blueshift&&window._blueshiftid)};Blueshift.prototype.page=function(page){if(this.options.retarget)window.blueshift.retarget();var properties=page.properties();properties._bsft_source="segment.com";window.blueshift.pageload(properties)};Blueshift.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits._bsft_source="segment.com";window.blueshift.identify(traits)};Blueshift.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits._bsft_source="segment.com";window.blueshift.track("group",traits)};Blueshift.prototype.track=function(track){var properties=track.properties();properties._bsft_source="segment.com";window.blueshift.track(track.event(),properties)}},{"analytics.js-integration":90}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":90,facade:134,"load-pixel":135,querystring:136,each:4}],134:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":137,"./alias":138,"./group":139,"./identify":140,"./track":141,"./page":142,"./screen":143}],137:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":144,"./is-enabled":145,"./utils":146,"./address":147,"obj-case":94,"new-date":148}],144:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:149,isodate:150,each:4}],149:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":124,type:7,"component-type":7}],150:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],145:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],146:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:151,clone:152,type:7}],151:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],152:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":7,type:7}],147:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();var props=this.properties?this.properties():{};return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)||get(props,"address."+a)||get(props,a)||(b?get(props,"address."+b):null)||(b?get(props,b):null)}}}},{"obj-case":94}],148:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:153,isodate:150,"./milliseconds":154,"./seconds":155}],153:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":124,type:7}],154:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],155:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],138:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":146,"./facade":137}],139:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":146,"./address":147,"is-email":156,"new-date":148,"./facade":137}],156:[function(require,module,exports){ module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],140:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday();var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":147,"./facade":137,"is-email":156,"new-date":148,"./utils":146,"obj-case":94,trim:128}],141:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.discount=Facade.proxy("properties.discount");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.properties(),"subtotal");var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;if(n=this.discount())total+=n;return total};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":146,"./facade":137,"./identify":140,"is-email":156,"obj-case":94}],142:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");Page.prototype.referrer=function(){return this.proxy("properties.referrer")||this.proxy("context.referrer.url")};Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":146,"./facade":137,"./track":141}],143:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":146,"./page":142,"./track":141}],135:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:127,substitute:157}],157:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],136:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:128,type:7}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":90,"next-tick":105}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var umd="function"==typeof define&&define.amd;var src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js";var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="'+src+'">');Bugsnag.prototype.initialize=function(page){var self=this;if(umd){window.require([src],function(bugsnag){bugsnag.apiKey=self.options.apiKey;window.Bugsnag=bugsnag;self.ready()});return}this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":90,is:93,extend:132,"on-error":158}],158:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],21:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var category=page.category();if(category)window._sf_async_config.sections=category;var author=page.proxy("properties.author");if(author)window._sf_async_config.authors=author;var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":90,defaults:159,"on-body":131}],159:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],22:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":90,"global-queue":160,each:4}],160:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],23:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":161,domify:121,each:4,"analytics.js-integration":90,is:93,"use-https":92,"on-body":131}],161:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],24:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};var traits=identify.traits();var username=identify.username();var email=identify.email();var name=identify.name();if(username||email||name)traits.username=username||email||name;extend(window.clicky_custom.session,traits)};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:134,extend:132,"analytics.js-integration":90,is:93}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE};Comscore.prototype.page=function(page){window.COMSCORE.beacon(this.options)}},{"analytics.js-integration":90,"use-https":92}],26:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":90}],27:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":90,"global-queue":160,facade:134,throttle:162,"to-iso-string":163,clone:97,each:4,bind:103}],162:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],163:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],28:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({createdAt:"created"});traits=alias(traits,{created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:164,"convert-dates":165,facade:134,"analytics.js-integration":90}],164:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:152}],165:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:93,clone:97}],29:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("_dc").global("_dcqi").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window._dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:164,"analytics.js-integration":90,is:93,"load-script":130,"global-queue":160}],30:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:132,"analytics.js-integration":90,"on-error":158,"global-queue":160}],31:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":90,"global-queue":160}],32:[function(require,module,exports){"use strict";var bind=require("bind");var domify=require("domify");var each=require("each");var extend=require("extend");var integration=require("analytics.js-integration");var json=require("json");var Extole=module.exports=integration("Extole").global("extole").option("clientId","").mapping("events").tag("main",'<script src="//tags.extole.com/{{ clientId }}/core.js">');Extole.prototype.initialize=function(){if(this.loaded())return this.ready();this.load("main",bind(this,this.ready))};Extole.prototype.loaded=function(){return!!window.extole};Extole.prototype.track=function(track){var user=this.analytics.user();var traits=user.traits();var userId=user.id();var email=traits.email;if(!userId&&!email){return this.debug("User must be identified before `#track` calls")}var event=track.event();var extoleEvents=this.events(event);if(!extoleEvents.length){return this.debug("No events found for %s",event)}each(extoleEvents,bind(this,function(extoleEvent){this._registerConversion(this._createConversionTag({type:extoleEvent,params:this._formatConversionParams(event,email,userId,track.properties())}))}))};Extole.prototype._registerConversion=function(conversionTag){if(window.extole.main&&window.extole.main.fireConversion){return window.extole.main.fireConversion(conversionTag)}if(window.extole.initializeGo){window.extole.initializeGo().andWhenItsReady(function(){window.extole.main.fireConversion(conversionTag)})}};Extole.prototype._formatConversionParams=function(event,email,userId,properties){var total;if(properties.total){total=properties.total;delete properties.total;properties["tag:cart_value"]=total}return extend({"tag:segment_event":event,e:email,partner_conversion_id:userId},properties)};Extole.prototype._createConversionTag=function(conversion){return domify('<script type="extole/conversion">'+json.stringify(conversion)+"</script>")}},{bind:103,domify:121,each:4,extend:132,"analytics.js-integration":90,json:166}],166:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":167}],167:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){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(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep; function quote(string){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){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}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{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})})}},{"analytics.js-integration":90,"global-queue":160,each:4}],34:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":160,"analytics.js-integration":90,facade:134,each:4}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":90,bind:103,when:133,is:93}],36:[function(require,module,exports){var foldl=require("foldl");var is=require("is");var camel=require("to-camel-case");var integration=require("analytics.js-integration");var FullStory=module.exports=integration("FullStory").option("org","").option("debug",false).tag('<script src="https://www.fullstory.com/s/fs.js"></script>');FullStory.prototype.initialize=function(){var self=this;window._fs_debug=this.options.debug;window._fs_host="www.fullstory.com";window._fs_org=this.options.org;(function(m,n,e,t,l,o,g,y){g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b)};g.q=[];g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){FS(l,v)};g.setSessionVars=function(v){FS("session",v)};g.setPageVars=function(v){FS("page",v)};self.ready();self.load()})(window,document,"FS","script","user")};FullStory.prototype.loaded=function(){return!!window.FS};FullStory.prototype.identify=function(identify){var id=identify.userId()||identify.anonymousId();var traits=identify.traits({name:"displayName"});var newTraits=foldl(function(results,value,key){if(key!=="id")results[key==="displayName"||key==="email"?key:convert(key,value)]=value;return results},{},traits);window.FS.identify(String(id),newTraits)};function convert(trait,value){trait=camel(trait);if(is.string(value))return trait+="_str";if(isInt(value))return trait+="_int";if(isFloat(value))return trait+="_real";if(is.date(value))return trait+="_date";if(is.boolean(value))return trait+="_bool"}function isFloat(n){return n===+n&&n!==(n|0)}function isInt(n){return n===+n&&n===(n|0)}},{foldl:168,is:93,"to-camel-case":169,"analytics.js-integration":90}],168:[function(require,module,exports){"use strict";var each=require("each");var foldl=function foldl(iterator,accumulator,collection){if(typeof iterator!=="function"){throw new TypeError("Expected a function but received a "+typeof iterator)}each(function(val,i,collection){accumulator=iterator(accumulator,val,i,collection)},collection);return accumulator};module.exports=foldl},{each:170}],170:[function(require,module,exports){"use strict";var keys=require("keys");var objToString=Object.prototype.toString;var isNumber=function isNumber(val){var type=typeof val;return type==="number"||type==="object"&&objToString.call(val)==="[object Number]"};var isArray=typeof Array.isArray==="function"?Array.isArray:function isArray(val){return objToString.call(val)==="[object Array]"};var isArrayLike=function isArrayLike(val){return val!=null&&(isArray(val)||val!=="function"&&isNumber(val.length))};var arrayEach=function arrayEach(iterator,array){for(var i=0;i<array.length;i+=1){if(iterator(array[i],i,array)===false){break}}};var baseEach=function baseEach(iterator,object){var ks=keys(object);for(var i=0;i<ks.length;i+=1){if(iterator(object[ks[i]],ks[i],object)===false){break}}};var each=function each(iterator,collection){return(isArrayLike(collection)?arrayEach:baseEach).call(this,iterator,collection)};module.exports=each},{keys:171}],171:[function(require,module,exports){"use strict";var strCharAt=String.prototype.charAt;var charAt=function(str,index){return strCharAt.call(str,index)};var hop=Object.prototype.hasOwnProperty;var toStr=Object.prototype.toString;var has=function has(context,prop){return hop.call(context,prop)};var isString=function isString(val){return toStr.call(val)==="[object String]"};var isArrayLike=function isArrayLike(val){return val!=null&&(typeof val!=="function"&&typeof val.length==="number")};var indexKeys=function indexKeys(target,pred){pred=pred||has;var results=[];for(var i=0,len=target.length;i<len;i+=1){if(pred(target,i)){results.push(String(i))}}return results};var objectKeys=function objectKeys(target,pred){pred=pred||has;var results=[];for(var key in target){if(pred(target,key)){results.push(String(key))}}return results};module.exports=function keys(source){if(source==null){return[]}if(isString(source)){return indexKeys(source,charAt)}if(isArrayLike(source)){return indexKeys(source,has)}return objectKeys(source)}},{}],169:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":122}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":90,"global-queue":160}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":90,"on-body":131}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var defaults=require("defaults");var load=require("load-script");var keys=require("object").keys;var select=require("select");var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","auto").option("doubleClick",false).option("enhancedEcommerce",false).option("enhancedLinkAttribution",false).option("nonInteraction",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(integration.options.classic){integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic}else if(integration.options.enhancedEcommerce){integration.viewedProduct=integration.viewedProductEnhanced;integration.clickedProduct=integration.clickedProductEnhanced;integration.addedProduct=integration.addedProductEnhanced;integration.removedProduct=integration.removedProductEnhanced;integration.startedOrder=integration.startedOrderEnhanced;integration.viewedCheckoutStep=integration.viewedCheckoutStepEnhanced;integration.completedCheckoutStep=integration.completedCheckoutStepEnhanced;integration.updatedOrder=integration.updatedOrderEnhanced;integration.completedOrder=integration.completedOrderEnhanced;integration.refundedOrder=integration.refundedOrderEnhanced;integration.viewedPromotion=integration.viewedPromotionEnhanced;integration.clickedPromotion=integration.clickedPromotionEnhanced}});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();if(window.location.hostname==="localhost")opts.domain="none";window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var campaign=page.proxy("context.campaign")||{};var pageview={};var pagePath=path(props,this.options);var pageTitle=name||props.title;var track;this._category=category;pageview.page=pagePath;pageview.title=pageTitle;pageview.location=props.url;if(campaign.name)pageview.campaignName=campaign.name;if(campaign.source)pageview.campaignSource=campaign.source;if(campaign.medium)pageview.campaignMedium=campaign.medium;if(campaign.content)pageview.campaignContent=campaign.content;if(campaign.term)pageview.campaignKeyword=campaign.term;var custom=metrics(props,opts);if(length(custom))window.ga("set",custom);window.ga("set",{page:pagePath,title:pageTitle});window.ga("send","pageview",pageview);if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{nonInteraction:1})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{nonInteraction:1})}};GA.prototype.identify=function(identify){var opts=this.options;if(opts.sendUserId&&identify.userId()){window.ga("set","userId",identify.userId())}var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom)};GA.prototype.track=function(track,options){var contextOpts=track.options(this.name);var interfaceOpts=this.options;var opts=defaults(options||{},contextOpts);opts=defaults(opts,interfaceOpts);var props=track.properties();var campaign=track.proxy("context.campaign")||{};var custom=metrics(props,interfaceOpts);if(length(custom))window.ga("set",custom);var payload={eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:!!(props.nonInteraction||opts.nonInteraction)};if(campaign.name)payload.campaignName=campaign.name;if(campaign.source)payload.campaignSource=campaign.source;if(campaign.medium)payload.campaignMedium=campaign.medium;if(campaign.content)payload.campaignContent=campaign.content;if(campaign.term)payload.campaignKeyword=campaign.term;window.ga("send","event",payload)};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});each(products,function(product){var productTrack=createProductTrack(track,product);window.ga("ecommerce:addItem",{category:productTrack.category(),quantity:productTrack.quantity(),price:productTrack.price(),name:productTrack.name(),sku:productTrack.sku(),id:orderId,currency:productTrack.currency()})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{nonInteraction:1})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{nonInteraction:1})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var nonInteraction=!!(props.nonInteraction||opts.nonInteraction);push("_trackEvent",category,event,label,value,nonInteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}GA.prototype.loadEnhancedEcommerce=function(track){if(!this.enhancedEcommerceLoaded){window.ga("require","ec");this.enhancedEcommerceLoaded=true}window.ga("set","&cu",track.currency())};GA.prototype.pushEnhancedEcommerce=function(track){ga("send","event",track.category()||"EnhancedEcommerce",track.event(),{nonInteraction:1})};GA.prototype.startedOrderEnhanced=function(track){this.viewedCheckoutStep(track)};GA.prototype.updatedOrderEnhanced=function(track){this.startedOrderEnhanced(track)};GA.prototype.viewedCheckoutStepEnhanced=function(track){var products=track.products();var props=track.properties();var options=extractCheckoutOptions(props);this.loadEnhancedEcommerce(track);each(products,function(product){var productTrack=createProductTrack(track,product);enhancedEcommerceTrackProduct(productTrack)});window.ga("ec:setAction","checkout",{step:props.step||1,option:options||undefined});this.pushEnhancedEcommerce(track)};GA.prototype.completedCheckoutStepEnhanced=function(track){var props=track.properties();var options=extractCheckoutOptions(props);if(!props.step||!options)return;this.loadEnhancedEcommerce(track);window.ga("ec:setAction","checkout_option",{step:props.step||1,option:options});window.ga("send","event","Checkout","Option")};GA.prototype.completedOrderEnhanced=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;this.loadEnhancedEcommerce(track);each(products,function(product){var productTrack=createProductTrack(track,product);enhancedEcommerceTrackProduct(productTrack)});window.ga("ec:setAction","purchase",{id:orderId,affiliation:props.affiliation,revenue:total,tax:track.tax(),shipping:track.shipping(),coupon:track.coupon()});this.pushEnhancedEcommerce(track)};GA.prototype.refundedOrderEnhanced=function(track){var orderId=track.orderId();var products=track.products();if(!orderId)return;this.loadEnhancedEcommerce(track);each(products,function(product){var track=new Track({properties:product});window.ga("ec:addProduct",{id:track.id()||track.sku(),quantity:track.quantity()})});window.ga("ec:setAction","refund",{id:orderId});this.pushEnhancedEcommerce(track)};GA.prototype.addedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"add");this.pushEnhancedEcommerce(track)};GA.prototype.removedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"remove");this.pushEnhancedEcommerce(track)};GA.prototype.viewedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"detail");this.pushEnhancedEcommerce(track)};GA.prototype.clickedProductEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"click",{list:props.list});this.pushEnhancedEcommerce(track)};GA.prototype.viewedPromotionEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);window.ga("ec:addPromo",{id:track.id(),name:track.name(),creative:props.creative,position:props.position});this.pushEnhancedEcommerce(track)};GA.prototype.clickedPromotionEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);window.ga("ec:addPromo",{id:track.id(),name:track.name(),creative:props.creative,position:props.position});ga("ec:setAction","promo_click",{});this.pushEnhancedEcommerce(track)};function enhancedEcommerceTrackProduct(track){var props=track.properties();window.ga("ec:addProduct",{id:track.id()||track.sku(),name:track.name(),category:track.category(),quantity:track.quantity(),price:track.price(),brand:props.brand,variant:props.variant,currency:track.currency()})}function enhancedEcommerceProductAction(track,action,data){enhancedEcommerceTrackProduct(track);window.ga("ec:setAction",action,data||{})}function extractCheckoutOptions(props){var options=[props.paymentMethod,props.shippingMethod];var valid=select(options,function(e){return e});return valid.length>0?valid.join(", "):null}function createProductTrack(track,properties){properties.currency=properties.currency||track.currency();return new Track({properties:properties})}},{"analytics.js-integration":90,"global-queue":160,object:172,canonical:173,"use-https":92,facade:134,callback:96,defaults:159,"load-script":130,select:174,"obj-case":94,each:4,type:115,url:175,is:93}],172:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],173:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],174:[function(require,module,exports){var toFunction=require("to-function");module.exports=function(arr,fn){var ret=[];fn=toFunction(fn);for(var i=0;i<arr.length;++i){if(fn(arr[i],i)){ret.push(arr[i])}}return ret}},{"to-function":176}],176:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:120,"component-props":120}],175:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],40:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event(); push(props)}},{"global-queue":160,"analytics.js-integration":90}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var is=require("is");var pick=require("pick");var omit=require("omit");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({createdAt:"created_at",firstName:"first_name",lastName:"last_name",title:"company_position",industry:"company_industry"});var specialKeys=["id","email","name","first_name","last_name","username","description","avatar","phone","created_at","company_name","company_size","company_position","company_industry"];var props=pick.apply(null,[traits].concat(specialKeys));props.custom=omit(specialKeys,traits);var id=identify.userId();if(id){push("identify",id,props)}else{push("properties",props)}var email=identify.email();var username=identify.username();var name=email||username||id;if(name)push("set","visitorName",name)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":90,facade:134,callback:96,"load-script":130,"on-body":131,each:4,is:93,pick:177,omit:178}],177:[function(require,module,exports){module.exports=pick;function pick(obj){var keys=[].slice.call(arguments,1);var ret={};for(var i=0,key;key=keys[i];i++){if(key in obj)ret[key]=obj[key]}return ret}},{}],178:[function(require,module,exports){module.exports=omit;function omit(keys,object){var ret={};for(var item in object){ret[item]=object[item]}for(var i=0;i<keys.length;i++){delete ret[keys[i]]}return ret}},{}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").global("heap").option("appId","").tag('<script src="//cdn.heapanalytics.com/js/heap-{{ appId }}.js">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(appid,config){window.heap.appid=appid;window.heap.config=config;var methodFactory=function(type){return function(){heap.push([type].concat(Array.prototype.slice.call(arguments,0)))}};var methods=["clearEventProperties","identify","setEventProperties","track","unsetEventProperty"];for(var i=0;i<methods.length;i++){heap[methods[i]]=methodFactory(methods[i])}};window.heap.load(this.options.appId);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits({email:"_email"});var id=identify.userId();if(id)traits.handle=id;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":90,alias:164}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":90}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":90,is:93}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":90,"global-queue":160,"convert-dates":165}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":90,alias:164}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);var userId=this.analytics.user().anonymousId();if(userId)push("setUserId",userId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.identify=function(identify){push("setUserId",identify.anonymousId())};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.events(track.event());var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.anonymousId()||"";each(events,function(event){if(event!="sale"){push("trackEvent",event,value,eventId)}})}},{"analytics.js-integration":90,"global-queue":160,facade:134,each:4,is:93}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//cdn.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!(window.__insp_&&window.__insp)};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});var email=identify.email();if(email)push("identify",email);push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())};Inspectlet.prototype.page=function(){push("virtualPage")}},{"analytics.js-integration":90,"global-queue":160,alias:164,clone:97}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var del=require("obj-case").del;var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var is=require("is");var Intercom=module.exports=integration("Intercom").global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").tag('<script src="https://widget.intercom.io/widget/{{ appId }}">');Intercom.prototype.initialize=function(page){initialize();this.load(this.ready)};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(){this.bootOrUpdate()};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email){return}if(traits.company!==null&&!is.object(traits.company)){delete traits.company}if(traits.company){defaults(traits.company,group.traits())}if(name)traits.name=name;if(created){del(traits,"created");del(traits,"createdAt");traits.created_at=created}if(companyCreated){del(traits.company,"created");del(traits.company,"createdAt");traits.company.created_at=companyCreated}traits=convertDates(traits,formatDate);if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;this.bootOrUpdate(traits)};Intercom.prototype.group=function(group){var props=group.properties();props=alias(props,{createdAt:"created"});props=alias(props,{created:"created_at"});var id=group.groupId();if(id)props.id=id;api("update",{company:props})};Intercom.prototype.track=function(track){api("trackEvent",track.event(),track.properties())};Intercom.prototype.bootOrUpdate=function(options){options=options||{};var method=this.booted===true?"update":"boot";var activator=this.options.activator;options.app_id=this.options.appId;if(activator!=="#IntercomDefaultWidget"){options.widget={activator:activator}}api(method,options);this.booted=true};function formatDate(date){return Math.floor(date/1e3)}function initialize(){window.Intercom=function(){window.Intercom.q.push(arguments)};window.Intercom.q=[]}function api(){window.Intercom.apply(window.Intercom,arguments)}},{"analytics.js-integration":90,"convert-dates":165,defaults:159,"obj-case":94,"is-email":156,"load-script":130,"is-empty":124,alias:164,each:4,is:93}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};this.addons(props,identify);this.client.setGlobalProperties(function(){return clone(props)})};Keen.prototype.track=function(track){var props=track.properties();this.addons(props,track);this.client.addEvent(track.event(),props)};Keen.prototype.addons=function(obj,msg){var options=this.options;var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});obj.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});obj.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});obj.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});obj.referrer_url=document.referrer;obj.page_url=document.location.href}obj.keen={timestamp:msg.timestamp(),addons:addons}}},{"analytics.js-integration":90,clone:97}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":90,indexof:118,is:93}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("library",'<script src="//scripts.kissmetrics.com/{{ apiKey }}.2.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});this.load("library",function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":90,"global-queue":160,facade:134,alias:164,each:4,is:93}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":90,"global-queue":160,"next-tick":105,alias:164}],54:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var tick=require("next-tick");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").option("listen",false).tag('<script src="//cdn.livechatinc.com/tracking.js">');var integration={name:"livechat",version:"1.0.0"};LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};delete window.__lc.listen;this.load(function(){when(function(){return self.loaded()},function(){if(self.options.listen)self.attachListeners();tick(self.ready)})})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.attachListeners=function(){var self=this;window.LC_API=window.LC_API||{};window.LC_API.on_chat_started=function(data){self.analytics.track("Live Chat Conversation Started",{agentName:data.agent_name},{context:{integration:integration}})};window.LC_API.on_message=function(data){if(data.user_type==="visitor"){self.analytics.track("Live Chat Message Sent",{},{context:{integration:integration}})}else{self.analytics.track("Live Chat Message Received",{agentName:data.agent_name,agentUsername:data.agent_login},{context:{integration:integration}})}};window.LC_API.on_chat_ended=function(){self.analytics.track("Live Chat Conversation Ended")}};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":90,clone:97,each:4,facade:134,when:133,"next-tick":105}],55:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":90,facade:134,"use-https":92}],56:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":90,alias:164}],57:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("crossSubdomainCookie",false).option("secureCookie",false).option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js">');var optionsAliases={cookieName:"cookie_name",crossSubdomainCookie:"cross_subdomain_cookie",secureCookie:"secure_cookie"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:164,clone:97,"convert-dates":165,"analytics.js-integration":90,is:93,"to-iso-string":163,indexof:118,"obj-case":94,some:179}],179:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/identify.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":90,bind:103,when:133,is:93}],59:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":160,"analytics.js-integration":90,each:4}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":90,"use-https":92,each:4,is:93}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">'); Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":90,"global-queue":160}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Identify=require("facade").Identify;var Nudgespot=module.exports=integration("Nudgespot").assumesPageview().option("apiKey","").global("nudgespot").tag('<script id="nudgespot" src="//cdn.nudgespot.com/nudgespot.js">');Nudgespot.prototype.initialize=function(page){window.nudgespot=window.nudgespot||[];window.nudgespot.init=function(n,t){function f(n,m){var a=m.split(".");2==a.length&&(n=n[a[0]],m=a[1]);n[m]=function(){n.push([m].concat(Array.prototype.slice.call(arguments,0)))}}n._version=.1;n._globals=[t];n.people=n.people||[];n.params=n.params||[];m="track register unregister identify set_config people.delete people.create people.update people.create_property people.tag people.remove_Tag".split(" ");for(var i=0;i<m.length;i++)f(n,m[i])};window.nudgespot.init(window.nudgespot,this.options.apiKey);this.load(this.ready)};Nudgespot.prototype.loaded=function(){return!!window.nudgespot&&window.nudgespot.push!==Array.prototype.push};Nudgespot.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({createdAt:"created"});traits=alias(traits,{created:"created_at"});window.nudgespot.identify(identify.userId(),traits)};Nudgespot.prototype.track=function(track){var properties=track.properties();window.nudgespot.track(track.event(),properties)}},{"analytics.js-integration":90,alias:164,facade:134}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("listen",false).option("track",false);var integration={name:"olark",version:"1.0.0"};Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false});if(this.options.listen)this.attachListeners()};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.attachListeners=function(){var self=this;api("chat.onBeginConversation",function(){self.analytics.track("Live Chat Conversation Started",{},{context:{integration:integration}})});api("chat.onMessageToOperator",function(event){self.analytics.track("Live Chat Message Sent",{},{context:{integration:integration}})});api("chat.onMessageToVisitor",function(event){self.analytics.track("Live Chat Message Received",{},{context:{integration:integration}})})};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":90,"use-https":92,"next-tick":105}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var isEmpty=require("is-empty");var foldl=require("foldl");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("listen",false).option("trackNamedPages",true).option("trackCategorizedPages",true);var integration={name:"optimizely",version:"1.0.0"};Optimizely.prototype.initialize=function(){var self=this;if(this.options.variations){tick(function(){self.replay()})}if(this.options.listen){tick(function(){self.roots()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.roots=function(){if(!window.optimizely)return;var data=window.optimizely.data;var allExperiments=data.experiments;if(!data||!data.state||!allExperiments)return;var variationNamesMap=data.state.variationNamesMap;var variationIdsMap=data.state.variationIdsMap;var activeExperimentIds=data.state.activeExperiments;var activeExperiments=getExperiments(activeExperimentIds,variationNamesMap,variationIdsMap,allExperiments);var self=this;each(activeExperiments,function(props){self.analytics.track("Experiment Viewed",props,{context:{integration:integration}})})};function getExperiments(activeExperimentIds,variationNamesMap,variationIdsMap,allExperiments){return foldl(function(results,experimentId){var experiment=allExperiments[experimentId];if(experiment){results.push({variationName:variationNamesMap[experimentId],variationId:variationIdsMap[experimentId],experimentId:experimentId,experimentName:experiment.name})}return results},[],activeExperimentIds)}Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data||!data.experiments||!data.state)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":90,"global-queue":160,callback:96,"next-tick":105,bind:103,each:4,"is-empty":124,foldl:168}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var omit=require("omit");var Outbound=module.exports=integration("Outbound").global("outbound").option("publicApiKey","").tag('<script src="//cdn.outbound.io/{{ publicApiKey }}.js">');Outbound.prototype.initialize=function(page){window.outbound=window.outbound||[];window.outbound.methods=["identify","track","registerApnsToken","registerGcmToken","disableApnsToken","disableGcmToken"];window.outbound.factory=function(method){return function(){var args=Array.prototype.slice.call(arguments);args.unshift(method);window.outbound.push(args);return window.outbound}};for(var i=0;i<window.outbound.methods.length;i++){var key=window.outbound.methods[i];window.outbound[key]=window.outbound.factory(key)}if(!document.getElementById("outbound-js")){var script=document.createElement("script");script.type="text/javascript";script.id="outbound-js";script.async=true;script.src="//cdn.outbound.io/pub-3e2b0899b2c81c6f0c59342d1ff057c3.js";var first=document.getElementsByTagName("script")[0];first.parentNode.insertBefore(script,first)}this.load(this.ready)};Outbound.prototype.loaded=function(){return window.outbound};Outbound.prototype.identify=function(identify){var traits=identify.traits();var userAttributes={user_id:traits.id,attributes:omit(["id","email","phone","firstName","lastName"],traits),email:traits.email,phone_number:traits.phone,first_name:traits.firstName,last_name:traits.lastName};outbound.identify(userAttributes.user_id,userAttributes)};Outbound.prototype.track=function(track){window.outbound.track(track.event(),track.properties())}},{"analytics.js-integration":90,omit:178}],66:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_pq");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pq").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pq=window._pq||[];this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pq&&window._pq.push)};PerfectAudience.prototype.track=function(track){var total=track.total()||track.revenue();var orderId=track.orderId();var props={};var sendProps=false;if(total){props.revenue=total;sendProps=true}if(orderId){props.orderId=orderId;sendProps=true}if(!sendProps)return push("track",track.event());return push("track",track.event(),props)};PerfectAudience.prototype.viewedProduct=function(track){var product=track.id()||track.sku();push("track",track.event());push("trackProduct",product)};PerfectAudience.prototype.completedOrder=function(track){var total=track.total()||track.revenue();var orderId=track.orderId();var props={};if(total)props.revenue=total;if(orderId)props.orderId=orderId;push("track",track.event(),props)}},{"analytics.js-integration":90,"global-queue":160}],67:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":90,"global-queue":160,"load-date":161}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var is=require("is");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").option("customVariableLimit",5).mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue();var category=track.category()||"All";var action=track.event();var name=track.proxy("properties.name")||track.proxy("properties.label");var value=track.value()||track.revenue();var options=track.options("Piwik");var customVariables=options.customVars||options.cvar;if(!is.object(customVariables)){customVariables={}}for(var i=1;i<=this.options.customVariableLimit;i+=1){if(customVariables[i]){push("setCustomVariable",i.toString(),customVariables[i][0],customVariables[i][1],"page")}}each(goals,function(goal){push("trackGoal",goal,revenue)});push("trackEvent",category,action,name,value)}},{"analytics.js-integration":90,"global-queue":160,each:4,is:93}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_preactq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_preactq").global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/preact-4.1.min.js">');Preact.prototype.initialize=function(page){window._preactq=window._preactq||[];window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._preactq&&window._preactq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":90,"convert-dates":165,"global-queue":160,alias:164}],70:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":90,"global-queue":160,facade:134,bind:103,when:133}],71:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var is=require("is");var reduce=require("reduce");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this._labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var customLabels=page.proxy("properties.label");var labels=this._labels("page",category,name,customLabels);var settings={event:"refresh",labels:labels,qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var orderId=track.orderId();var customLabels=track.proxy("properties.label");var labels=this._labels("event",name,customLabels);var settings={event:"click",labels:labels,qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(orderId)settings.orderid=orderId;if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var customLabels=track.proxy("properties.label");var labels=this._labels("event",name,customLabels);var category=track.category();var repeat=track.proxy("properties.repeat");if(this.options.advertise&&category){labels+=","+this._labels("pcat",category)}if("boolean"==typeof repeat){labels+=",_fp.customer."+(repeat?"repeat":"new")}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype._labels=function(type){var args=Array.prototype.slice.call(arguments,1);var advertise=this.options.advertise;if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;var separator=advertise?" ":".";var ret=reduce(args,function(ret,arg){if(arg!=null){ret.push(String(arg).replace(/, /g,","))}return ret},[]).join(separator);return[type,ret].join(".")}},{"global-queue":160,"analytics.js-integration":90,"use-https":92,is:93,reduce:180}],180:[function(require,module,exports){module.exports=function(arr,fn,initial){var idx=0;var len=arr.length;var curr=arguments.length==3?initial:arr[idx++];while(idx<len){curr=fn.call(null,curr,arr[idx],++idx,arr)}return curr}},{}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a,b){function c(b){this.shimId=++h,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function d(b,c,d){a._rollbarWrappedError&&(d[4]||(d[4]=a._rollbarWrappedError),d[5]||(d[5]=a._rollbarWrappedError._rollbarContext),a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function e(b){var d=c;return g(function(){if(this.notifier)return this.notifier[b].apply(this.notifier,arguments);var c=this,e="scope"===b;e&&(c=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:c,method:b,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?c:void 0})}function f(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b&&b._wrapped?b._wrapped:b,c)}}}function g(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var h=0;c.init=function(a,b){var e=b.globalAlias||"Rollbar";if("object"==typeof a[e])return a[e];a._rollbarShimQueue=[],a._rollbarWrappedError=null,b=b||{};var h=new c;return g(function(){if(h.configure(b),b.captureUncaught){var c=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);d(h,c,a)};var g,i,j="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(g=0;g<j.length;++g)i=j[g],a[i]&&a[i].prototype&&f(h,a[i].prototype)}return a[e]=h,h},h.logger)()},c.prototype.loadFull=function(a,b,c,d,e){var f=g(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=g(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}"function"==typeof e&&e(b)},this.logger);g(function(){c?f():a.addEventListener?a.addEventListener("load",f,!1):a.attachEvent("onload",f)},this.logger)()},c.prototype.wrap=function(b,c){try{var d;if(d="function"==typeof c?c:function(){return c||{}},"function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw c._rollbarContext=d(),c._rollbarContext._wrappedSource=b.toString(),a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var e in b)b.hasOwnProperty(e)&&(b._wrapped[e]=b[e])}return b._wrapped}catch(f){return b}};for(var i="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),j=0;j<i.length;++j)c.prototype[i[j]]=e(i[j]);var k="//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||k;var l=c.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":90,extend:132,is:93}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").option("referralImage","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var paymentProviderId=identify.proxy("traits.paymentProviderId");var accountStatus=identify.proxy("traits.accountStatus");var referralCode=identify.proxy("traits.referralCode");var image=identify.proxy("traits.referralImage")||this.options.referralImage;var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(paymentProviderId)init.payment_provider_id=paymentProviderId;if(init.payment_provider_id=="null")init.payment_provider_id=null;if(accountStatus)init.account_status=accountStatus;if(referralCode)init.referral_code=referralCode;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()};SaaSquatch.prototype.group=function(group){var sqh=window._sqh;var props=group.properties();var id=group.groupId();var image=group.proxy("traits.referralImage")||this.options.referralImage;var opts=group.options(this.name);if(this.called)return;var init={tenant_alias:this.options.tenantAlias,account_id:id};if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":90}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var when=require("when");var SatisMeter=module.exports=integration("SatisMeter").global("satismeter").option("token","").tag('<script src="https://app.satismeter.com/satismeter.js">');SatisMeter.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};SatisMeter.prototype.loaded=function(){return!!window.satismeter};SatisMeter.prototype.identify=function(identify){var traits=identify.traits();traits.token=this.options.token;traits.user={id:identify.userId()};if(identify.name()){traits.user.name=identify.name()}if(identify.email()){traits.user.email=identify.email()}if(identify.created()){traits.user.signUpDate=identify.created().toISOString()}delete traits.id;delete traits.email;delete traits.name;delete traits.created;window.satismeter(traits)}},{"analytics.js-integration":90,when:133}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var localstorage=require("store");var protocol=require("protocol");var utm=require("utm-params");var ads=require("ad-params");var send=require("send-json");var cookie=require("cookie");var clone=require("clone");var uuid=require("uuid");var top=require("top-domain");var extend=require("extend");var json=require("segmentio/json@1.0.0");var options={maxage:31536e6,secure:false,path:"/"};var Segment=exports=module.exports=integration("Segment.io").option("apiKey","");exports.storage=function(){return"file:"==protocol()||"chrome-extension:"==protocol()?localstorage:cookie};exports.global=window;Segment.prototype.initialize=function(page){var self=this;this.ready();this.analytics.on("invoke",function(msg){var action=msg.action();var listener="on"+msg.action();self.debug("%s %o",action,msg);if(self[listener])self[listener](msg);self.ready()})};Segment.prototype.loaded=function(){return true};Segment.prototype.onpage=function(page){this.send("/p",page.json())};Segment.prototype.onidentify=function(identify){this.send("/i",identify.json())};Segment.prototype.ongroup=function(group){this.send("/g",group.json())};Segment.prototype.ontrack=function(track){var json=track.json();delete json.traits;this.send("/t",json)};Segment.prototype.onalias=function(alias){var json=alias.json();var user=this.analytics.user();json.previousId=json.previousId||json.from||user.id()||user.anonymousId();json.userId=json.userId||json.to;delete json.from;delete json.to;this.send("/a",json)};Segment.prototype.normalize=function(msg){this.debug("normalize %o",msg);var user=this.analytics.user();var global=exports.global;var query=global.location.search;var ctx=msg.context=msg.context||msg.options||{};delete msg.options;msg.writeKey=this.options.apiKey;ctx.userAgent=navigator.userAgent;if(!ctx.library)ctx.library={name:"analytics.js",version:this.analytics.VERSION};if(query)ctx.campaign=utm(query);this.referrerId(query,ctx);msg.userId=msg.userId||user.id();msg.anonymousId=user.anonymousId();msg.messageId=uuid();msg.sentAt=new Date;this.debug("normalized %o",msg);return msg};Segment.prototype.send=function(path,msg,fn){var url=scheme()+"//api.segment.io/v1"+path;var headers={"Content-Type":"text/plain"};var fn=fn||noop;var self=this;msg=this.normalize(msg);send(url,msg,headers,function(err,res){self.debug("sent %O, received %O",msg,arguments);if(err)return fn(err);res.url=url;fn(null,res)})};Segment.prototype.cookie=function(name,val){var store=Segment.storage();if(arguments.length===1)return store(name);var global=exports.global;var href=global.location.href;var domain="."+top(href);if("."==domain)domain="";this.debug("store domain %s -> %s",href,domain);var opts=clone(options);opts.domain=domain;this.debug("store %s, %s, %o",name,val,opts);store(name,val,opts);if(store(name))return;delete opts.domain;this.debug("fallback store %s, %s, %o",name,val,opts);store(name,val,opts)};Segment.prototype.referrerId=function(query,ctx){var stored=this.cookie("s:context.referrer");var ad;if(stored)stored=json.parse(stored);if(query)ad=ads(query);ad=ad||stored;if(!ad)return;ctx.referrer=extend(ctx.referrer||{},ad);this.cookie("s:context.referrer",json.stringify(ad))};function scheme(){return"http:"==protocol()?"http:":"https:"}function noop(){}},{"analytics.js-integration":90,store:181,protocol:182,"utm-params":125,"ad-params":183,"send-json":184,cookie:185,clone:97,uuid:186,"top-domain":126,extend:132,"segmentio/json@1.0.0":166}],181:[function(require,module,exports){var unserialize=require("unserialize");var each=require("each");var storage;try{storage=window.localStorage}catch(e){storage=null}module.exports=store;function store(key,value){var length=arguments.length;if(0==length)return all();if(2<=length)return set(key,value);if(1!=length)return;if(null==key)return storage.clear();if("string"==typeof key)return get(key);if("object"==typeof key)return each(key,set)}store.supported=!!storage;function set(key,val){return null==val?storage.removeItem(key):storage.setItem(key,JSON.stringify(val))}function get(key){return unserialize(storage.getItem(key))}function all(){var len=storage.length;var ret={};var key;while(0<=--len){key=storage.key(len);ret[key]=get(key)}return ret}},{unserialize:187,each:114}],187:[function(require,module,exports){module.exports=function(val){try{return JSON.parse(val)}catch(e){return val||undefined}}},{}],182:[function(require,module,exports){var define=Object.defineProperty;var initialProtocol=window.location.protocol;var mockedProtocol;module.exports=function(protocol){if(arguments.length===0)return get();else return set(protocol)};module.exports.http=function(){set("http:")};module.exports.https=function(){set("https:")};module.exports.reset=function(){set(initialProtocol)};function get(){return mockedProtocol||window.location.protocol}function set(protocol){try{define(window.location,"protocol",{get:function(){return protocol}})}catch(err){mockedProtocol=protocol}}},{}], 183:[function(require,module,exports){var parse=require("querystring").parse;module.exports=ads;var QUERYIDS={btid:"dataxu",urid:"millennial-media"};function ads(query){var params=parse(query);for(var key in params){for(var id in QUERYIDS){if(key===id){return{id:params[key],type:QUERYIDS[id]}}}}}},{querystring:127}],184:[function(require,module,exports){var encode=require("base64-encode");var cors=require("has-cors");var jsonp=require("jsonp");var JSON=require("json");exports=module.exports=cors?json:base64;exports.callback="callback";exports.prefix="data";exports.json=json;exports.base64=base64;exports.type=cors?"xhr":"jsonp";function json(url,obj,headers,fn){if(3==arguments.length)fn=headers,headers={};var req=new XMLHttpRequest;req.onerror=fn;req.onreadystatechange=done;req.open("POST",url,true);for(var k in headers)req.setRequestHeader(k,headers[k]);req.send(JSON.stringify(obj));function done(){if(4==req.readyState)return fn(null,req)}}function base64(url,obj,_,fn){if(3==arguments.length)fn=_;var prefix=exports.prefix;obj=encode(JSON.stringify(obj));obj=encodeURIComponent(obj);url+="?"+prefix+"="+obj;jsonp(url,{param:exports.callback},function(err,obj){if(err)return fn(err);fn(null,{url:url,body:obj})})}},{"base64-encode":188,"has-cors":189,jsonp:190,json:166}],188:[function(require,module,exports){var utf8Encode=require("utf8-encode");var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";module.exports=encode;function encode(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=utf8Encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=(chr1&3)<<4|chr2>>4;enc3=(chr2&15)<<2|chr3>>6;enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4)}return output}},{"utf8-encode":191}],191:[function(require,module,exports){module.exports=encode;function encode(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c)}else if(c>127&&c<2048){utftext+=String.fromCharCode(c>>6|192);utftext+=String.fromCharCode(c&63|128)}else{utftext+=String.fromCharCode(c>>12|224);utftext+=String.fromCharCode(c>>6&63|128);utftext+=String.fromCharCode(c&63|128)}}return utftext}},{}],189:[function(require,module,exports){try{module.exports=typeof XMLHttpRequest!=="undefined"&&"withCredentials"in new XMLHttpRequest}catch(err){module.exports=false}},{}],190:[function(require,module,exports){var debug=require("debug")("jsonp");module.exports=jsonp;var count=0;function noop(){}function jsonp(url,opts,fn){if("function"==typeof opts){fn=opts;opts={}}if(!opts)opts={};var prefix=opts.prefix||"__jp";var param=opts.param||"callback";var timeout=null!=opts.timeout?opts.timeout:6e4;var enc=encodeURIComponent;var target=document.getElementsByTagName("script")[0]||document.head;var script;var timer;var id=prefix+count++;if(timeout){timer=setTimeout(function(){cleanup();if(fn)fn(new Error("Timeout"))},timeout)}function cleanup(){script.parentNode.removeChild(script);window[id]=noop}window[id]=function(data){debug("jsonp got",data);if(timer)clearTimeout(timer);cleanup();if(fn)fn(null,data)};url+=(~url.indexOf("?")?"&":"?")+param+"="+enc(id);url=url.replace("?&","?");debug('jsonp req "%s"',url);script=document.createElement("script");script.src=url;target.parentNode.insertBefore(script,target)}},{debug:192}],192:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":193,"./debug":194}],193:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],194:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],185:[function(require,module,exports){var debug=require("debug")("cookie");module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toUTCString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}function encode(value){try{return encodeURIComponent(value)}catch(e){debug("error `encode(%o)` - %o",value,e)}}function decode(value){try{return decodeURIComponent(value)}catch(e){debug("error `decode(%o)` - %o",value,e)}}},{debug:192}],186:[function(require,module,exports){module.exports=function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)}},{}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.16/native/raven.min.js">');Sentry.prototype.initialize=function(){var dsn=this.options.config;window.RavenConfig={dsn:dsn};this.load(this.ready)};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":90,is:93}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var tick=require("next-tick");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").global("SnapEngage").option("apiKey","").option("listen",false).tag('<script src="//www.snapengage.com/cdn/js/{{ apiKey }}.js">');var integration={name:"snapengage",version:"1.0.0"};SnapEngage.prototype.initialize=function(page){var self=this;this.load(function(){if(self.options.listen)self.attachListeners();tick(self.ready)})};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)&&is.object(window.SnapEngage)};SnapEngage.prototype.attachListeners=function(){var self=this;window.SnapEngage.setCallback("StartChat",function(email,message,type){self.analytics.track("Live Chat Conversation Started",{},{context:{integration:integration}})});window.SnapEngage.setCallback("ChatMessageReceived",function(agent,message){self.analytics.track("Live Chat Message Received",{agentUsername:agent},{context:{integration:integration}})});window.SnapEngage.setCallback("ChatMessageSent",function(message){self.analytics.track("Live Chat Message Sent",{},{context:{integration:integration}})});window.SnapEngage.setCallback("Close",function(type,status){self.analytics.track("Live Chat Conversation Ended",{},{context:{integration:integration}})})};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":90,is:93,"next-tick":105}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":90,bind:103,when:133}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var SupportHero=module.exports=integration("SupportHero").assumesPageview().global("supportHeroWidget").option("token","").option("track",false).tag('<script src="https://d29l98y0pmei9d.cloudfront.net/js/widget.min.js?k={{ token }}">');SupportHero.prototype.initialize=function(page){window.supportHeroWidget={};window.supportHeroWidget.setUserId=window.supportHeroWidget.setUserId||function(){};window.supportHeroWidget.setUserTraits=window.supportHeroWidget.setUserTraits||function(){};this.load(this.ready)};SupportHero.prototype.loaded=function(){return!!window.supportHeroWidget};SupportHero.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id){window.supportHeroWidget.setUserId(id)}if(traits){window.supportHeroWidget.setUserTraits(traits)}}},{"analytics.js-integration":90}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":90,slug:101,"global-queue":160}],81:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(category)window.trak.io.channel("category");if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){var properties=track.properties();var channel=track.proxy("properties.channel");if(channel){delete properties.channel;window.trak.io.track(track.event(),channel,properties)}else{window.trak.io.track(track.event(),properties)}};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":90,alias:164,clone:97}],82:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":90,each:4}],83:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var clone=require("clone");var Userlike=module.exports=integration("Userlike").assumesPageview().global("userlikeConfig").global("userlikeData").option("secretKey","").option("listen",false).tag('<script src="//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/{{ secretKey }}.js">');var integration={name:"userlike",version:"1.0.0"};Userlike.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});segment_base_info=clone(this.options);segment_base_info.visitor={name:identify.name(),email:identify.email()};if(!window.userlikeData)window.userlikeData={custom:{}};window.userlikeData.custom.segmentio=segment_base_info;this.load(function(){if(self.options.listen)self.attachListeners();self.ready()})};Userlike.prototype.loaded=function(){return!!(window.userlikeConfig&&window.userlikeData)};Userlike.prototype.attachListeners=function(){var self=this;window.userlikeTrackingEvent=function(eventName,globalCtx,sessionCtx){if(eventName==="chat_started"){self.analytics.track("Live Chat Conversation Started",{agentId:sessionCtx.operator_id,agentName:sessionCtx.operator_name},{context:{integration:integration}})}if(eventName==="message_operator_terminating"){self.analytics.track("Live Chat Message Sent",{agentId:sessionCtx.operator_id,agentName:sessionCtx.operator_name},{context:{integration:integration}})}if(eventName==="message_client_terminating"){self.analytics.track("Live Chat Message Received",{agentId:sessionCtx.operator_id,agentName:sessionCtx.operator_name},{context:{integration:integration}})}if(eventName==="chat_quit"){self.analytics.track("Live Chat Conversation Ended",{agentId:sessionCtx.operator_id,agentName:sessionCtx.operator_name},{context:{integration:integration}})}}}},{"analytics.js-integration":90,facade:134,clone:97}],84:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("screenshotEnabled",true).option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).option("customTicketFields",{}).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position",screenshotEnabled:"screenshot_enabled",customTicketFields:"ticket_custom_fields"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":90,"global-queue":160,"convert-dates":165,"to-unix-timestamp":195,alias:164,clone:97}],195:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],85:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var objCase=require("obj-case");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){var regex=/[uU]nsubscribe/;if(track.event().match(regex)){push("unsubscribe",{id:track.properties().id})}else{push("track",track.event(),track.properties())}};Vero.prototype.alias=function(alias){var to=alias.to();if(alias.from()){push("reidentify",to,alias.from())}else{push("reidentify",to)}}},{"analytics.js-integration":90,"global-queue":160,"component/cookie":185,"obj-case":94}],86:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true).option("listen",false);var integration={name:"visual-website-optimizer",version:"1.0.0"};VWO.prototype.initialize=function(){var self=this;if(this.options.replay){tick(function(){self.replay()})}if(this.options.listen){tick(function(){self.roots()})}this.ready()};VWO.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;enqueue(function(){_vis_opt_revenue_conversion(total)})};VWO.prototype.replay=function(){var analytics=this.analytics;experiments(function(err,traits){if(traits)analytics.identify(traits)})};VWO.prototype.roots=function(){var analytics=this.analytics;rootExperiments(function(err,data){each(data,function(experimentId,variationName){analytics.track("Experiment Viewed",{experimentId:experimentId,variationName:variationName},{context:{integration:integration}})})})};function rootExperiments(fn){enqueue(function(){var data={};var experimentIds=window._vwo_exp_ids;if(!experimentIds)return fn();each(experimentIds,function(experimentId){var variationName=variation(experimentId);if(variationName)data[experimentId]=variationName});fn(null,data)})}function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":90,"next-tick":105,each:4}],87:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":90,"use-https":92}],88:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":90,"to-snake-case":91,"is-email":156,extend:132,each:4,type:115}],89:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":90,"next-tick":105,bind:103,when:133}],3:[function(require,module,exports){var _analytics=window.analytics;var after=require("after");var bind=require("bind");var callback=require("callback");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var pageDefaults=require("./pageDefaults");var pick=require("pick");var prevent=require("prevent");var querystring=require("querystring");var normalize=require("./normalize");var size=require("object").length;var keys=require("object").keys;var memory=require("./memory");var store=require("./store");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;exports.memory=memory;function Analytics(){this._options({});this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;this.log=debug("analytics.js");bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page();self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.log("initialize %o - %o",name,opts);self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.setAnonymousId=function(id){this.user().anonymousId(id);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);var msg=this.normalize({options:options,traits:user.traits(),userId:user.id()});this._invoke("identify",new Identify(msg));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);var msg=this.normalize({options:options,traits:group.traits(),groupId:group.id()});this._invoke("group",new Group(msg));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;var plan=this.options.plan||{};var events=plan.track||{};var msg=this.normalize({properties:properties,options:options, event:event});if(plan=events[event]){this.log("plan %o - %o",event,plan);if(false==plan.enabled)return this._callback(fn);defaults(msg.integrations,plan.integrations||{})}this._invoke("track",new Track(msg));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;var href=el.getAttribute("href")||el.getAttributeNS("http://www.w3.org/1999/xlink","href")||el.getAttribute("xlink:href");self.track(ev,props);if(href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;properties=clone(properties)||{};if(name)properties.name=name;if(category)properties.category=category;var defs=pageDefaults();defaults(properties,defs);var overrides=pick(keys(defs),properties);if(!is.empty(overrides)){options=options||{};options.context=options.context||{};options.context.page=overrides}var msg=this.normalize({properties:properties,category:category,options:options,name:name});this._invoke("page",new Page(msg));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;var msg=this.normalize({options:options,previousId:from,userId:to});this._invoke("alias",new Alias(msg));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};this.options=options;cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype.reset=function(){this.user().logout();this.group().logout()};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);if(q.ajs_aid)user.anonymousId(q.ajs_aid);return this};Analytics.prototype.normalize=function(msg){msg=normalize(msg,keys(this._integrations));if(msg.anonymousId)user.anonymousId(msg.anonymousId);msg.anonymousId=user.anonymousId();msg.context.page=defaults(msg.context.page||{},pageDefaults());return msg};Analytics.prototype.noConflict=function(){window.analytics=_analytics;return this}},{after:113,bind:196,callback:96,clone:97,"./cookie":197,debug:192,defaults:99,each:4,emitter:112,"./group":198,is:93,"is-email":156,"is-meta":199,"new-date":148,event:200,"./pageDefaults":201,pick:202,prevent:203,querystring:204,"./normalize":205,object:172,"./memory":206,"./store":207,"./user":208,facade:134}],196:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:103,"bind-all":104}],197:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);if("."==domain)domain=null;this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:192,bind:196,cookie:185,clone:97,defaults:99,json:166,"top-domain":209}],209:[function(require,module,exports){var parse=require("url").parse;var cookie=require("cookie");exports=module.exports=domain;exports.cookie=cookie;function domain(url){var cookie=exports.cookie;var levels=exports.levels(url);for(var i=0;i<levels.length;++i){var cname="__tld__";var domain=levels[i];var opts={domain:"."+domain};cookie(cname,1,opts);if(cookie(cname)){cookie(cname,null,opts);return domain}}return""}domain.levels=function(url){var host=parse(url).hostname;var parts=host.split(".");var last=parts[parts.length-1];var levels=[];if(4==parts.length&&parseInt(last,10)==last){return levels}if(1>=parts.length){return levels}for(var i=parts.length-2;0<=i;--i){levels.push(parts.slice(i).join("."))}return levels}},{url:129,cookie:185}],198:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:192,"./entity":210,inherit:211,bind:196}],210:[function(require,module,exports){var debug=require("debug")("analytics:entity");var traverse=require("isodate-traverse");var defaults=require("defaults");var memory=require("./memory");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options);this.initialize()}Entity.prototype.initialize=function(){cookie.set("ajs:cookies",true);if(cookie.get("ajs:cookies")){cookie.remove("ajs:cookies");this._storage=cookie;return}if(store.enabled){this._storage=store;return}debug("warning using memory store both cookies and localStorage are disabled");this._storage=memory};Entity.prototype.storage=function(){return this._storage};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?this.storage().get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){this.storage().set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{debug:192,"isodate-traverse":144,defaults:99,"./memory":206,"./cookie":197,"./store":207,extend:132,clone:97}],206:[function(require,module,exports){var clone=require("clone");var bind=require("bind");var has=Object.prototype.hasOwnProperty;module.exports=bind.all(new Memory);function Memory(){this.store={}}Memory.prototype.set=function(key,value){this.store[key]=clone(value);return true};Memory.prototype.get=function(key){if(!has.call(this.store,key))return;return clone(this.store[key])};Memory.prototype.remove=function(key){delete this.store[key];return true}},{clone:97,bind:196}],207:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:196,defaults:99,"store.js":212}],212:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:166}],211:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],199:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],200:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],201:[function(require,module,exports){var canonical=require("canonical");var url=require("url");function pageDefaults(){return{path:canonicalPath(),referrer:document.referrer,search:location.search,title:document.title,url:canonicalUrl(location.search)}}function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1===i?url:url.slice(0,i)}module.exports=pageDefaults},{canonical:173,url:175}],202:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString;var existy=function(val){return val!=null};var isArray=function(val){return objToString.call(val)==="[object Array]"};var isString=function(val){return typeof val==="string"||objToString.call(val)==="[object String]"};var isObject=function(val){return val!=null&&typeof val==="object"};var pick=function pick(props,object){if(!existy(object)||!isObject(object)){return{}}if(isString(props)){props=[props]}if(!isArray(props)){props=[]}var result={};for(var i=0;i<props.length;i+=1){if(isString(props[i])&&props[i]in object){result[props[i]]=object[props[i]]}}return result};module.exports=pick},{}],203:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],204:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:128,type:7}],205:[function(require,module,exports){var debug=require("debug")("analytics.js:normalize");var indexof=require("component/indexof");var defaults=require("defaults");var map=require("component/map");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;module.exports=normalize;var toplevel=["integrations","anonymousId","timestamp","context"];function normalize(msg,list){var lower=map(list,function(s){return s.toLowerCase()});var opts=msg.options||{};var integrations=opts.integrations||{};var providers=opts.providers||{};var context=opts.context||{};var ret={};debug("<-",msg);each(opts,function(key,value){if(!integration(key))return;if(!has.call(integrations,key))integrations[key]=value;delete opts[key]});delete opts.providers;each(providers,function(key,value){if(!integration(key))return;if(is.object(integrations[key]))return;if(has.call(integrations,key)&&"boolean"==typeof providers[key])return;integrations[key]=value});each(opts,function(key){if(~indexof(toplevel,key)){ret[key]=opts[key]}else{context[key]=opts[key]}});delete msg.options;ret.integrations=integrations;ret.context=context;ret=defaults(ret,msg);debug("->",ret);return ret;function integration(name){return!!(~indexof(list,name)||"all"==name.toLowerCase()||~indexof(lower,name.toLowerCase()))}}},{debug:192,"component/indexof":118,defaults:99,"component/map":213,each:4,is:93}],213:[function(require,module,exports){var toFunction=require("to-function");module.exports=function(arr,fn){var ret=[];fn=toFunction(fn);for(var i=0;i<arr.length;++i){ret.push(fn(arr[i],i))}return ret}},{"to-function":176}],208:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");var uuid=require("uuid");var rawCookie=require("cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.id=function(id){var prev=this._getId();var ret=Entity.prototype.id.apply(this,arguments);if(null==prev)return ret;if(prev!=id&&id)this.anonymousId(null);return ret};User.prototype.anonymousId=function(anonId){var store=this.storage();if(arguments.length){store.set("ajs_anonymous_id",anonId);return this}if(anonId=store.get("ajs_anonymous_id")){return anonId}if(anonId=rawCookie("_sio")){anonId=anonId.split("----")[0];store.set("ajs_anonymous_id",anonId);store.remove("_sio");return anonId}anonId=uuid();store.set("ajs_anonymous_id",anonId);return store.get("ajs_anonymous_id")};User.prototype.logout=function(){Entity.prototype.logout.call(this);this.anonymousId(null)};User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{debug:192,"./entity":210,inherit:211,bind:196,"./cookie":197,uuid:186,cookie:185}],5:[function(require,module,exports){module.exports={name:"analytics",version:"2.8.14",main:"analytics.js",dependencies:{},devDependencies:{}}},{}]},{},{1:""}));
ajax/libs/angular-google-maps/2.0.21/angular-google-maps.js
simudream/cdnjs
/*! angular-google-maps 2.0.21 2015-06-04 * 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 { if (options.transport === 'auto') { return '//maps.googleapis.com/maps/api/js?'; } else { return options.transport + '://maps.googleapis.com/maps/api/js?'; } } }; includeScript = function(options) { var omitOptions, query, script; omitOptions = ['transport', 'isGoogleMapsForWork', 'china']; if (options.isGoogleMapsForWork) { omitOptions.push('key'); } query = _.map(_.omit(options, omitOptions), 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 = { transport: 'https', isGoogleMapsForWork: false, 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() { angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() { return { init: _.once(function() { 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; } }; } 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.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, _getArrayAndKeys, _getIterateeValue, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch; promiseTypes = uiGmapPromise.promiseTypes; isInProgress = uiGmapPromise.isInProgress; promiseStatus = uiGmapPromise.promiseStatus; ExposedPromise = uiGmapPromise.ExposedPromise; SniffedPromise = uiGmapPromise.SniffedPromise; kickPromise = function(sniffedPromise, cancelCb) { var promise; promise = sniffedPromise.promise(); promise.promiseType = sniffedPromise.promiseType; if (promise.$$state) { $log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status))); } promise.cancelCb = cancelCb; return promise; }; doSkippPromise = function(sniffedPromise, lastPromise) { if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) { $log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY"); return true; } return false; }; maybeCancelPromises = function(queue, sniffedPromise, lastPromise) { var first; if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) { if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) { $log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType); lastPromise.cancelCb('cancel safe'); first = queue.peek(); if ((first != null) && isInProgress(first)) { if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) { $log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType); return first.cancelCb('cancel safe'); } else { return $log.warn('first promise was not cancelable'); } } } } }; /* From a High Level: This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces. This is a function and should not be considered a class. So it is run to manage the state (cancel, skip, link) as needed. Purpose: The whole point is to check if there is existing async work going on. If so we wait on it. arguments: - existingPiecesObj = Queue<Promises> - sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise) with its intended type. - cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise gracefully without messing up state. Synopsis: - Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering) where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete - Every Promise that comes 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); if ((cancelCb != null) && _.isFunction(cancelCb)) { return cancelCb(msg); } }; return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger); }; defaultChunkSize = 80; errorObject = { value: null }; tryCatch = function(fn, ctx, args) { var e; 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 _isArray, valOrKey; _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', 'forEach', 'map'])); 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, val; if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) { cnt = chunkSizeOrDontChunk; } else { cnt = array.length; } i = index; keepGoing = true; while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) { val = _getIterateeValue(collection, array, i); keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]); ++i; } if (array) { if (keepGoing && i < array.length) { index = i; if (chunkSizeOrDontChunk) { if ((pauseCb != null) && _.isFunction(pauseCb)) { logTryCatch(pauseCb, void 0, overallD, []); } return $timeout(function() { return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys); }, pauseMilli, false); } } else { return overallD.resolve(); } } }); }; each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var error, overallD, ret; if (chunkSizeOrDontChunk == null) { chunkSizeOrDontChunk = defaultChunkSize; } if (index == null) { index = 0; } if (pauseMilli == null) { pauseMilli = 1; } ret = void 0; overallD = uiGmapPromise.defer(); ret = overallD.promise; if (!pauseMilli) { error = 'pause (delay) must be set from _async!'; $log.error(error); overallD.reject(error); return ret; } return _getArrayAndKeys(collection, _keys, function() { overallD.resolve(); return ret; }, function(array, keys) { doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys); return ret; }); }; map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var results; results = []; return _getArrayAndKeys(collection, _keys, function() { return uiGmapPromise.resolve(results); }, function(array, keys) { return each(collection, function(o) { return results.push(iterator(o)); }, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() { return results; }); }); }; return { each: each, map: map, managePromiseQueue: managePromiseQueue, promiseLock: managePromiseQueue, defaultChunkSize: defaultChunkSize, chunkSizeFrom: function(fromSize, ret) { if (ret == null) { ret = void 0; } if (_.isNumber(fromSize)) { ret = fromSize; } if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) { ret = false; } return ret; } }; } ]); }).call(this); ;(function() { var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() { var BaseObject, baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, ref, value; for (key in obj) { value = obj[key]; if (indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((ref = obj.extended) != null) { ref.apply(this); } return this; }; BaseObject.include = function(obj) { var key, ref, value; for (key in obj) { value = obj[key]; if (indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((ref = obj.included) != null) { ref.apply(this); } return this; }; return BaseObject; })(); return BaseObject; }); }).call(this); ; /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() { return { onChildCreation: function(child) {} }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.$on('$destroy', function() { return CtrlHandle.handle($scope); }); $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [ "uiGmapLogger", function($log) { var _getEventsObj, _hasEvents; _hasEvents = function(obj) { return angular.isDefined(obj.events) && (obj.events != null) && angular.isObject(obj.events); }; _getEventsObj = function(scope, model) { if (_hasEvents(scope)) { return scope; } if (_hasEvents(model)) { return model; } }; return { setEvents: function(gObject, scope, model, ignores) { var eventObj; eventObj = _getEventsObj(scope, model); if (eventObj != null) { return _.compact(_.map(eventObj.events, function(eventHandler, eventName) { var doIgnore; if (ignores) { doIgnore = _(ignores).contains(eventName); } if (eventObj.events.hasOwnProperty(eventName) && angular.isFunction(eventObj.events[eventName]) && !doIgnore) { return google.maps.event.addListener(gObject, eventName, function() { if (!scope.$evalAsync) { scope.$evalAsync = function() {}; } return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments])); }); } })); } }, removeEvents: function(listeners) { 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 _isFalse, _isTruthy, getCoords, getLatitude, getLongitude, validateCoords; _isTruthy = function(value, bool, optionsArray) { return value === bool || optionsArray.indexOf(value) !== -1; }; _isFalse = function(value) { return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']); }; getLatitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[1]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[1]; } else { return value.latitude; } }; getLongitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[0]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[0]; } else { return value.longitude; } }; getCoords = function(value) { if (!value) { return; } if (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 _checkIfReady, _ctr, _currentCheckNum, _maxCtrChecks, _promises, _proms; _ctr = 0; _proms = []; _currentCheckNum = 1; _maxCtrChecks = 50; _promises = function() { return $q.all(_proms); }; _checkIfReady = function(deferred, expectedInstances) { return $timeout(function() { if (_currentCheckNum >= _maxCtrChecks) { deferred.reject('Your maps are not found we have checked the maximum amount of times. :)'); } _currentCheckNum += 1; if (_ctr !== expectedInstances) { return _checkIfReady(deferred, expectedInstances); } else { return deferred.resolve(_promises()); } }, 100); }; return { spawn: function() { var d; d = $q.defer(); _proms.push(d.promise); _ctr += 1; return { instance: _ctr, deferred: d }; }, promises: _promises, instances: function() { return _ctr; }, promise: function(expectedInstances) { var d; if (expectedInstances == null) { expectedInstances = 1; } d = $q.defer(); _checkIfReady(d, expectedInstances); return d.promise; }, reset: function() { _ctr = 0; _proms.length = 0; }, decrement: function() { if (_ctr > 0) { _ctr -= 1; } if (_proms.length) { _proms.length -= 1; } } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [ "uiGmapBaseObject", function(BaseObject) { var Linked; Linked = (function(superClass) { extend(Linked, superClass); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(BaseObject); return Linked; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [ '$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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) { var ModelKey; return ModelKey = (function(superClass) { extend(ModelKey, superClass); function ModelKey(scope1) { this.scope = scope1; 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.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; }; 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 GmapUtil.getPath(model, key); } return model; }; ModelKey.prototype.getProp = function(propName, model) { return this.modelOrKey(model, propName); }; /* 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(arrayOrObjModels) { var len, toCheck; if (arrayOrObjModels == null) { arrayOrObjModels = void 0; } len = 0; toCheck = arrayOrObjModels ? arrayOrObjModels : this.scope.models; if (toCheck == null) { return len; } if (angular.isArray(toCheck) || (toCheck.length != null)) { len = toCheck.length; } else { len = Object.keys(toCheck).length; } return len; }; return 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)) { 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() { angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() { var _ignores, _iterators, _slapForEach, _slapMap; _ignores = ['length', 'forEach', 'map']; _iterators = []; _slapForEach = function(object) { object.forEach = function(cb) { return _.each(_.omit(object, _ignores), function(val) { if (!_.isFunction(val)) { return cb(val); } }); }; return object; }; _iterators.push(_slapForEach); _slapMap = function(object) { object.map = function(cb) { return _.map(_.omit(object, _ignores), function(val) { if (!_.isFunction(val)) { return cb(val); } }); }; return object; }; _iterators.push(_slapMap); return { slapMap: _slapMap, slapForEach: _slapForEach, slapAll: function(object) { _iterators.forEach(function(it) { return it(object); }); return object; } }; }); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) { var CommonOptionsBuilder; return CommonOptionsBuilder = (function(superClass) { extend(CommonOptionsBuilder, superClass); function CommonOptionsBuilder() { this.watchProps = bind(this.watchProps, this); this.buildOpts = bind(this.buildOpts, this); return CommonOptionsBuilder.__super__.constructor.apply(this, arguments); } CommonOptionsBuilder.prototype.props = [ 'clickable', 'draggable', 'editable', 'visible', { prop: 'stroke', isColl: true } ]; CommonOptionsBuilder.prototype.getCorrectModel = function(scope) { if (angular.isDefined(scope != null ? scope.model : void 0)) { return scope.model; } else { return scope; } }; CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var model, opts, stroke; if (customOpts == null) { customOpts = {}; } if (forEachOpts == null) { forEachOpts = {}; } if (!this.scope) { $log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts'); return; } if (!this.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 extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var PolylineOptionsBuilder; return PolylineOptionsBuilder = (function(superClass) { extend(PolylineOptionsBuilder, superClass); function PolylineOptionsBuilder() { return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments); } PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolylineOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolylineOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapShapeOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var ShapeOptionsBuilder; return ShapeOptionsBuilder = (function(superClass) { extend(ShapeOptionsBuilder, superClass); function ShapeOptionsBuilder() { return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments); } ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var fill, model; model = this.getCorrectModel(this.scope); fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model); customOpts = angular.extend(customOpts, { fillColor: fill != null ? fill.color : void 0, fillOpacity: fill != null ? fill.opacity : void 0 }); return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts); }; return ShapeOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapPolygonOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var PolygonOptionsBuilder; return PolygonOptionsBuilder = (function(superClass) { extend(PolygonOptionsBuilder, superClass); function PolygonOptionsBuilder() { return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments); } PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolygonOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolygonOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapRectangleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var RectangleOptionsBuilder; return RectangleOptionsBuilder = (function(superClass) { extend(RectangleOptionsBuilder, superClass); function RectangleOptionsBuilder() { return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments); } RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) { return RectangleOptionsBuilder.__super__.buildOpts.call(this, { bounds: bounds }, cachedEval); }; return RectangleOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapCircleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var CircleOptionsBuilder; return CircleOptionsBuilder = (function(superClass) { extend(CircleOptionsBuilder, superClass); function CircleOptionsBuilder() { return CircleOptionsBuilder.__super__.constructor.apply(this, arguments); } CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) { return CircleOptionsBuilder.__super__.buildOpts.call(this, { center: center, radius: radius }, cachedEval); }; return CircleOptionsBuilder; })(ShapeOptionsBuilder); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [ 'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) { return _.extend(GmapUtil, { createOptions: function(coords, icon, defaults, map) { var opts; if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords), visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, isLabel: function(options) { if (options == null) { return false; } return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null); } }); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [ 'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) { return function(Builder, gFactory) { var BasePolyChildModel; return BasePolyChildModel = (function(superClass) { extend(BasePolyChildModel, superClass); BasePolyChildModel.include(GmapUtil); function BasePolyChildModel(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 (_this.scope.model != null) { maybeCachedEval = _this.scope; } if (pathPoints.length > 0) { _this.gObject = gFactory(_this.buildOpts(pathPoints, maybeCachedEval)); } if (_this.gObject) { if (_this.scope.fit) { _this.extendMapBounds(_this.map, pathPoints); } arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) { if (_this.scope.fit) { return _this.extendMapBounds(_this.map, pathPoints); } }); if (angular.isDefined(_this.scope.events) && angular.isObject(_this.scope.events)) { _this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope); } return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.model) : EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.scope); } }; })(this); create(); this.scope.$watch('path', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.gObject) { return create(); } }; })(this), true); if (!this.scope["static"] && angular.isDefined(this.scope.editable)) { this.scope.$watch('editable', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref = _this.gObject) != null ? ref.setEditable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.draggable)) { this.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(this.scope.visible)) { this.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(this.scope.geodesic)) { this.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(this.scope.stroke) && angular.isDefined(this.scope.stroke.weight)) { this.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(this.scope.stroke) && angular.isDefined(this.scope.stroke.color)) { this.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(this.scope.stroke) && angular.isDefined(this.scope.stroke.opacity)) { this.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(this.scope.icons)) { this.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); } this.scope.$on('$destroy', (function(_this) { return function() { _this.clean(); return _this.scope = null; }; })(this)); if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.color)) { this.scope.$watch('fill.color', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.opacity)) { this.scope.$watch('fill.opacity', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(this.scope.zIndex)) { this.scope.$watch('zIndex', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } } BasePolyChildModel.prototype.clean = function() { var ref; EventsHelper.removeEvents(this.listeners); EventsHelper.removeEvents(this.internalListeners); if ((ref = this.gObject) != null) { ref.setMap(null); } return this.gObject = null; }; return BasePolyChildModel; })(Builder); }; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , & http://jsfiddle.net/YsQdh/88/ */ (function() { angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [ 'uiGmapLogger', '$q', function($log, $q) { var drawFreeHand, freeHandMgr; drawFreeHand = function(map, polys, enable) { 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 enable(); }); return void 0; }; freeHandMgr = function(map1, defaultOptions) { var disableMap, enable; this.map = map1; if (!defaultOptions) { defaultOptions = { draggable: true, zoomControl: true, scrollwheel: true, disableDoubleClickZoom: true }; } enable = (function(_this) { return function() { var ref; if ((ref = _this.deferred) != null) { ref.resolve(); } return _.defer(function() { return _this.map.setOptions(_.extend(_this.oldOptions, defaultOptions)); }); }; })(this); disableMap = (function(_this) { return function() { $log.info('disabling map move'); _this.oldOptions = map.getOptions(); _this.oldOptions.center = map.getCenter(); return _this.map.setOptions({ draggable: false, zoomControl: false, scrollwheel: false, disableDoubleClickZoom: false }); }; })(this); this.engage = (function(_this) { return function(polys1) { _this.polys = polys1; _this.deferred = $q.defer(); disableMap(); $log.info('DrawFreeHandChildModel is engaged (drawing).'); google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) { return drawFreeHand(_this.map, _this.polys, enable); }); return _this.deferred.promise; }; })(this); return this; }; return freeHandMgr; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [ 'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) { var MarkerChildModel; MarkerChildModel = (function(superClass) { var destroy; extend(MarkerChildModel, superClass); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); MarkerChildModel.include(MarkerOptions); destroy = function(child) { if ((child != null ? child.gObject : void 0) != null) { child.removeEvents(child.externalListeners); child.removeEvents(child.internalListeners); if (child != null ? child.gObject : void 0) { if (child.removeFromManager) { child.gManager.remove(child.gObject); } child.gObject.setMap(null); return child.gObject = null; } } }; function MarkerChildModel(scope, model1, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) { var action; this.model = model1; 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) { return _this[k + 'Key'] = _.isFunction(_this.keys[k]) ? _this.keys[k]() : _this.keys[k]; }; })(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(this.coordsKey, 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(_this.coordsKey, _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(_this.iconKey, _this.model); if (oldValue === newValue) { return; } _this.gObject.setIcon(newValue); coords = _this.getProp(_this.coordsKey, _this.model); _this.gObject.setPosition(_this.getCoords(coords)); return _this.gObject.setVisible(_this.validateCoords(coords)); }; })(this)); }; MarkerChildModel.prototype.setOptions = function(scope, doDraw) { var ref; if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope, false)) { return; } this.renderGMarker(doDraw, (function(_this) { return function() { var _options, coords, icon; coords = _this.getProp(_this.coordsKey, _this.model); icon = _this.getProp(_this.iconKey, _this.model); _options = _this.getProp(_this.optionsKey, _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 = _.isFunction(_this.clickKey) ? _this.clickKey : _this.getProp(_this.clickKey, _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 extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) { var PolygonChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polygon(opts); }; base = new BaseGen(Builder, gFactory); return PolygonChildModel = (function(superClass) { extend(PolygonChildModel, superClass); function PolygonChildModel() { return PolygonChildModel.__super__.constructor.apply(this, arguments); } return PolygonChildModel; })(base); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) { var PolylineChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polyline(opts); }; base = BaseGen(Builder, gFactory); return PolylineChildModel = (function(superClass) { extend(PolylineChildModel, superClass); function PolylineChildModel() { return PolylineChildModel.__super__.constructor.apply(this, arguments); } return PolylineChildModel; })(base); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) { var WindowChildModel; WindowChildModel = (function(superClass) { extend(WindowChildModel, superClass); WindowChildModel.include(GmapUtil); WindowChildModel.include(EventsHelper); function WindowChildModel(model1, scope1, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) { var maybeMarker; this.model = model1; this.scope = scope1; 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 ref, wasOpen; if (!(_this.element || _this.html)) { return; } if (_this.html !== _this.element.html() && _this.gObject) { if ((ref = _this.opts) != null) { ref.content = void 0; } wasOpen = _this.gObject.isOpen(); _this.remove(); return _this.createGWin(wasOpen); } }; })(this)); }; WindowChildModel.prototype.createGWin = function(isOpen) { var _opts, defaults, maybeMarker, ref, ref1; if (isOpen == null) { isOpen = false; } maybeMarker = this.getGmarker(); defaults = {}; if (this.opts != null) { if (this.scope.coords) { this.opts.position = this.getCoords(this.scope.coords); } defaults = this.opts; } if (this.element) { this.html = _.isObject(this.element) ? this.element.html() : this.element; } _opts = this.scope.options ? this.scope.options : defaults; this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts); if (this.opts != null) { if (!this.gObject) { if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) { this.gObject = new window.InfoBox(this.opts); } else { this.gObject = new google.maps.InfoWindow(this.opts); } this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() { return ChromeFixes.maybeRepaint(this.content); })); this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) { return function() { if (maybeMarker) { maybeMarker.setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { maybeMarker.setVisible(false); return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _this.gObject.close(); _this.model.show = false; if (_this.scope.closeClick != null) { return _this.scope.$evalAsync(_this.scope.closeClick()); } else { return _this.scope.$evalAsync(); } }; })(this))); } this.gObject.setContent(this.opts.content); this.handleClick(((ref = this.scope) != null ? (ref1 = ref.options) != null ? ref1.forceClick : void 0 : void 0) || isOpen); return this.doShow(this.gObject.isOpen()); } }; WindowChildModel.prototype.watchCoords = function() { var scope; scope = this.markerScope != null ? this.markerScope : this.scope; return scope.$watch('coords', (function(_this) { return function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { _this.hideWindow(); } else if (!_this.validateCoords(newValue)) { $log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.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 bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapBasePolysParentModel', [ '$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmap_async', 'uiGmapPromise', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, _async, uiGmapPromise) { return function(IPoly, PolyChildModel, gObjectName) { var BasePolysParentModel; return BasePolysParentModel = (function(superClass) { extend(BasePolysParentModel, superClass); BasePolysParentModel.include(ModelsWatcher); function BasePolysParentModel(scope, element, attrs, gMap1, defaults) { this.element = element; this.attrs = attrs; this.gMap = gMap1; this.defaults = defaults; this.createChild = bind(this.createChild, this); this.pieceMeal = bind(this.pieceMeal, this); this.createAllNew = bind(this.createAllNew, this); this.watchIdKey = bind(this.watchIdKey, this); this.createChildScopes = bind(this.createChildScopes, this); this.watchDestroy = bind(this.watchDestroy, this); this.onDestroy = bind(this.onDestroy, this); this.rebuildAll = bind(this.rebuildAll, this); this.doINeedToWipe = bind(this.doINeedToWipe, this); this.watchModels = bind(this.watchModels, this); BasePolysParentModel.__super__.constructor.call(this, scope); this["interface"] = IPoly; this.$log = $log; this.plurals = new PropMap(); _.each(IPoly.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.createChildScopes(); } BasePolysParentModel.prototype.watchModels = function(scope) { 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)); }; BasePolysParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; BasePolysParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; BasePolysParentModel.prototype.onDestroy = function(scope) { BasePolysParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(true); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var ref; return (ref = _this.plurals) != null ? ref.removeAll() : void 0; }); }; })(this)); }; BasePolysParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; BasePolysParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error("No models to create " + gObjectName + "s from! I Need direct models!"); return; } if ((this.gMap == null) || (this.scope.models == null)) { return; } this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; BasePolysParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; BasePolysParentModel.prototype.createAllNew = function(scope, isArray) { var maybeCanceled; if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.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)); }; BasePolysParentModel.prototype.pieceMeal = function(scope, isArray) { var maybeCanceled, payload; if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; this.models = scope.models; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise(function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); }).then(function(state) { payload = state; if (payload.updates.length) { $log.info("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); } }; BasePolysParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(IPoly.scopeKeys, childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); childScope["static"] = this.scope["static"]; child = new PolyChildModel(childScope, this.attrs, gMap, this.defaults, model); if (model[this.idKey] == null) { this.$log.error(gObjectName + " model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; return BasePolysParentModel; })(ModelKey); }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) { var CircleParentModel; return CircleParentModel = (function(superClass) { extend(CircleParentModel, superClass); CircleParentModel.include(GmapUtil); CircleParentModel.include(EventsHelper); function CircleParentModel(scope, element, attrs, map, DEFAULTS) { var clean, gObject, lastRadius; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; this.scope = scope; lastRadius = null; clean = (function(_this) { return function() { lastRadius = null; if (_this.listeners != null) { _this.removeEvents(_this.listeners); return _this.listeners = void 0; } }; })(this); gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.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', 'zIndex' ]); this.watchProps(); 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 extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) { var DrawingManagerParentModel; return DrawingManagerParentModel = (function(superClass) { extend(DrawingManagerParentModel, superClass); DrawingManagerParentModel.include(EventsHelper); function DrawingManagerParentModel(scope, element, attrs, map) { var gObject, listeners; this.scope = scope; this.attrs = attrs; this.map = map; gObject = new google.maps.drawing.DrawingManager(this.scope.options); gObject.setMap(this.map); listeners = void 0; if (this.scope.control != null) { this.scope.control.getDrawingManager = function() { return gObject; }; } if (!this.scope["static"] && this.scope.options) { this.scope.$watch('options', function(newValue) { return gObject != null ? gObject.setOptions(newValue) : void 0; }, true); } if (this.scope.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); this.scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } this.scope.$on('$destroy', (function(_this) { return function() { if (listeners != null) { _this.removeEvents(listeners); } gObject.setMap(null); return gObject = null; }; })(this)); } return DrawingManagerParentModel; })(BaseObject); } ]); }).call(this); ; /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [ "uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(superClass) { extend(IMarkerParentModel, superClass); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope1, element, attrs, map) { this.scope = scope1; this.element = element; this.attrs = attrs; this.map = map; this.onWatch = bind(this.onWatch, this); this.watch = bind(this.watch, this); this.validateScope = bind(this.validateScope, this); IMarkerParentModel.__super__.constructor.call(this, this.scope); this.$log = Logger; if (!this.validateScope(this.scope)) { throw new String("Unable to construct IMarkerParentModel due to invalid scope"); } this.doClick = angular.isDefined(this.attrs.click); if (this.scope.options != null) { this.DEFAULTS = this.scope.options; } this.watch('coords', this.scope); this.watch('icon', this.scope); this.watch('options', this.scope); this.scope.$on("$destroy", (function(_this) { return function() { return _this.onDestroy(_this.scope); }; })(this)); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) { if (equalityCheck == null) { equalityCheck = true; } return scope.$watch(propNameToWatch, (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }; })(this), equalityCheck); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {}; return IMarkerParentModel; })(ModelKey); return IMarkerParentModel; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [ "uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; return IWindowParentModel = (function(superClass) { extend(IWindowParentModel, superClass); IWindowParentModel.include(GmapUtil); function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { IWindowParentModel.__super__.constructor.call(this, scope); this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.DEFAULTS = {}; if (scope.options != null) { this.DEFAULTS = scope.options; } } IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return IWindowParentModel; })(ModelKey); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(superClass) { extend(LayerParentModel, superClass); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!'); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.gObject.setMap(this.gMap); } this.scope.$watch('show', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.gObject.setMap(_this.gMap); } else { return _this.gObject.setMap(null); } } }; })(this), true); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) { var MapTypeParentModel; MapTypeParentModel = (function(superClass) { extend(MapTypeParentModel, superClass); function MapTypeParentModel(scope, element, attrs, gMap, $log) { 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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [ "uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", 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(superClass) { extend(MarkersParentModel, superClass); 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(this.scope); this.scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); if (!this.modelsLength()) { this.modelsRendered = false; } this.scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) { if (newValue.length === 0 && oldValue.length === 0) { return; } _this.modelsRendered = true; return _this.onWatch('models', _this.scope, newValue, oldValue); } }; })(this), !this.isTrue(attrs.modelsbyref)); this.watch('doCluster', this.scope); this.watch('clusterOptions', this.scope); this.watch('clusterEvents', this.scope); this.watch('fit', this.scope); this.watch('idKey', this.scope); this.gManager = void 0; this.createAllNew(this.scope); } MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === "idKey" && newValue !== oldValue) { this.idKey = newValue; } if (this.doRebuildAll || propNameToWatch === 'doCluster') { 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, ref, ref1, ref2, self; 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.plurals); childScope = scope.$new(true); 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() { ['Polygon', 'Polyline'].forEach(function(name) { return angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory("uiGmap" + name + "sParentModel", [ 'uiGmapBasePolysParentModel', "uiGmap" + name + "ChildModel", "uiGmapI" + name, function(BasePolysParentModel, ChildModel, IPoly) { return BasePolysParentModel(IPoly, ChildModel, name); } ]); }); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) { var RectangleParentModel; return RectangleParentModel = (function(superClass) { extend(RectangleParentModel, superClass); RectangleParentModel.include(GmapUtil); RectangleParentModel.include(EventsHelper); function RectangleParentModel(scope, element, attrs, 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(_this.attrs.fit)) { return _this.fitMapBounds(_this.map, bounds); } }; })(this); createBounds = (function(_this) { return function() { var ref, ref1, ref2; if ((_this.scope.bounds != null) && (((ref = _this.scope.bounds) != null ? ref.sw : void 0) != null) && (((ref1 = _this.scope.bounds) != null ? ref1.ne : void 0) != null) && _this.validateBoundPoints(_this.scope.bounds)) { bounds = _this.convertBoundPoints(_this.scope.bounds); return $log.info("new new bounds created: " + (JSON.stringify(bounds))); } else if ((_this.scope.bounds.getNorthEast != null) && (_this.scope.bounds.getSouthWest != null)) { return bounds = _this.scope.bounds; } else { if (_this.scope.bounds != null) { return $log.error("Invalid bounds for newValue: " + (JSON.stringify((ref2 = _this.scope) != null ? ref2.bounds : void 0))); } } }; })(this); createBounds(); gObject = new google.maps.Rectangle(this.buildOpts(bounds)); $log.info("gObject (rectangle) created: " + gObject); settingBoundsFromScope = false; updateBounds = (function(_this) { return function() { var b, ne, sw; b = gObject.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return _this.scope.$evalAsync(function(s) { if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) { return s.bounds = b; } }); }; })(this); init = (function(_this) { return function() { fit(); _this.removeEvents(myListeners); myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() { return dragging = true; })); myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() { dragging = false; return updateBounds(); })); return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() { if (dragging) { return; } return updateBounds(); })); }; })(this); clear = (function(_this) { return function() { _this.removeEvents(myListeners); if (listeners != null) { _this.removeEvents(listeners); } return gObject.setMap(null); }; })(this); if (bounds != null) { init(); } this.scope.$watch('bounds', (function(newValue, oldValue) { var isNew; if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) { return; } settingBoundsFromScope = true; if (newValue == null) { clear(); return; } if (bounds == null) { isNew = true; } else { fit(); } createBounds(); gObject.setBounds(bounds); settingBoundsFromScope = false; if (isNew && (bounds != null)) { return init(); } }), true); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { if ((bounds != null) && (newVals != null)) { return gObject.setOptions(_this.buildOpts(bounds)); } } }; })(this); this.props.push('bounds'); this.watchProps(this.props); if (this.attrs.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); this.scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } this.scope.$on('$destroy', (function(_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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) { var SearchBoxParentModel; SearchBoxParentModel = (function(superClass) { extend(SearchBoxParentModel, superClass); SearchBoxParentModel.include(EventsHelper); function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) { var controlDiv; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.ctrlPosition = ctrlPosition; this.template = template; this.$log = $log != null ? $log : Logger; this.setVisibility = bind(this.setVisibility, this); this.getBounds = bind(this.getBounds, this); this.setBounds = bind(this.setBounds, this); this.createSearchBox = bind(this.createSearchBox, this); this.addToParentDiv = bind(this.addToParentDiv, this); this.addAsMapControl = bind(this.addAsMapControl, this); this.init = bind(this.init, this); if (this.attrs.template == null) { this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!'); return; } if (angular.isUndefined(this.scope.options)) { this.scope.options = {}; this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.visible)) { this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.autocomplete)) { this.scope.options.autocomplete = false; } this.visible = this.scope.options.visible; this.autocomplete = this.scope.options.autocomplete; controlDiv = angular.element('<div></div>'); controlDiv.append(this.template); this.input = controlDiv.find('input')[0]; this.init(); } SearchBoxParentModel.prototype.init = function() { this.createSearchBox(); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (angular.isObject(newValue)) { if (newValue.bounds != null) { _this.setBounds(newValue.bounds); } if (newValue.visible != null) { if (_this.visible !== newValue.visible) { return _this.setVisibility(newValue.visible); } } } }; })(this), true); if (this.attrs.parentdiv != null) { this.addToParentDiv(); } else { this.addAsMapControl(); } if (this.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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [ 'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) { var WindowsParentModel; WindowsParentModel = (function(superClass) { extend(WindowsParentModel, superClass); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, gMap1, markersScope) { this.gMap = gMap1; this.markersScope = markersScope; this.modelKeyComparison = bind(this.modelKeyComparison, this); this.interpolateContent = bind(this.interpolateContent, this); this.setChildScope = bind(this.setChildScope, this); this.createWindow = bind(this.createWindow, this); this.setContentKeys = bind(this.setContentKeys, this); this.pieceMeal = bind(this.pieceMeal, this); this.createAllNew = bind(this.createAllNew, this); this.watchIdKey = bind(this.watchIdKey, this); this.createChildScopes = bind(this.createChildScopes, this); this.watchOurScope = bind(this.watchOurScope, this); this.watchDestroy = bind(this.watchDestroy, this); this.onDestroy = bind(this.onDestroy, this); this.rebuildAll = bind(this.rebuildAll, this); this.doINeedToWipe = bind(this.doINeedToWipe, this); this.watchModels = bind(this.watchModels, this); this.go = bind(this.go, this); WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache); this["interface"] = IWindow; this.plurals = new PropMap(); _.each(IWindow.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.linked = new Linked(scope, element, attrs, ctrls); this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.firstWatchModels = true; this.$log.info(self); this.parentScope = void 0; this.go(scope); } WindowsParentModel.prototype.go = function(scope) { this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); return this.createChildScopes(); }; WindowsParentModel.prototype.watchModels = function(scope) { var itemToWatch; itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models'; return scope.$watch(itemToWatch, (function(_this) { return function(newValue, oldValue) { var doScratch; if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) { _this.firstWatchModels = false; if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) { return _this.rebuildAll(scope, true, true); } else { doScratch = _this.plurals.length === 0; if (_this.existingPieces != null) { return _.last(_this.existingPieces._content).then(function() { return _this.createChildScopes(doScratch); }); } else { return _this.createChildScopes(doScratch); } } } }; })(this), true); }; WindowsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; WindowsParentModel.prototype.onDestroy = function(scope) { WindowsParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var ref; return (ref = _this.plurals) != null ? ref.removeAll() : void 0; }); }; })(this)); }; WindowsParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { _this.firstWatchModels = true; _this.firstTime = true; return _this.rebuildAll(scope, false, true); }; })(this)); }; WindowsParentModel.prototype.watchOurScope = function(scope) { return _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; }; })(this)); }; WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { var modelsNotDefined, ref, ref1; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (this.markersScope === void 0 || (((ref = this.markersScope) != null ? ref.plurals : void 0) === void 0 || ((ref1 = this.markersScope) != null ? ref1.models : void 0) === void 0))) { this.$log.error('No models to create windows from! Need direct models or models derived from markers!'); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.watchIdKey(this.linked.scope); if (isCreatingFromScratch) { return this.createAllNew(this.linked.scope, false); } else { return this.pieceMeal(this.linked.scope, false); } } else { this.parentScope = this.markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNew(this.markersScope, true, 'plurals', false); } else { return this.pieceMeal(this.markersScope, true, 'plurals', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = false; } if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } this.setContentKeys(scope.models); if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { var gMarker, ref; gMarker = hasGMarker ? (ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? ref.gObject : void 0 : void 0; if (!maybeCanceled) { if (!gMarker && _this.markersScope) { $log.error('Unable to get gMarker from markersScope!'); } _this.createWindow(model, gMarker, _this.gMap); } return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.firstTime = false; }); }; })(this)); }; WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled, payload; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { _this.plurals.remove(child.id); if (child.destroy != null) { child.destroy(true); } return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker, ref; gMarker = (ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? ref.gObject : void 0; if (!gMarker) { throw 'Gmarker undefined'; } _this.createWindow(modelToAdd, gMarker, _this.gMap); return maybeCanceled; }); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }); }; })(this)); } else { $log.debug('pieceMeal: rebuildAll'); return this.rebuildAll(this.scope, true, true); } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (this.modelsLength(models)) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { var child, childScope, fakeElement, opts, ref, ref1; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); fakeElement = { html: (function(_this) { return function() { return _this.interpolateContent(_this.linked.element.html(), model); }; })(this) }; this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {}; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel(model, 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, i, interpModel, key, len, ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = $interpolate(content); interpModel = {}; ref = this.contentKeys; for (i = 0, len = ref.length; i < len; i++) { key = ref[i]; interpModel[key] = model[key]; } return exp(interpModel); }; WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) { var isEqual, scope; scope = this.scope.coords != null ? this.scope : this.parentScope; if (scope == null) { throw 'No scope or parentScope set!'; } isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords)); if (!isEqual) { return isEqual; } isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) { return function(k) { return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]); }; })(this)); return isEqual; }; return WindowsParentModel; })(IWindowParentModel); return WindowsParentModel; } ]); }).call(this); ;(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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [ "uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) { var Control; return Control = (function(superClass) { extend(Control, superClass); function Control() { this.link = bind(this.link, this); Control.__super__.constructor.call(this); } Control.prototype.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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [ 'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) { var FreeDrawPolygons; return FreeDrawPolygons = (function(superClass) { extend(FreeDrawPolygons, superClass); function FreeDrawPolygons() { this.link = bind(this.link, this); return FreeDrawPolygons.__super__.constructor.apply(this, arguments); } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EMA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap'; FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=', revertmapoptions: '=' }; 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, scope.revertmapoptions); 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: "=", zIndex: "=zindex" } }; } ]); }).call(this); ; /* - interface for all controls to derive from - to enforce a minimum set of requirements - attributes - template - position - controller - index */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [ "uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) { var IControl; return IControl = (function(superClass) { extend(IControl, superClass); IControl.extend(CtrlHandle); function IControl() { this.restrict = 'EA'; this.replace = true; this.require = '^' + 'uiGmapGoogleMap'; this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new 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 extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [ 'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(superClass) { extend(IMarker, superClass); IMarker.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; IMarker.scopeKeys = _.keys(IMarker.scope); IMarker.keys = IMarker.scopeKeys; IMarker.extend(CtrlHandle); function IMarker() { this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = _.extend(this.scope || {}, IMarker.scope); } return IMarker; })(BaseObject); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolygon; return IPolygon = (function(superClass) { extend(IPolygon, superClass); IPolygon.scope = { path: '=path', stroke: '=stroke', clickable: '=', draggable: '=', editable: '=', geodesic: '=', fill: '=', icons: '=icons', visible: '=', "static": '=', events: '=', zIndex: '=zindex', fit: '=', control: '=control' }; IPolygon.scopeKeys = _.keys(IPolygon.scope); IPolygon.include(GmapUtil); IPolygon.extend(CtrlHandle); function IPolygon() {} IPolygon.prototype.restrict = 'EMA'; IPolygon.prototype.replace = true; IPolygon.prototype.require = '^' + 'uiGmapGoogleMap'; IPolygon.prototype.scope = IPolygon.scope; IPolygon.prototype.DEFAULTS = {}; IPolygon.prototype.$log = Logger; return IPolygon; })(BaseObject); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolyline; return IPolyline = (function(superClass) { extend(IPolyline, superClass); IPolyline.scope = { path: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', geodesic: '=', icons: '=', visible: '=', "static": '=', fit: '=', events: '=', zIndex: '=zindex' }; IPolyline.scopeKeys = _.keys(IPolyline.scope); IPolyline.include(GmapUtil); IPolyline.extend(CtrlHandle); function IPolyline() {} IPolyline.prototype.restrict = 'EMA'; IPolyline.prototype.replace = true; IPolyline.prototype.require = '^' + 'uiGmapGoogleMap'; IPolyline.prototype.scope = IPolyline.scope; IPolyline.prototype.DEFAULTS = {}; IPolyline.prototype.$log = Logger; return IPolyline; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [ function() { 'use strict'; var DEFAULTS; DEFAULTS = {}; return { restrict: 'EMA', require: '^' + 'uiGmapGoogleMap', replace: true, scope: { bounds: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', fill: '=', visible: '=', events: '=' } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [ 'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) { var IWindow; return IWindow = (function(superClass) { extend(IWindow, superClass); IWindow.scope = { coords: '=coords', template: '=template', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options', control: '=control', show: '=show' }; IWindow.scopeKeys = _.keys(IWindow.scope); IWindow.include(ChildEvents); IWindow.extend(CtrlHandle); function IWindow() { this.restrict = 'EMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = '^' + 'uiGmapGoogleMap'; this.replace = true; this.scope = _.extend(this.scope || {}, IWindow.scope); } return IWindow; })(BaseObject); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [ '$timeout', '$q', '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(superClass) { extend(Map, superClass); 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.decrement(); }); 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 _gMap, customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, ref, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise; 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 ref1, ref2, settingZoomFromScope; 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, ref1, ref2, ref3, ref4, sw; if (newValue === oldValue) { return; } if (((newValue != null ? (ref1 = newValue.northeast) != null ? ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref2 = newValue.northeast) != null ? ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (ref3 = newValue.southwest) != null ? ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref4 = newValue.southwest) != null ? ref4.longitude : void 0 : void 0) == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _gMap.fitBounds(bounds); }); return ['options', 'styles'].forEach(function(toWatch) { return scope.$watch(toWatch, function(newValue, oldValue) { 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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [ "uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) { var Marker; return Marker = (function(superClass) { extend(Marker, superClass); function Marker() { 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 extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [ "uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) { var Markers; return Markers = (function(superClass) { extend(Markers, superClass); function Markers() { Markers.__super__.constructor.call(this); this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; Plural.extend(this, { doCluster: '=docluster', clusterOptions: '=clusteroptions', clusterEvents: '=clusterevents', modelsByRef: '=modelsbyref' }); $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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [ 'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) { var Polygon; return Polygon = (function(superClass) { extend(Polygon, superClass); function Polygon() { this.link = bind(this.link, this); return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.link = function(scope, element, attrs, mapCtrl) { var children, promise; children = []; promise = IPolygon.mapPromise(scope, mapCtrl); if (scope.control != null) { scope.control.getInstance = this; scope.control.polygons = children; scope.control.promise = promise; } return promise.then((function(_this) { return function(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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [ 'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) { var Polygons; return Polygons = (function(superClass) { extend(Polygons, superClass); function Polygons() { this.link = bind(this.link, this); Polygons.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polygons.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polygons: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polygons: no models found to create from'); } return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygons; })(Interface); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [ 'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) { var Polyline; return Polyline = (function(superClass) { extend(Polyline, superClass); function Polyline() { this.link = bind(this.link, this); return Polyline.__super__.constructor.apply(this, arguments); } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) { return function(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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [ 'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) { var Polylines; return Polylines = (function(superClass) { extend(Polylines, superClass); function Polylines() { this.link = bind(this.link, this); Polylines.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polylines.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [ 'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) { var Window; return Window = (function(superClass) { extend(Window, superClass); Window.include(GmapUtil); function Window() { this.link = bind(this.link, this); Window.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; $log.debug(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var markerCtrl, markerScope; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; this.mapPromise = IWindow.mapPromise(scope, ctrls[0]); return this.mapPromise.then((function(_this) { return function(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); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [ 'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) { /* Windows directive where many windows map to the models property */ var Windows; return Windows = (function(superClass) { extend(Windows, superClass); function Windows() { this.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); ;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));
src/parser/hunter/marksmanship/modules/spells/azeritetraits/InTheRhythm.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText'; import UptimeIcon from 'interface/icons/Uptime'; import HasteIcon from 'interface/icons/Haste'; import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic'; import { calculateAzeriteEffects } from 'common/stats'; import StatTracker from 'parser/shared/modules/StatTracker'; import { formatPercentage, formatNumber } from 'common/format'; const inTheRhythmStats = traits => Object.values(traits).reduce((obj, rank) => { const [haste] = calculateAzeriteEffects(SPELLS.IN_THE_RHYTHM.id, rank); obj.haste += haste; return obj; }, { haste: 0, }); const DURATION = 8000; /** Rapid Fire * When Rapid Fire finishes fully channeling, your Haste is increased by 623 for 8 sec. * * Example log: https://www.warcraftlogs.com/reports/47LJvZ9BgdhR8TXf#fight=43&type=summary&source=16 */ class InTheRhythm extends Analyzer { static dependencies = { statTracker: StatTracker, }; applications = 0; lastApplicationTimestamp = 0; possibleApplications = 0; haste = 0; wastedUptime = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.IN_THE_RHYTHM.id); if (!this.active) { return; } const { haste } = inTheRhythmStats(this.selectedCombatant.traitsBySpellId[SPELLS.IN_THE_RHYTHM.id]); this.haste = haste; this.statTracker.add(SPELLS.IN_THE_RHYTHM_BUFF.id, { haste, }); } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.RAPID_FIRE.id) { return; } this.possibleApplications += 1; } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.IN_THE_RHYTHM_BUFF.id) { return; } this.applications += 1; this.lastApplicationTimestamp = event.timestamp; } on_byPlayer_refreshbuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.IN_THE_RHYTHM_BUFF.id) { return; } this.applications += 1; this.wastedUptime += DURATION - (event.timestamp - this.lastApplicationTimestamp); this.lastApplicationTimestamp = event.timestamp; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.IN_THE_RHYTHM_BUFF.id) / this.owner.fightDuration; } get avgHaste() { return this.uptime * this.haste; } statistic() { return ( <AzeritePowerStatistic size="flexible" tooltip={( <> In The Rhythm granted <strong>{this.haste}</strong> Haste for <strong>{formatPercentage(this.uptime)}%</strong> of the fight. <br /> You lost out on {formatNumber(this.wastedUptime / 1000)} seconds of uptime from refreshing the buff before it expired. </> )} > <BoringSpellValueText spell={SPELLS.IN_THE_RHYTHM}> {this.applications}/{this.possibleApplications} <small> applications</small> <br /> <UptimeIcon /> {formatPercentage(this.uptime)}% <small>uptime</small> <br /> <HasteIcon /> {formatNumber(this.avgHaste)} <small> average Haste gained</small> </BoringSpellValueText> </AzeritePowerStatistic> ); } } export default InTheRhythm;
src/icons/BookmarkIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class BookmarkIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M34 6H14c-2.21 0-3.98 1.79-3.98 4L10 42l14-6 14 6V10c0-2.21-1.79-4-4-4z"/></svg>;} };
src/components/GalleryByReactApp.js
J1aDong/gallery-by-react
require('normalize.css/normalize.css'); require('styles/main.scss'); import React from 'react'; import ReactDOM from 'react-dom'; // 获取图片相关的数据 var imageDatas = require('../data/imageDatas.json'); // 利用自执行函数, 将图片名信息转成图片URL路径信息 imageDatas = (function genImageURL(imageDatasArr) { for (var i = 0, j = imageDatasArr.length; i < j; i++) { var singleImageData = imageDatasArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imageDatasArr[i] = singleImageData; } return imageDatasArr; })(imageDatas); /* * 获取区间内的一个随机值 */ function getRangeRandom(low, high) { return Math.ceil(Math.random() * (high - low) + low); } /* * 获取 0~30° 之间的一个任意正负值 */ function get30DegRandom() { return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30)); } var ImgFigure = React.createClass({ /* * imgFigure 的点击处理函数 */ handleClick: function (e) { if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); }, render: function () { var styleObj = {}; // 如果props属性中指定了这张图片的位置,则使用 if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } // 如果图片的旋转角度有值并且不为0, 添加旋转角度 if (this.props.arrange.rotate) { (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value) { styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this)); } // 如果是居中的图片, z-index设为11 if (this.props.arrange.isCenter) { styleObj.zIndex = 11; } var imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : ''; return ( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title} /> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ); } }); // 控制组件 var ControllerUnit = React.createClass({ handleClick: function (e) { // 如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); }, render: function () { var controlelrUnitClassName = "controller-unit"; // 如果对应的是居中的图片,显示控制按钮的居中态 if (this.props.arrange.isCenter) { controlelrUnitClassName += " is-center"; // 如果同时对应的是翻转图片, 显示控制按钮的翻转态 if (this.props.arrange.isInverse) { controlelrUnitClassName += " is-inverse"; } } return ( <span className={controlelrUnitClassName} onClick={this.handleClick}></span> ); } }); var GalleryByReactApp = React.createClass({ Constant: { centerPos: { left: 0, right: 0 }, hPosRange: { // 水平方向的取值范围 leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { // 垂直方向的取值范围 x: [0, 0], topY: [0, 0] } }, /* * 翻转图片 * @param index 传入当前被执行inverse操作的图片对应的图片信息数组的index值 * @returns {Function} 这是一个闭包函数, 其内return一个真正待被执行的函数 */ inverse: function (index) { return function () { var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this); }, /* * 重新布局所有图片 * @param centerIndex 指定居中排布哪个图片 */ rearrange: function (centerIndex) { var imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), // 取一个或者不取 topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1); // 首先居中 centerIndex 的图片, 居中的 centerIndex 的图片不需要旋转 imgsArrangeCenterArr[0] = { pos: centerPos, rotate: 0, isCenter: true }; // 取出要布局上侧的图片的状态信息 topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum); // 布局位于上侧的图片 imgsArrangeTopArr.forEach(function (value, index) { imgsArrangeTopArr[index] = { pos: { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter: false }; }); // 布局左右两侧的图片 for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { var hPosRangeLORX = null; // 前半部分布局左边, 右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter: false }; } if (imgsArrangeTopArr && imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); }, /* * 利用arrange函数, 居中对应index的图片 * @param index, 需要被居中的图片对应的图片信息数组的index值 * @returns {Function} */ center: function (index) { return function () { this.rearrange(index); }.bind(this); }, getInitialState: function () { return { imgsArrangeArr: [ /*{ pos: { left: '0', top: '0' }, rotate: 0, // 旋转角度 isInverse: false, // 图片正反面 isCenter: false, // 图片是否居中 }*/ ] }; }, // 组件加载以后, 为每张图片计算其位置的范围 componentDidMount: function () { // 首先拿到舞台的大小 var stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); // 拿到一个imageFigure的大小 var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); // 计算中心图片的位置点 this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; // 计算左侧,右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; // 计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0); }, render: function () { var controllerUnits = [], imgFigures = []; imageDatas.forEach(function (value, index) { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false, isCenter: false }; } imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>); controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } }); module.exports = GalleryByReactApp;
src/__tests__/Tooltip-test.js
react-mdl/react-mdl
/* eslint-env mocha */ import expect from 'expect'; import React from 'react'; import { render } from './render'; import Tooltip from '../Tooltip'; import Icon from '../Icon'; describe('Tooltip', () => { it('should render the child and label inside a div', () => { const element = ( <Tooltip label="my tooltip"> text </Tooltip> ); const output = render(element); expect(output.type).toBe('div'); expect(output.props.children.length).toBe(2); }); it('should render the tooltip with the tooltip css', () => { const element = ( <Tooltip label="my tooltip"> text </Tooltip> ); const output = render(element); const label = output.props.children[1].props.children; expect(label.props.className).toInclude('mdl-tooltip'); }); it('should link the child and the label', () => { const element = ( <Tooltip label="my tooltip"> text </Tooltip> ); const output = render(element); const child = output.props.children[0]; const label = output.props.children[1].props.children; expect(child.props.id).toBe(label.props.htmlFor); }); it('should work with a complex child', () => { const element = ( <Tooltip label={<div>my tooltip</div>}> <Icon name="add" /> </Tooltip> ); const output = render(element); const child = output.props.children[0]; const label = output.props.children[1].props.children; expect(child.props.id).toBe(label.props.htmlFor); }); it('should render a small tooltip by default', () => { const element = ( <Tooltip label="my tooltip"> <Icon name="add" /> </Tooltip> ); const output = render(element); const label = output.props.children[1].props.children; expect(label.props.className) .toExclude('mdl-tooltip--large'); }); it('should render a large tooltip if specified', () => { const element = ( <Tooltip label="my tooltip"> <Icon name="add" /> </Tooltip> ); const output = render(element); const label = output.props.children[1].props.children; expect(label.props.className) .toExclude('mdl-tooltip--large'); }); it('should not render any tooltip positioning css if unspecified', () => { const element = ( <Tooltip label="my tooltip"> <Icon name="add" /> </Tooltip> ); const output = render(element); const label = output.props.children[1].props.children; expect(label.props.className) .toExclude('mdl-tooltip--left') .toExclude('mdl-tooltip--right') .toExclude('mdl-tooltip--top') .toExclude('mdl-tooltip--bottom'); }); it('should render tooltip with correct positioning css if specified', () => { ['left', 'right', 'top', 'bottom'].forEach((position) => { const element = ( <Tooltip label="my tooltip" position={position}> <Icon name="add" /> </Tooltip> ); const output = render(element); const label = output.props.children[1].props.children; expect(label.props.className) .toInclude(`mdl-tooltip--${position}`); }); }); });
ajax/libs/foundation/4.0.4/js/vendor/jquery.min.js
dhenson02/cdnjs
(function(e,t){function n(e){var t=e.length,n=lt.type(e);return lt.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}function i(e){var t=wt[e]={};return lt.each(e.match(ut)||[],function(e,n){t[n]=!0}),t}function r(e,n,i,r){if(lt.acceptData(e)){var o,a,s=lt.expando,l="string"==typeof n,c=e.nodeType,u=c?lt.cache:e,d=c?e[s]:e[s]&&s;if(d&&u[d]&&(r||u[d].data)||!l||i!==t)return d||(c?e[s]=d=Q.pop()||lt.guid++:d=s),u[d]||(u[d]={},c||(u[d].toJSON=lt.noop)),("object"==typeof n||"function"==typeof n)&&(r?u[d]=lt.extend(u[d],n):u[d].data=lt.extend(u[d].data,n)),o=u[d],r||(o.data||(o.data={}),o=o.data),i!==t&&(o[lt.camelCase(n)]=i),l?(a=o[n],null==a&&(a=o[lt.camelCase(n)])):a=o,a}}function o(e,t,n){if(lt.acceptData(e)){var i,r,o,a=e.nodeType,l=a?lt.cache:e,c=a?e[lt.expando]:lt.expando;if(l[c]){if(t&&(o=n?l[c]:l[c].data)){lt.isArray(t)?t=t.concat(lt.map(t,lt.camelCase)):t in o?t=[t]:(t=lt.camelCase(t),t=t in o?[t]:t.split(" "));for(i=0,r=t.length;r>i;i++)delete o[t[i]];if(!(n?s:lt.isEmptyObject)(o))return}(n||(delete l[c].data,s(l[c])))&&(a?lt.cleanData([e],!0):lt.support.deleteExpando||l!=l.window?delete l[c]:l[c]=null)}}}function a(e,n,i){if(i===t&&1===e.nodeType){var r="data-"+n.replace(Et,"-$1").toLowerCase();if(i=e.getAttribute(r),"string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:Ct.test(i)?lt.parseJSON(i):i}catch(o){}lt.data(e,n,i)}else i=t}return i}function s(e){var t;for(t in e)if(("data"!==t||!lt.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function l(){return!0}function c(){return!1}function u(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function d(e,t,n){if(t=t||0,lt.isFunction(t))return lt.grep(e,function(e,i){var r=!!t.call(e,i,e);return r===n});if(t.nodeType)return lt.grep(e,function(e){return e===t===n});if("string"==typeof t){var i=lt.grep(e,function(e){return 1===e.nodeType});if(Kt.test(t))return lt.filter(t,i,!n);t=lt.filter(t,i)}return lt.grep(e,function(e){return lt.inArray(e,t)>=0===n})}function p(e){var t=Wt.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function h(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function m(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function g(e){var t=on.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function f(e,t){for(var n,i=0;null!=(n=e[i]);i++)lt._data(n,"globalEval",!t||lt._data(t[i],"globalEval"))}function b(e,t){if(1===t.nodeType&&lt.hasData(e)){var n,i,r,o=lt._data(e),a=lt._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(i=0,r=s[n].length;r>i;i++)lt.event.add(t,n,s[n][i])}a.data&&(a.data=lt.extend({},a.data))}}function v(e,t){var n,i,r;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!lt.support.noCloneEvent&&t[lt.expando]){r=lt._data(t);for(i in r.events)lt.removeEvent(t,i,r.handle);t.removeAttribute(lt.expando)}"script"===n&&t.text!==e.text?(m(t).text=e.text,g(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),lt.support.html5Clone&&e.innerHTML&&!lt.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&tn.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)}}function y(e,n){var i,r,o=0,a=typeof e.getElementsByTagName!==V?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==V?e.querySelectorAll(n||"*"):t;if(!a)for(a=[],i=e.childNodes||e;null!=(r=i[o]);o++)!n||lt.nodeName(r,n)?a.push(r):lt.merge(a,y(r,n));return n===t||n&&lt.nodeName(e,n)?lt.merge([e],a):a}function _(e){tn.test(e.type)&&(e.defaultChecked=e.checked)}function k(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),i=t,r=En.length;r--;)if(t=En[r]+n,t in e)return t;return i}function x(e,t){return e=t||e,"none"===lt.css(e,"display")||!lt.contains(e.ownerDocument,e)}function w(e,t){for(var n,i,r,o=[],a=0,s=e.length;s>a;a++)i=e[a],i.style&&(o[a]=lt._data(i,"olddisplay"),n=i.style.display,t?(o[a]||"none"!==n||(i.style.display=""),""===i.style.display&&x(i)&&(o[a]=lt._data(i,"olddisplay",S(i.nodeName)))):o[a]||(r=x(i),(n&&"none"!==n||!r)&&lt._data(i,"olddisplay",r?n:lt.css(i,"display"))));for(a=0;s>a;a++)i=e[a],i.style&&(t&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=t?o[a]||"":"none"));return e}function C(e,t,n){var i=vn.exec(t);return i?Math.max(0,i[1]-(n||0))+(i[2]||"px"):t}function E(e,t,n,i,r){for(var o=n===(i?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=lt.css(e,n+Cn[o],!0,r)),i?("content"===n&&(a-=lt.css(e,"padding"+Cn[o],!0,r)),"margin"!==n&&(a-=lt.css(e,"border"+Cn[o]+"Width",!0,r))):(a+=lt.css(e,"padding"+Cn[o],!0,r),"padding"!==n&&(a+=lt.css(e,"border"+Cn[o]+"Width",!0,r)));return a}function T(e,t,n){var i=!0,r="width"===t?e.offsetWidth:e.offsetHeight,o=dn(e),a=lt.support.boxSizing&&"border-box"===lt.css(e,"boxSizing",!1,o);if(0>=r||null==r){if(r=pn(e,t,o),(0>r||null==r)&&(r=e.style[t]),yn.test(r))return r;i=a&&(lt.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+E(e,t,n||(a?"border":"content"),i,o)+"px"}function S(e){var t=G,n=kn[e];return n||(n=A(e,t),"none"!==n&&n||(un=(un||lt("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(un[0].contentWindow||un[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=A(e,t),un.detach()),kn[e]=n),n}function A(e,t){var n=lt(t.createElement(e)).appendTo(t.body),i=lt.css(n[0],"display");return n.remove(),i}function R(e,t,n,i){var r;if(lt.isArray(t))lt.each(t,function(t,r){n||Sn.test(e)?i(e,r):R(e+"["+("object"==typeof r?t:"")+"]",r,n,i)});else if(n||"object"!==lt.type(t))i(e,t);else for(r in t)R(e+"["+r+"]",t[r],n,i)}function I(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var i,r=0,o=t.toLowerCase().match(ut)||[];if(lt.isFunction(n))for(;i=o[r++];)"+"===i[0]?(i=i.slice(1)||"*",(e[i]=e[i]||[]).unshift(n)):(e[i]=e[i]||[]).push(n)}}function D(e,n,i,r){function o(l){var c;return a[l]=!0,lt.each(e[l]||[],function(e,l){var u=l(n,i,r);return"string"!=typeof u||s||a[u]?s?!(c=u):t:(n.dataTypes.unshift(u),o(u),!1)}),c}var a={},s=e===Un;return o(n.dataTypes[0])||!a["*"]&&o("*")}function O(e,n){var i,r,o=lt.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((o[r]?e:i||(i={}))[r]=n[r]);return i&&lt.extend(!0,e,i),e}function L(e,n,i){var r,o,a,s,l=e.contents,c=e.dataTypes,u=e.responseFields;for(s in u)s in i&&(n[u[s]]=i[s]);for(;"*"===c[0];)c.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){c.unshift(s);break}if(c[0]in i)a=c[0];else{for(s in i){if(!c[0]||e.converters[s+" "+c[0]]){a=s;break}r||(r=s)}a=a||r}return a?(a!==c[0]&&c.unshift(a),i[a]):t}function F(e,t){var n,i,r,o,a={},s=0,l=e.dataTypes.slice(),c=l[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l[1])for(r in e.converters)a[r.toLowerCase()]=e.converters[r];for(;i=l[++s];)if("*"!==i){if("*"!==c&&c!==i){if(r=a[c+" "+i]||a["* "+i],!r)for(n in a)if(o=n.split(" "),o[1]===i&&(r=a[c+" "+o[0]]||a["* "+o[0]])){r===!0?r=a[n]:a[n]!==!0&&(i=o[0],l.splice(s--,0,i));break}if(r!==!0)if(r&&e["throws"])t=r(t);else try{t=r(t)}catch(u){return{state:"parsererror",error:r?u:"No conversion from "+c+" to "+i}}}c=i}return{state:"success",data:t}}function N(){try{return new e.XMLHttpRequest}catch(t){}}function P(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function B(){return setTimeout(function(){Qn=t}),Qn=lt.now()}function M(e,t){lt.each(t,function(t,n){for(var i=(oi[t]||[]).concat(oi["*"]),r=0,o=i.length;o>r;r++)if(i[r].call(e,t,n))return})}function j(e,t,n){var i,r,o=0,a=ri.length,s=lt.Deferred().always(function(){delete l.elem}),l=function(){if(r)return!1;for(var t=Qn||B(),n=Math.max(0,c.startTime+c.duration-t),i=n/c.duration||0,o=1-i,a=0,l=c.tweens.length;l>a;a++)c.tweens[a].run(o);return s.notifyWith(e,[c,o,n]),1>o&&l?n:(s.resolveWith(e,[c]),!1)},c=s.promise({elem:e,props:lt.extend({},t),opts:lt.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Qn||B(),duration:n.duration,tweens:[],createTween:function(t,n){var i=lt.Tween(e,c.opts,t,n,c.opts.specialEasing[t]||c.opts.easing);return c.tweens.push(i),i},stop:function(t){var n=0,i=t?c.tweens.length:0;if(r)return this;for(r=!0;i>n;n++)c.tweens[n].run(1);return t?s.resolveWith(e,[c,t]):s.rejectWith(e,[c,t]),this}}),u=c.props;for(z(u,c.opts.specialEasing);a>o;o++)if(i=ri[o].call(c,e,u,c.opts))return i;return M(c,u),lt.isFunction(c.opts.start)&&c.opts.start.call(e,c),lt.fx.timer(lt.extend(l,{elem:e,anim:c,queue:c.opts.queue})),c.progress(c.opts.progress).done(c.opts.done,c.opts.complete).fail(c.opts.fail).always(c.opts.always)}function z(e,t){var n,i,r,o,a;for(r in e)if(i=lt.camelCase(r),o=t[i],n=e[r],lt.isArray(n)&&(o=n[1],n=e[r]=n[0]),r!==i&&(e[i]=n,delete e[r]),a=lt.cssHooks[i],a&&"expand"in a){n=a.expand(n),delete e[i];for(r in n)r in e||(e[r]=n[r],t[r]=o)}else t[i]=o}function $(e,t,n){var i,r,o,a,s,l,c,u,d,p=this,h=e.style,m={},g=[],f=e.nodeType&&x(e);n.queue||(u=lt._queueHooks(e,"fx"),null==u.unqueued&&(u.unqueued=0,d=u.empty.fire,u.empty.fire=function(){u.unqueued||d()}),u.unqueued++,p.always(function(){p.always(function(){u.unqueued--,lt.queue(e,"fx").length||u.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],"inline"===lt.css(e,"display")&&"none"===lt.css(e,"float")&&(lt.support.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?h.zoom=1:h.display="inline-block")),n.overflow&&(h.overflow="hidden",lt.support.shrinkWrapBlocks||p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(r in t)if(a=t[r],ti.exec(a)){if(delete t[r],l=l||"toggle"===a,a===(f?"hide":"show"))continue;g.push(r)}if(o=g.length){s=lt._data(e,"fxshow")||lt._data(e,"fxshow",{}),"hidden"in s&&(f=s.hidden),l&&(s.hidden=!f),f?lt(e).show():p.done(function(){lt(e).hide()}),p.done(function(){var t;lt._removeData(e,"fxshow");for(t in m)lt.style(e,t,m[t])});for(r=0;o>r;r++)i=g[r],c=p.createTween(i,f?s[i]:0),m[i]=s[i]||lt.style(e,i),i in s||(s[i]=c.start,f&&(c.end=c.start,c.start="width"===i||"height"===i?1:0))}}function H(e,t,n,i,r){return new H.prototype.init(e,t,n,i,r)}function K(e,t){var n,i={height:e},r=0;for(t=t?1:0;4>r;r+=2-t)n=Cn[r],i["margin"+n]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function U(e){return lt.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var q,W,V=typeof t,G=e.document,Y=e.location,X=e.jQuery,J=e.$,Z={},Q=[],et="1.9.1",tt=Q.concat,nt=Q.push,it=Q.slice,rt=Q.indexOf,ot=Z.toString,at=Z.hasOwnProperty,st=et.trim,lt=function(e,t){return new lt.fn.init(e,t,W)},ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ut=/\S+/g,dt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,pt=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,ht=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,mt=/^[\],:{}\s]*$/,gt=/(?:^|:|,)(?:\s*\[)+/g,ft=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,bt=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,vt=/^-ms-/,yt=/-([\da-z])/gi,_t=function(e,t){return t.toUpperCase()},kt=function(e){(G.addEventListener||"load"===e.type||"complete"===G.readyState)&&(xt(),lt.ready())},xt=function(){G.addEventListener?(G.removeEventListener("DOMContentLoaded",kt,!1),e.removeEventListener("load",kt,!1)):(G.detachEvent("onreadystatechange",kt),e.detachEvent("onload",kt))};lt.fn=lt.prototype={jquery:et,constructor:lt,init:function(e,n,i){var r,o;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:pt.exec(e),!r||!r[1]&&n)return!n||n.jquery?(n||i).find(e):this.constructor(n).find(e);if(r[1]){if(n=n instanceof lt?n[0]:n,lt.merge(this,lt.parseHTML(r[1],n&&n.nodeType?n.ownerDocument||n:G,!0)),ht.test(r[1])&&lt.isPlainObject(n))for(r in n)lt.isFunction(this[r])?this[r](n[r]):this.attr(r,n[r]);return this}if(o=G.getElementById(r[2]),o&&o.parentNode){if(o.id!==r[2])return i.find(e);this.length=1,this[0]=o}return this.context=G,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):lt.isFunction(e)?i.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),lt.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return it.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=lt.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return lt.each(this,e,t)},ready:function(e){return lt.ready.promise().done(e),this},slice:function(){return this.pushStack(it.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(lt.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:nt,sort:[].sort,splice:[].splice},lt.fn.init.prototype=lt.fn,lt.extend=lt.fn.extend=function(){var e,n,i,r,o,a,s=arguments[0]||{},l=1,c=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[1]||{},l=2),"object"==typeof s||lt.isFunction(s)||(s={}),c===l&&(s=this,--l);c>l;l++)if(null!=(o=arguments[l]))for(r in o)e=s[r],i=o[r],s!==i&&(u&&i&&(lt.isPlainObject(i)||(n=lt.isArray(i)))?(n?(n=!1,a=e&&lt.isArray(e)?e:[]):a=e&&lt.isPlainObject(e)?e:{},s[r]=lt.extend(u,a,i)):i!==t&&(s[r]=i));return s},lt.extend({noConflict:function(t){return e.$===lt&&(e.$=J),t&&e.jQuery===lt&&(e.jQuery=X),lt},isReady:!1,readyWait:1,holdReady:function(e){e?lt.readyWait++:lt.ready(!0)},ready:function(e){if(e===!0?!--lt.readyWait:!lt.isReady){if(!G.body)return setTimeout(lt.ready);lt.isReady=!0,e!==!0&&--lt.readyWait>0||(q.resolveWith(G,[lt]),lt.fn.trigger&&lt(G).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===lt.type(e)},isArray:Array.isArray||function(e){return"array"===lt.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?Z[ot.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==lt.type(e)||e.nodeType||lt.isWindow(e))return!1;try{if(e.constructor&&!at.call(e,"constructor")&&!at.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var i;for(i in e);return i===t||at.call(e,i)},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||G;var i=ht.exec(e),r=!n&&[];return i?[t.createElement(i[1])]:(i=lt.buildFragment([e],t,r),r&&lt(r).remove(),lt.merge([],i.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=lt.trim(n),n&&mt.test(n.replace(ft,"@").replace(bt,"]").replace(gt,"")))?Function("return "+n)():(lt.error("Invalid JSON: "+n),t)},parseXML:function(n){var i,r;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(r=new DOMParser,i=r.parseFromString(n,"text/xml")):(i=new ActiveXObject("Microsoft.XMLDOM"),i.async="false",i.loadXML(n))}catch(o){i=t}return i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||lt.error("Invalid XML: "+n),i},noop:function(){},globalEval:function(t){t&&lt.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(vt,"ms-").replace(yt,_t)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var r,o=0,a=e.length,s=n(e);if(i){if(s)for(;a>o&&(r=t.apply(e[o],i),r!==!1);o++);else for(o in e)if(r=t.apply(e[o],i),r===!1)break}else if(s)for(;a>o&&(r=t.call(e[o],o,e[o]),r!==!1);o++);else for(o in e)if(r=t.call(e[o],o,e[o]),r===!1)break;return e},trim:st&&!st.call(" ")?function(e){return null==e?"":st.call(e)}:function(e){return null==e?"":(e+"").replace(dt,"")},makeArray:function(e,t){var i=t||[];return null!=e&&(n(Object(e))?lt.merge(i,"string"==typeof e?[e]:e):nt.call(i,e)),i},inArray:function(e,t,n){var i;if(t){if(rt)return rt.call(t,e,n);for(i=t.length,n=n?0>n?Math.max(0,i+n):n:0;i>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var i=n.length,r=e.length,o=0;if("number"==typeof i)for(;i>o;o++)e[r++]=n[o];else for(;n[o]!==t;)e[r++]=n[o++];return e.length=r,e},grep:function(e,t,n){var i,r=[],o=0,a=e.length;for(n=!!n;a>o;o++)i=!!t(e[o],o),n!==i&&r.push(e[o]);return r},map:function(e,t,i){var r,o=0,a=e.length,s=n(e),l=[];if(s)for(;a>o;o++)r=t(e[o],o,i),null!=r&&(l[l.length]=r);else for(o in e)r=t(e[o],o,i),null!=r&&(l[l.length]=r);return tt.apply([],l)},guid:1,proxy:function(e,n){var i,r,o;return"string"==typeof n&&(o=e[n],n=e,e=o),lt.isFunction(e)?(i=it.call(arguments,2),r=function(){return e.apply(n||this,i.concat(it.call(arguments)))},r.guid=e.guid=e.guid||lt.guid++,r):t},access:function(e,n,i,r,o,a,s){var l=0,c=e.length,u=null==i;if("object"===lt.type(i)){o=!0;for(l in i)lt.access(e,n,l,i[l],!0,a,s)}else if(r!==t&&(o=!0,lt.isFunction(r)||(s=!0),u&&(s?(n.call(e,r),n=null):(u=n,n=function(e,t,n){return u.call(lt(e),n)})),n))for(;c>l;l++)n(e[l],i,s?r:r.call(e[l],l,n(e[l],i)));return o?e:u?n.call(e):c?n(e[0],i):a},now:function(){return(new Date).getTime()}}),lt.ready.promise=function(t){if(!q)if(q=lt.Deferred(),"complete"===G.readyState)setTimeout(lt.ready);else if(G.addEventListener)G.addEventListener("DOMContentLoaded",kt,!1),e.addEventListener("load",kt,!1);else{G.attachEvent("onreadystatechange",kt),e.attachEvent("onload",kt);var n=!1;try{n=null==e.frameElement&&G.documentElement}catch(i){}n&&n.doScroll&&function r(){if(!lt.isReady){try{n.doScroll("left")}catch(e){return setTimeout(r,50)}xt(),lt.ready()}}()}return q.promise(t)},lt.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()}),W=lt(G);var wt={};lt.Callbacks=function(e){e="string"==typeof e?wt[e]||i(e):lt.extend({},e);var n,r,o,a,s,l,c=[],u=!e.once&&[],d=function(t){for(r=e.memory&&t,o=!0,s=l||0,l=0,a=c.length,n=!0;c&&a>s;s++)if(c[s].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,c&&(u?u.length&&d(u.shift()):r?c=[]:p.disable())},p={add:function(){if(c){var t=c.length;(function i(t){lt.each(t,function(t,n){var r=lt.type(n);"function"===r?e.unique&&p.has(n)||c.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?a=c.length:r&&(l=t,d(r))}return this},remove:function(){return c&&lt.each(arguments,function(e,t){for(var i;(i=lt.inArray(t,c,i))>-1;)c.splice(i,1),n&&(a>=i&&a--,s>=i&&s--)}),this},has:function(e){return e?lt.inArray(e,c)>-1:!(!c||!c.length)},empty:function(){return c=[],this},disable:function(){return c=u=r=t,this},disabled:function(){return!c},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!c||o&&!u||(n?u.push(t):d(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!o}};return p},lt.extend({Deferred:function(e){var t=[["resolve","done",lt.Callbacks("once memory"),"resolved"],["reject","fail",lt.Callbacks("once memory"),"rejected"],["notify","progress",lt.Callbacks("memory")]],n="pending",i={state:function(){return n},always:function(){return r.done(arguments).fail(arguments),this},then:function(){var e=arguments;return lt.Deferred(function(n){lt.each(t,function(t,o){var a=o[0],s=lt.isFunction(e[t])&&e[t];r[o[1]](function(){var e=s&&s.apply(this,arguments);e&&lt.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===i?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?lt.extend(e,i):i}},r={};return i.pipe=i.then,lt.each(t,function(e,o){var a=o[2],s=o[3];i[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),r[o[0]]=function(){return r[o[0]+"With"](this===r?i:this,arguments),this},r[o[0]+"With"]=a.fireWith}),i.promise(r),e&&e.call(r,r),r},when:function(e){var t,n,i,r=0,o=it.call(arguments),a=o.length,s=1!==a||e&&lt.isFunction(e.promise)?a:0,l=1===s?e:lt.Deferred(),c=function(e,n,i){return function(r){n[e]=this,i[e]=arguments.length>1?it.call(arguments):r,i===t?l.notifyWith(n,i):--s||l.resolveWith(n,i)}};if(a>1)for(t=Array(a),n=Array(a),i=Array(a);a>r;r++)o[r]&&lt.isFunction(o[r].promise)?o[r].promise().done(c(r,i,o)).fail(l.reject).progress(c(r,n,t)):--s;return s||l.resolveWith(i,o),l.promise()}}),lt.support=function(){var t,n,i,r,o,a,s,l,c,u,d=G.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0],!n||!i||!n.length)return{};o=G.createElement("select"),s=o.appendChild(G.createElement("option")),r=d.getElementsByTagName("input")[0],i.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(i.getAttribute("style")),hrefNormalized:"/a"===i.getAttribute("href"),opacity:/^0.5/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:!!r.value,optSelected:s.selected,enctype:!!G.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==G.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===G.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},r.checked=!0,t.noCloneChecked=r.cloneNode(!0).checked,o.disabled=!0,t.optDisabled=!s.disabled;try{delete d.test}catch(p){t.deleteExpando=!1}r=G.createElement("input"),r.setAttribute("value",""),t.input=""===r.getAttribute("value"),r.value="t",r.setAttribute("type","radio"),t.radioValue="t"===r.value,r.setAttribute("checked","t"),r.setAttribute("name","t"),a=G.createDocumentFragment(),a.appendChild(r),t.appendChecked=r.checked,t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(u in{submit:!0,change:!0,focusin:!0})d.setAttribute(l="on"+u,"t"),t[u+"Bubbles"]=l in e||d.attributes[l].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,lt(function(){var n,i,r,o="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",a=G.getElementsByTagName("body")[0];a&&(n=G.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",r=d.getElementsByTagName("td"),r[0].style.cssText="padding:0;margin:0;border:0;display:none",c=0===r[0].offsetHeight,r[0].style.display="",r[1].style.display="none",t.reliableHiddenOffsets=c&&0===r[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!==a.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,i=d.appendChild(G.createElement("div")),i.style.cssText=d.style.cssText=o,i.style.marginRight=i.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)),typeof d.style.zoom!==V&&(d.innerHTML="",d.style.cssText=o+"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&&(a.style.zoom=1)),a.removeChild(n),n=d=r=i=null)}),n=o=a=s=i=r=null,t}();var Ct=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,Et=/([A-Z])/g;lt.extend({cache:{},expando:"jQuery"+(et+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?lt.cache[e[lt.expando]]:e[lt.expando],!!e&&!s(e)},data:function(e,t,n){return r(e,t,n)},removeData:function(e,t){return o(e,t)},_data:function(e,t,n){return r(e,t,n,!0)},_removeData:function(e,t){return o(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&lt.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),lt.fn.extend({data:function(e,n){var i,r,o=this[0],s=0,l=null;if(e===t){if(this.length&&(l=lt.data(o),1===o.nodeType&&!lt._data(o,"parsedAttrs"))){for(i=o.attributes;i.length>s;s++)r=i[s].name,r.indexOf("data-")||(r=lt.camelCase(r.slice(5)),a(o,r,l[r]));lt._data(o,"parsedAttrs",!0)}return l}return"object"==typeof e?this.each(function(){lt.data(this,e)}):lt.access(this,function(n){return n===t?o?a(o,e,lt.data(o,e)):null:(this.each(function(){lt.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){lt.removeData(this,e)})}}),lt.extend({queue:function(e,n,i){var r;return e?(n=(n||"fx")+"queue",r=lt._data(e,n),i&&(!r||lt.isArray(i)?r=lt._data(e,n,lt.makeArray(i)):r.push(i)),r||[]):t},dequeue:function(e,t){t=t||"fx";var n=lt.queue(e,t),i=n.length,r=n.shift(),o=lt._queueHooks(e,t),a=function(){lt.dequeue(e,t)};"inprogress"===r&&(r=n.shift(),i--),o.cur=r,r&&("fx"===t&&n.unshift("inprogress"),delete o.stop,r.call(e,a,o)),!i&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return lt._data(e,n)||lt._data(e,n,{empty:lt.Callbacks("once memory").add(function(){lt._removeData(e,t+"queue"),lt._removeData(e,n)})})}}),lt.fn.extend({queue:function(e,n){var i=2;return"string"!=typeof e&&(n=e,e="fx",i--),i>arguments.length?lt.queue(this[0],e):n===t?this:this.each(function(){var t=lt.queue(this,e,n);lt._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&lt.dequeue(this,e)})},dequeue:function(e){return this.each(function(){lt.dequeue(this,e)})},delay:function(e,t){return e=lt.fx?lt.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var i=setTimeout(t,e);n.stop=function(){clearTimeout(i)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var i,r=1,o=lt.Deferred(),a=this,s=this.length,l=function(){--r||o.resolveWith(a,[a])};for("string"!=typeof e&&(n=e,e=t),e=e||"fx";s--;)i=lt._data(a[s],e+"queueHooks"),i&&i.empty&&(r++,i.empty.add(l));return l(),o.promise(n)}});var Tt,St,At=/[\t\r\n]/g,Rt=/\r/g,It=/^(?:input|select|textarea|button|object)$/i,Dt=/^(?:a|area)$/i,Ot=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,Lt=/^(?:checked|selected)$/i,Ft=lt.support.getSetAttribute,Nt=lt.support.input;lt.fn.extend({attr:function(e,t){return lt.access(this,lt.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){lt.removeAttr(this,e)})},prop:function(e,t){return lt.access(this,lt.prop,e,t,arguments.length>1)},removeProp:function(e){return e=lt.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,i,r,o,a=0,s=this.length,l="string"==typeof e&&e;if(lt.isFunction(e))return this.each(function(t){lt(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(ut)||[];s>a;a++)if(n=this[a],i=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(At," "):" ")){for(o=0;r=t[o++];)0>i.indexOf(" "+r+" ")&&(i+=r+" ");n.className=lt.trim(i)}return this},removeClass:function(e){var t,n,i,r,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(lt.isFunction(e))return this.each(function(t){lt(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(ut)||[];s>a;a++)if(n=this[a],i=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(At," "):"")){for(o=0;r=t[o++];)for(;i.indexOf(" "+r+" ")>=0;)i=i.replace(" "+r+" "," ");n.className=e?lt.trim(i):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return lt.isFunction(e)?this.each(function(n){lt(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var r,o=0,a=lt(this),s=t,l=e.match(ut)||[];r=l[o++];)s=i?s:!a.hasClass(r),a[s?"addClass":"removeClass"](r);else(n===V||"boolean"===n)&&(this.className&&lt._data(this,"__className__",this.className),this.className=this.className||e===!1?"":lt._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,i=this.length;i>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(At," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,i,r,o=this[0];{if(arguments.length)return r=lt.isFunction(e),this.each(function(n){var o,a=lt(this);1===this.nodeType&&(o=r?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":lt.isArray(o)&&(o=lt.map(o,function(e){return null==e?"":e+""})),i=lt.valHooks[this.type]||lt.valHooks[this.nodeName.toLowerCase()],i&&"set"in i&&i.set(this,o,"value")!==t||(this.value=o))});if(o)return i=lt.valHooks[o.type]||lt.valHooks[o.nodeName.toLowerCase()],i&&"get"in i&&(n=i.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(Rt,""):null==n?"":n)}}}),lt.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){for(var t,n,i=e.options,r=e.selectedIndex,o="select-one"===e.type||0>r,a=o?null:[],s=o?r+1:i.length,l=0>r?s:o?r:0;s>l;l++)if(n=i[l],!(!n.selected&&l!==r||(lt.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&lt.nodeName(n.parentNode,"optgroup"))){if(t=lt(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=lt.makeArray(t);return lt(e).find("option").each(function(){this.selected=lt.inArray(lt(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,i){var r,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===V?lt.prop(e,n,i):(o=1!==s||!lt.isXMLDoc(e),o&&(n=n.toLowerCase(),r=lt.attrHooks[n]||(Ot.test(n)?St:Tt)),i===t?r&&o&&"get"in r&&null!==(a=r.get(e,n))?a:(typeof e.getAttribute!==V&&(a=e.getAttribute(n)),null==a?t:a):null!==i?r&&o&&"set"in r&&(a=r.set(e,i,n))!==t?a:(e.setAttribute(n,i+""),i):(lt.removeAttr(e,n),t))},removeAttr:function(e,t){var n,i,r=0,o=t&&t.match(ut);if(o&&1===e.nodeType)for(;n=o[r++];)i=lt.propFix[n]||n,Ot.test(n)?!Ft&&Lt.test(n)?e[lt.camelCase("default-"+n)]=e[i]=!1:e[i]=!1:lt.attr(e,n,""),e.removeAttribute(Ft?n:i)},attrHooks:{type:{set:function(e,t){if(!lt.support.radioValue&&"radio"===t&&lt.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,i){var r,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!lt.isXMLDoc(e),a&&(n=lt.propFix[n]||n,o=lt.propHooks[n]),i!==t?o&&"set"in o&&(r=o.set(e,i,n))!==t?r:e[n]=i:o&&"get"in o&&null!==(r=o.get(e,n))?r:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):It.test(e.nodeName)||Dt.test(e.nodeName)&&e.href?0:t}}}}),St={get:function(e,n){var i=lt.prop(e,n),r="boolean"==typeof i&&e.getAttribute(n),o="boolean"==typeof i?Nt&&Ft?null!=r:Lt.test(n)?e[lt.camelCase("default-"+n)]:!!r:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t },set:function(e,t,n){return t===!1?lt.removeAttr(e,n):Nt&&Ft||!Lt.test(n)?e.setAttribute(!Ft&&lt.propFix[n]||n,n):e[lt.camelCase("default-"+n)]=e[n]=!0,n}},Nt&&Ft||(lt.attrHooks.value={get:function(e,n){var i=e.getAttributeNode(n);return lt.nodeName(e,"input")?e.defaultValue:i&&i.specified?i.value:t},set:function(e,n,i){return lt.nodeName(e,"input")?(e.defaultValue=n,t):Tt&&Tt.set(e,n,i)}}),Ft||(Tt=lt.valHooks.button={get:function(e,n){var i=e.getAttributeNode(n);return i&&("id"===n||"name"===n||"coords"===n?""!==i.value:i.specified)?i.value:t},set:function(e,n,i){var r=e.getAttributeNode(i);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i)),r.value=n+="","value"===i||n===e.getAttribute(i)?n:t}},lt.attrHooks.contenteditable={get:Tt.get,set:function(e,t,n){Tt.set(e,""===t?!1:t,n)}},lt.each(["width","height"],function(e,n){lt.attrHooks[n]=lt.extend(lt.attrHooks[n],{set:function(e,i){return""===i?(e.setAttribute(n,"auto"),i):t}})})),lt.support.hrefNormalized||(lt.each(["href","src","width","height"],function(e,n){lt.attrHooks[n]=lt.extend(lt.attrHooks[n],{get:function(e){var i=e.getAttribute(n,2);return null==i?t:i}})}),lt.each(["href","src"],function(e,t){lt.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),lt.support.style||(lt.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),lt.support.optSelected||(lt.propHooks.selected=lt.extend(lt.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),lt.support.enctype||(lt.propFix.enctype="encoding"),lt.support.checkOn||lt.each(["radio","checkbox"],function(){lt.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),lt.each(["radio","checkbox"],function(){lt.valHooks[this]=lt.extend(lt.valHooks[this],{set:function(e,n){return lt.isArray(n)?e.checked=lt.inArray(lt(e).val(),n)>=0:t}})});var Pt=/^(?:input|select|textarea)$/i,Bt=/^key/,Mt=/^(?:mouse|contextmenu)|click/,jt=/^(?:focusinfocus|focusoutblur)$/,zt=/^([^.]*)(?:\.(.+)|)$/;lt.event={global:{},add:function(e,n,i,r,o){var a,s,l,c,u,d,p,h,m,g,f,b=lt._data(e);if(b){for(i.handler&&(c=i,i=c.handler,o=c.selector),i.guid||(i.guid=lt.guid++),(s=b.events)||(s=b.events={}),(d=b.handle)||(d=b.handle=function(e){return typeof lt===V||e&&lt.event.triggered===e.type?t:lt.event.dispatch.apply(d.elem,arguments)},d.elem=e),n=(n||"").match(ut)||[""],l=n.length;l--;)a=zt.exec(n[l])||[],m=f=a[1],g=(a[2]||"").split(".").sort(),u=lt.event.special[m]||{},m=(o?u.delegateType:u.bindType)||m,u=lt.event.special[m]||{},p=lt.extend({type:m,origType:f,data:r,handler:i,guid:i.guid,selector:o,needsContext:o&&lt.expr.match.needsContext.test(o),namespace:g.join(".")},c),(h=s[m])||(h=s[m]=[],h.delegateCount=0,u.setup&&u.setup.call(e,r,g,d)!==!1||(e.addEventListener?e.addEventListener(m,d,!1):e.attachEvent&&e.attachEvent("on"+m,d))),u.add&&(u.add.call(e,p),p.handler.guid||(p.handler.guid=i.guid)),o?h.splice(h.delegateCount++,0,p):h.push(p),lt.event.global[m]=!0;e=null}},remove:function(e,t,n,i,r){var o,a,s,l,c,u,d,p,h,m,g,f=lt.hasData(e)&&lt._data(e);if(f&&(u=f.events)){for(t=(t||"").match(ut)||[""],c=t.length;c--;)if(s=zt.exec(t[c])||[],h=g=s[1],m=(s[2]||"").split(".").sort(),h){for(d=lt.event.special[h]||{},h=(i?d.delegateType:d.bindType)||h,p=u[h]||[],s=s[2]&&RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=p.length;o--;)a=p[o],!r&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||i&&i!==a.selector&&("**"!==i||!a.selector)||(p.splice(o,1),a.selector&&p.delegateCount--,d.remove&&d.remove.call(e,a));l&&!p.length&&(d.teardown&&d.teardown.call(e,m,f.handle)!==!1||lt.removeEvent(e,h,f.handle),delete u[h])}else for(h in u)lt.event.remove(e,h+t[c],n,i,!0);lt.isEmptyObject(u)&&(delete f.handle,lt._removeData(e,"events"))}},trigger:function(n,i,r,o){var a,s,l,c,u,d,p,h=[r||G],m=at.call(n,"type")?n.type:n,g=at.call(n,"namespace")?n.namespace.split("."):[];if(l=d=r=r||G,3!==r.nodeType&&8!==r.nodeType&&!jt.test(m+lt.event.triggered)&&(m.indexOf(".")>=0&&(g=m.split("."),m=g.shift(),g.sort()),s=0>m.indexOf(":")&&"on"+m,n=n[lt.expando]?n:new lt.Event(m,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=g.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=r),i=null==i?[n]:lt.makeArray(i,[n]),u=lt.event.special[m]||{},o||!u.trigger||u.trigger.apply(r,i)!==!1)){if(!o&&!u.noBubble&&!lt.isWindow(r)){for(c=u.delegateType||m,jt.test(c+m)||(l=l.parentNode);l;l=l.parentNode)h.push(l),d=l;d===(r.ownerDocument||G)&&h.push(d.defaultView||d.parentWindow||e)}for(p=0;(l=h[p++])&&!n.isPropagationStopped();)n.type=p>1?c:u.bindType||m,a=(lt._data(l,"events")||{})[n.type]&&lt._data(l,"handle"),a&&a.apply(l,i),a=s&&l[s],a&&lt.acceptData(l)&&a.apply&&a.apply(l,i)===!1&&n.preventDefault();if(n.type=m,!(o||n.isDefaultPrevented()||u._default&&u._default.apply(r.ownerDocument,i)!==!1||"click"===m&&lt.nodeName(r,"a")||!lt.acceptData(r)||!s||!r[m]||lt.isWindow(r))){d=r[s],d&&(r[s]=null),lt.event.triggered=m;try{r[m]()}catch(f){}lt.event.triggered=t,d&&(r[s]=d)}return n.result}},dispatch:function(e){e=lt.event.fix(e);var n,i,r,o,a,s=[],l=it.call(arguments),c=(lt._data(this,"events")||{})[e.type]||[],u=lt.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(s=lt.event.handlers.call(this,e,c),n=0;(o=s[n++])&&!e.isPropagationStopped();)for(e.currentTarget=o.elem,a=0;(r=o.handlers[a++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,i=((lt.event.special[r.origType]||{}).handle||r.handler).apply(o.elem,l),i!==t&&(e.result=i)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,n){var i,r,o,a,s=[],l=n.delegateCount,c=e.target;if(l&&c.nodeType&&(!e.button||"click"!==e.type))for(;c!=this;c=c.parentNode||this)if(1===c.nodeType&&(c.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)r=n[a],i=r.selector+" ",o[i]===t&&(o[i]=r.needsContext?lt(i,this).index(c)>=0:lt.find(i,this,null,[c]).length),o[i]&&o.push(r);o.length&&s.push({elem:c,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[lt.expando])return e;var t,n,i,r=e.type,o=e,a=this.fixHooks[r];for(a||(this.fixHooks[r]=a=Mt.test(r)?this.mouseHooks:Bt.test(r)?this.keyHooks:{}),i=a.props?this.props.concat(a.props):this.props,e=new lt.Event(o),t=i.length;t--;)n=i[t],e[n]=o[n];return e.target||(e.target=o.srcElement||G),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):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 i,r,o,a=n.button,s=n.fromElement;return null==e.pageX&&null!=n.clientX&&(r=e.target.ownerDocument||G,o=r.documentElement,i=r.body,e.pageX=n.clientX+(o&&o.scrollLeft||i&&i.scrollLeft||0)-(o&&o.clientLeft||i&&i.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||i&&i.scrollTop||0)-(o&&o.clientTop||i&&i.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?n.toElement:s),e.which||a===t||(e.which=1&a?1:2&a?3:4&a?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return lt.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==G.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===G.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,i){var r=lt.extend(new lt.Event,n,{type:e,isSimulated:!0,originalEvent:{}});i?lt.event.trigger(r,null,t):lt.event.dispatch.call(t,r),r.isDefaultPrevented()&&n.preventDefault()}},lt.removeEvent=G.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var i="on"+t;e.detachEvent&&(typeof e[i]===V&&(e[i]=null),e.detachEvent(i,n))},lt.Event=function(e,n){return this instanceof lt.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?l:c):this.type=e,n&&lt.extend(this,n),this.timeStamp=e&&e.timeStamp||lt.now(),this[lt.expando]=!0,t):new lt.Event(e,n)},lt.Event.prototype={isDefaultPrevented:c,isPropagationStopped:c,isImmediatePropagationStopped:c,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=l,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=l,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=l,this.stopPropagation()}},lt.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){lt.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,i=this,r=e.relatedTarget,o=e.handleObj;return(!r||r!==i&&!lt.contains(i,r))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),lt.support.submitBubbles||(lt.event.special.submit={setup:function(){return lt.nodeName(this,"form")?!1:(lt.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,i=lt.nodeName(n,"input")||lt.nodeName(n,"button")?n.form:t;i&&!lt._data(i,"submitBubbles")&&(lt.event.add(i,"submit._submit",function(e){e._submit_bubble=!0}),lt._data(i,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&lt.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return lt.nodeName(this,"form")?!1:(lt.event.remove(this,"._submit"),t)}}),lt.support.changeBubbles||(lt.event.special.change={setup:function(){return Pt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(lt.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),lt.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),lt.event.simulate("change",this,e,!0)})),!1):(lt.event.add(this,"beforeactivate._change",function(e){var t=e.target;Pt.test(t.nodeName)&&!lt._data(t,"changeBubbles")&&(lt.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||lt.event.simulate("change",this.parentNode,e,!0)}),lt._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 lt.event.remove(this,"._change"),!Pt.test(this.nodeName)}}),lt.support.focusinBubbles||lt.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,i=function(e){lt.event.simulate(t,e.target,lt.event.fix(e),!0)};lt.event.special[t]={setup:function(){0===n++&&G.addEventListener(e,i,!0)},teardown:function(){0===--n&&G.removeEventListener(e,i,!0)}}}),lt.fn.extend({on:function(e,n,i,r,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(i=i||n,n=t);for(a in e)this.on(a,n,i,e[a],o);return this}if(null==i&&null==r?(r=n,i=n=t):null==r&&("string"==typeof n?(r=i,i=t):(r=i,i=n,n=t)),r===!1)r=c;else if(!r)return this;return 1===o&&(s=r,r=function(e){return lt().off(e),s.apply(this,arguments)},r.guid=s.guid||(s.guid=lt.guid++)),this.each(function(){lt.event.add(this,e,r,i,n)})},one:function(e,t,n,i){return this.on(e,t,n,i,1)},off:function(e,n,i){var r,o;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,lt(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(i=n,n=t),i===!1&&(i=c),this.each(function(){lt.event.remove(this,e,i,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,i){return this.on(t,e,n,i)},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(){lt.event.trigger(e,t,this)})},triggerHandler:function(e,n){var i=this[0];return i?lt.event.trigger(e,n,i,!0):t}}),function(e,t){function n(e){return mt.test(e+"")}function i(){var e,t=[];return e=function(n,i){return t.push(n+=" ")>C.cacheLength&&delete e[t.shift()],e[n]=i}}function r(e){return e[j]=!0,e}function o(e){var t=D.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function a(e,t,n,i){var r,o,a,s,l,c,u,h,m,g;if((t?t.ownerDocument||t:z)!==D&&I(t),t=t||D,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!L&&!i){if(r=gt.exec(e))if(a=r[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))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(r[2])return J.apply(n,Z.call(t.getElementsByTagName(e),0)),n;if((a=r[3])&&$.getByClassName&&t.getElementsByClassName)return J.apply(n,Z.call(t.getElementsByClassName(a),0)),n}if($.qsa&&!F.test(e)){if(u=!0,h=j,m=t,g=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(c=d(e),(u=t.getAttribute("id"))?h=u.replace(vt,"\\$&"):t.setAttribute("id",h),h="[id='"+h+"'] ",l=c.length;l--;)c[l]=h+p(c[l]);m=ht.test(e)&&t.parentNode||t,g=c.join(",")}if(g)try{return J.apply(n,Z.call(m.querySelectorAll(g),0)),n}catch(f){}finally{u||t.removeAttribute("id")}}}return _(e.replace(at,"$1"),t,n,i)}function s(e,t){var n=t&&e,i=n&&(~t.sourceIndex||G)-(~e.sourceIndex||G);if(i)return i;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function l(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function c(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,i){for(var r,o=e([],n.length,t),a=o.length;a--;)n[r=o[a]]&&(n[r]=!(i[r]=n[r]))})})}function d(e,t){var n,i,r,o,s,l,c,u=q[e+" "];if(u)return t?0:u.slice(0);for(s=e,l=[],c=C.preFilter;s;){(!n||(i=st.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(r=[])),n=!1,(i=ct.exec(s))&&(n=i.shift(),r.push({value:n,type:i[0].replace(at," ")}),s=s.slice(n.length));for(o in C.filter)!(i=pt[o].exec(s))||c[o]&&!(i=c[o](i))||(n=i.shift(),r.push({value:n,type:o,matches:i}),s=s.slice(n.length));if(!n)break}return t?s.length:s?a.error(e):q(e,l).slice(0)}function p(e){for(var t=0,n=e.length,i="";n>t;t++)i+=e[t].value;return i}function h(e,t,n){var i=t.dir,r=n&&"parentNode"===i,o=K++;return t.first?function(t,n,o){for(;t=t[i];)if(1===t.nodeType||r)return e(t,n,o)}:function(t,n,a){var s,l,c,u=H+" "+o;if(a){for(;t=t[i];)if((1===t.nodeType||r)&&e(t,n,a))return!0}else for(;t=t[i];)if(1===t.nodeType||r)if(c=t[j]||(t[j]={}),(l=c[i])&&l[0]===u){if((s=l[1])===!0||s===w)return s===!0}else if(l=c[i]=[u],l[1]=e(t,n,a)||w,l[1]===!0)return!0}}function m(e){return e.length>1?function(t,n,i){for(var r=e.length;r--;)if(!e[r](t,n,i))return!1;return!0}:e[0]}function g(e,t,n,i,r){for(var o,a=[],s=0,l=e.length,c=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,i,r))&&(a.push(o),c&&t.push(s));return a}function f(e,t,n,i,o,a){return i&&!i[j]&&(i=f(i)),o&&!o[j]&&(o=f(o,a)),r(function(r,a,s,l){var c,u,d,p=[],h=[],m=a.length,f=r||y(t||"*",s.nodeType?[s]:s,[]),b=!e||!r&&t?f:g(f,p,e,s,l),v=n?o||(r?e:m||i)?[]:a:b;if(n&&n(b,v,s,l),i)for(c=g(v,h),i(c,[],s,l),u=c.length;u--;)(d=c[u])&&(v[h[u]]=!(b[h[u]]=d));if(r){if(o||e){if(o){for(c=[],u=v.length;u--;)(d=v[u])&&c.push(b[u]=d);o(null,v=[],c,l)}for(u=v.length;u--;)(d=v[u])&&(c=o?Q.call(r,d):p[u])>-1&&(r[c]=!(a[c]=d))}}else v=g(v===a?v.splice(m,v.length):v),o?o(null,a,v,l):J.apply(a,v)})}function b(e){for(var t,n,i,r=e.length,o=C.relative[e[0].type],a=o||C.relative[" "],s=o?1:0,l=h(function(e){return e===t},a,!0),c=h(function(e){return Q.call(t,e)>-1},a,!0),u=[function(e,n,i){return!o&&(i||n!==R)||((t=n).nodeType?l(e,n,i):c(e,n,i))}];r>s;s++)if(n=C.relative[e[s].type])u=[h(m(u),n)];else{if(n=C.filter[e[s].type].apply(null,e[s].matches),n[j]){for(i=++s;r>i&&!C.relative[e[i].type];i++);return f(s>1&&m(u),s>1&&p(e.slice(0,s-1)).replace(at,"$1"),n,i>s&&b(e.slice(s,i)),r>i&&b(e=e.slice(i)),r>i&&p(e))}u.push(n)}return m(u)}function v(e,t){var n=0,i=t.length>0,o=e.length>0,s=function(r,s,l,c,u){var d,p,h,m=[],f=0,b="0",v=r&&[],y=null!=u,_=R,k=r||o&&C.find.TAG("*",u&&s.parentNode||s),x=H+=null==_?1:Math.random()||.1;for(y&&(R=s!==D&&s,w=n);null!=(d=k[b]);b++){if(o&&d){for(p=0;h=e[p++];)if(h(d,s,l)){c.push(d);break}y&&(H=x,w=++n)}i&&((d=!h&&d)&&f--,r&&v.push(d))}if(f+=b,i&&b!==f){for(p=0;h=t[p++];)h(v,m,s,l);if(r){if(f>0)for(;b--;)v[b]||m[b]||(m[b]=X.call(c));m=g(m)}J.apply(c,m),y&&!r&&m.length>0&&f+t.length>1&&a.uniqueSort(c)}return y&&(H=x,R=_),v};return i?r(s):s}function y(e,t,n){for(var i=0,r=t.length;r>i;i++)a(e,t[i],n);return n}function _(e,t,n,i){var r,o,a,s,l,c=d(e);if(!i&&1===c.length){if(o=c[0]=c[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&9===t.nodeType&&!L&&C.relative[o[1].type]){if(t=C.find.ID(a.matches[0].replace(_t,kt),t)[0],!t)return n;e=e.slice(o.shift().value.length)}for(r=pt.needsContext.test(e)?0:o.length;r--&&(a=o[r],!C.relative[s=a.type]);)if((l=C.find[s])&&(i=l(a.matches[0].replace(_t,kt),ht.test(o[0].type)&&t.parentNode||t))){if(o.splice(r,1),e=i.length&&p(o),!e)return J.apply(n,Z.call(i,0)),n;break}}return S(e,c)(i,t,L,n,ht.test(e)),n}function k(){}var x,w,C,E,T,S,A,R,I,D,O,L,F,N,P,B,M,j="sizzle"+-new Date,z=e.document,$={},H=0,K=0,U=i(),q=i(),W=i(),V=typeof t,G=1<<31,Y=[],X=Y.pop,J=Y.push,Z=Y.slice,Q=Y.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},et="[\\x20\\t\\r\\n\\f]",tt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=tt.replace("w","w#"),it="([*^$|!~]?=)",rt="\\["+et+"*("+tt+")"+et+"*(?:"+it+et+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+nt+")|)|)"+et+"*\\]",ot=":("+tt+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+rt.replace(3,8)+")*)|.*)\\)|)",at=RegExp("^"+et+"+|((?:^|[^\\\\])(?:\\\\.)*)"+et+"+$","g"),st=RegExp("^"+et+"*,"+et+"*"),ct=RegExp("^"+et+"*([\\x20\\t\\r\\n\\f>+~])"+et+"*"),ut=RegExp(ot),dt=RegExp("^"+nt+"$"),pt={ID:RegExp("^#("+tt+")"),CLASS:RegExp("^\\.("+tt+")"),NAME:RegExp("^\\[name=['\"]?("+tt+")['\"]?\\]"),TAG:RegExp("^("+tt.replace("w","w*")+")"),ATTR:RegExp("^"+rt),PSEUDO:RegExp("^"+ot),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+et+"*(even|odd|(([+-]|)(\\d*)n|)"+et+"*(?:([+-]|)"+et+"*(\\d+)|))"+et+"*\\)|)","i"),needsContext:RegExp("^"+et+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+et+"*((?:-\\d)?\\d*)"+et+"*\\)|)(?=[^-]|$)","i")},ht=/[\x20\t\r\n\f]*[+~]/,mt=/^[^{]+\{\s*\[native code/,gt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ft=/^(?:input|select|textarea|button)$/i,bt=/^h\d$/i,vt=/'|\\/g,yt=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,_t=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,kt=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{Z.call(z.documentElement.childNodes,0)[0].nodeType}catch(xt){Z=function(e){for(var t,n=[];t=this[e++];)n.push(t);return n}}T=a.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},I=a.setDocument=function(e){var i=e?e.ownerDocument||e:z;return i!==D&&9===i.nodeType&&i.documentElement?(D=i,O=i.documentElement,L=T(i),$.tagNameNoComments=o(function(e){return e.appendChild(i.createComment("")),!e.getElementsByTagName("*").length}),$.attributes=o(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),$.getByClassName=o(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}),$.getByName=o(function(e){e.id=j+0,e.innerHTML="<a name='"+j+"'></a><div name='"+j+"'></div>",O.insertBefore(e,O.firstChild);var t=i.getElementsByName&&i.getElementsByName(j).length===2+i.getElementsByName(j+0).length;return $.getIdNotName=!i.getElementById(j),O.removeChild(e),t}),C.attrHandle=o(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==V&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},$.getIdNotName?(C.find.ID=function(e,t){if(typeof t.getElementById!==V&&!L){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},C.filter.ID=function(e){var t=e.replace(_t,kt);return function(e){return e.getAttribute("id")===t}}):(C.find.ID=function(e,n){if(typeof n.getElementById!==V&&!L){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==V&&i.getAttributeNode("id").value===e?[i]:t:[]}},C.filter.ID=function(e){var t=e.replace(_t,kt);return function(e){var n=typeof e.getAttributeNode!==V&&e.getAttributeNode("id");return n&&n.value===t}}),C.find.TAG=$.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==V?n.getElementsByTagName(e):t}:function(e,t){var n,i=[],r=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[r++];)1===n.nodeType&&i.push(n);return i}return o},C.find.NAME=$.getByName&&function(e,n){return typeof n.getElementsByName!==V?n.getElementsByName(name):t},C.find.CLASS=$.getByClassName&&function(e,n){return typeof n.getElementsByClassName===V||L?t:n.getElementsByClassName(e)},N=[],F=[":focus"],($.qsa=n(i.querySelectorAll))&&(o(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||F.push("\\["+et+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||F.push(":checked")}),o(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&F.push("[*^$]="+et+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||F.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),F.push(",.*:")})),($.matchesSelector=n(P=O.matchesSelector||O.mozMatchesSelector||O.webkitMatchesSelector||O.oMatchesSelector||O.msMatchesSelector))&&o(function(e){$.disconnectedMatch=P.call(e,"div"),P.call(e,"[s!='']:x"),N.push("!=",ot)}),F=RegExp(F.join("|")),N=RegExp(N.join("|")),B=n(O.contains)||O.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},M=O.compareDocumentPosition?function(e,t){var n;return e===t?(A=!0,0):(n=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&n||e.parentNode&&11===e.parentNode.nodeType?e===i||B(z,e)?-1:t===i||B(z,t)?1:0:4&n?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var n,r=0,o=e.parentNode,a=t.parentNode,l=[e],c=[t];if(e===t)return A=!0,0;if(!o||!a)return e===i?-1:t===i?1:o?-1:a?1:0;if(o===a)return s(e,t);for(n=e;n=n.parentNode;)l.unshift(n);for(n=t;n=n.parentNode;)c.unshift(n);for(;l[r]===c[r];)r++;return r?s(l[r],c[r]):l[r]===z?-1:c[r]===z?1:0},A=!1,[0,0].sort(M),$.detectDuplicates=A,D):D},a.matches=function(e,t){return a(e,null,null,t)},a.matchesSelector=function(e,t){if((e.ownerDocument||e)!==D&&I(e),t=t.replace(yt,"='$1']"),!(!$.matchesSelector||L||N&&N.test(t)||F.test(t)))try{var n=P.call(e,t);if(n||$.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return a(t,D,null,[e]).length>0},a.contains=function(e,t){return(e.ownerDocument||e)!==D&&I(e),B(e,t)},a.attr=function(e,t){var n;return(e.ownerDocument||e)!==D&&I(e),L||(t=t.toLowerCase()),(n=C.attrHandle[t])?n(e):L||$.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},a.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},a.uniqueSort=function(e){var t,n=[],i=1,r=0;if(A=!$.detectDuplicates,e.sort(M),A){for(;t=e[i];i++)t===e[i-1]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return e},E=a.getText=function(e){var t,n="",i=0,r=e.nodeType;if(r){if(1===r||9===r||11===r){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=E(e)}else if(3===r||4===r)return e.nodeValue}else for(;t=e[i];i++)n+=E(t);return n},C=a.selectors={cacheLength:50,createPseudo:r,match:pt,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(_t,kt),e[3]=(e[4]||e[5]||"").replace(_t,kt),"~="===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]||a.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]&&a.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return pt.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&ut.test(n)&&(t=d(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(_t,kt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=U[e+" "];return t||(t=RegExp("(^|"+et+")"+e+"("+et+"|$)"))&&U(e,function(e){return t.test(e.className||typeof e.getAttribute!==V&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(i){var r=a.attr(i,e);return null==r?"!="===t:t?(r+="","="===t?r===n:"!="===t?r!==n:"^="===t?n&&0===r.indexOf(n):"*="===t?n&&r.indexOf(n)>-1:"$="===t?n&&r.slice(-n.length)===n:"~="===t?(" "+r+" ").indexOf(n)>-1:"|="===t?r===n||r.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,i,r){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===i&&0===r?function(e){return!!e.parentNode}:function(t,n,l){var c,u,d,p,h,m,g=o!==a?"nextSibling":"previousSibling",f=t.parentNode,b=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(f){if(o){for(;g;){for(d=t;d=d[g];)if(s?d.nodeName.toLowerCase()===b:1===d.nodeType)return!1;m=g="only"===e&&!m&&"nextSibling"}return!0}if(m=[a?f.firstChild:f.lastChild],a&&v){for(u=f[j]||(f[j]={}),c=u[e]||[],h=c[0]===H&&c[1],p=c[0]===H&&c[2],d=h&&f.childNodes[h];d=++h&&d&&d[g]||(p=h=0)||m.pop();)if(1===d.nodeType&&++p&&d===t){u[e]=[H,h,p];break}}else if(v&&(c=(t[j]||(t[j]={}))[e])&&c[0]===H)p=c[1];else for(;(d=++h&&d&&d[g]||(p=h=0)||m.pop())&&((s?d.nodeName.toLowerCase()!==b:1!==d.nodeType)||!++p||(v&&((d[j]||(d[j]={}))[e]=[H,p]),d!==t)););return p-=r,p===i||0===p%i&&p/i>=0}}},PSEUDO:function(e,t){var n,i=C.pseudos[e]||C.setFilters[e.toLowerCase()]||a.error("unsupported pseudo: "+e);return i[j]?i(t):i.length>1?(n=[e,e,"",t],C.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,n){for(var r,o=i(e,t),a=o.length;a--;)r=Q.call(e,o[a]),e[r]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:r(function(e){var t=[],n=[],i=S(e.replace(at,"$1"));return i[j]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(t){return a(e,t).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||E(t)).indexOf(e)>-1}}),lang:r(function(e){return dt.test(e||"")||a.error("unsupported lang: "+e),e=e.replace(_t,kt).toLowerCase(),function(t){var n;do if(n=L?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===O},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.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!C.pseudos.empty(e)},header:function(e){return bt.test(e.nodeName)},input:function(e){return ft.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:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var i=0>n?n+t:n;--i>=0;)e.push(i);return e}),gt:u(function(e,t,n){for(var i=0>n?n+t:n;t>++i;)e.push(i);return e})}};for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[x]=l(x);for(x in{submit:!0,reset:!0})C.pseudos[x]=c(x);S=a.compile=function(e,t){var n,i=[],r=[],o=W[e+" "];if(!o){for(t||(t=d(e)),n=t.length;n--;)o=b(t[n]),o[j]?i.push(o):r.push(o);o=W(e,v(r,i))}return o},C.pseudos.nth=C.pseudos.eq,C.filters=k.prototype=C.pseudos,C.setFilters=new k,I(),a.attr=lt.attr,lt.find=a,lt.expr=a.selectors,lt.expr[":"]=lt.expr.pseudos,lt.unique=a.uniqueSort,lt.text=a.getText,lt.isXMLDoc=a.isXML,lt.contains=a.contains}(e);var $t=/Until$/,Ht=/^(?:parents|prev(?:Until|All))/,Kt=/^.[^:#\[\.,]*$/,Ut=lt.expr.match.needsContext,qt={children:!0,contents:!0,next:!0,prev:!0};lt.fn.extend({find:function(e){var t,n,i,r=this.length;if("string"!=typeof e)return i=this,this.pushStack(lt(e).filter(function(){for(t=0;r>t;t++)if(lt.contains(i[t],this))return!0}));for(n=[],t=0;r>t;t++)lt.find(e,this[t],n);return n=this.pushStack(r>1?lt.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=lt(e,this),i=n.length;return this.filter(function(){for(t=0;i>t;t++)if(lt.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(d(this,e,!1))},filter:function(e){return this.pushStack(d(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?Ut.test(e)?lt(e,this.context).index(this[0])>=0:lt.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){for(var n,i=0,r=this.length,o=[],a=Ut.test(e)||"string"!=typeof e?lt(e,t||this.context):0;r>i;i++)for(n=this[i];n&&n.ownerDocument&&n!==t&&11!==n.nodeType;){if(a?a.index(n)>-1:lt.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}return this.pushStack(o.length>1?lt.unique(o):o)},index:function(e){return e?"string"==typeof e?lt.inArray(this[0],lt(e)):lt.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?lt(e,t):lt.makeArray(e&&e.nodeType?[e]:e),i=lt.merge(this.get(),n);return this.pushStack(lt.unique(i))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),lt.fn.andSelf=lt.fn.addBack,lt.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return lt.dir(e,"parentNode")},parentsUntil:function(e,t,n){return lt.dir(e,"parentNode",n)},next:function(e){return u(e,"nextSibling")},prev:function(e){return u(e,"previousSibling")},nextAll:function(e){return lt.dir(e,"nextSibling")},prevAll:function(e){return lt.dir(e,"previousSibling") },nextUntil:function(e,t,n){return lt.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return lt.dir(e,"previousSibling",n)},siblings:function(e){return lt.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return lt.sibling(e.firstChild)},contents:function(e){return lt.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:lt.merge([],e.childNodes)}},function(e,t){lt.fn[e]=function(n,i){var r=lt.map(this,t,n);return $t.test(e)||(i=n),i&&"string"==typeof i&&(r=lt.filter(i,r)),r=this.length>1&&!qt[e]?lt.unique(r):r,this.length>1&&Ht.test(e)&&(r=r.reverse()),this.pushStack(r)}}),lt.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?lt.find.matchesSelector(t[0],e)?[t[0]]:[]:lt.find.matches(e,t)},dir:function(e,n,i){for(var r=[],o=e[n];o&&9!==o.nodeType&&(i===t||1!==o.nodeType||!lt(o).is(i));)1===o.nodeType&&r.push(o),o=o[n];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});var Wt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Vt=/ jQuery\d+="(?:null|\d+)"/g,Gt=RegExp("<(?:"+Wt+")[\\s/>]","i"),Yt=/^\s+/,Xt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Jt=/<([\w:]+)/,Zt=/<tbody/i,Qt=/<|&#?\w+;/,en=/<(?:script|style|link)/i,tn=/^(?:checkbox|radio)$/i,nn=/checked\s*(?:[^=]|=\s*.checked.)/i,rn=/^$|\/(?:java|ecma)script/i,on=/^true\/(.*)/,an=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sn={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:lt.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},ln=p(G),cn=ln.appendChild(G.createElement("div"));sn.optgroup=sn.option,sn.tbody=sn.tfoot=sn.colgroup=sn.caption=sn.thead,sn.th=sn.td,lt.fn.extend({text:function(e){return lt.access(this,function(e){return e===t?lt.text(this):this.empty().append((this[0]&&this[0].ownerDocument||G).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(lt.isFunction(e))return this.each(function(t){lt(this).wrapAll(e.call(this,t))});if(this[0]){var t=lt(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return lt.isFunction(e)?this.each(function(t){lt(this).wrapInner(e.call(this,t))}):this.each(function(){var t=lt(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=lt.isFunction(e);return this.each(function(n){lt(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){lt.nodeName(this,"body")||lt(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){for(var n,i=0;null!=(n=this[i]);i++)(!e||lt.filter(e,[n]).length>0)&&(t||1!==n.nodeType||lt.cleanData(y(n)),n.parentNode&&(t&&lt.contains(n.ownerDocument,n)&&f(y(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&lt.cleanData(y(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&lt.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 lt.clone(this,e,t)})},html:function(e){return lt.access(this,function(e){var n=this[0]||{},i=0,r=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(Vt,""):t;if(!("string"!=typeof e||en.test(e)||!lt.support.htmlSerialize&&Gt.test(e)||!lt.support.leadingWhitespace&&Yt.test(e)||sn[(Jt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Xt,"<$1></$2>");try{for(;r>i;i++)n=this[i]||{},1===n.nodeType&&(lt.cleanData(y(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=lt.isFunction(e);return t||"string"==typeof e||(e=lt(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(lt(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,i){e=tt.apply([],e);var r,o,a,s,l,c,u=0,d=this.length,p=this,f=d-1,b=e[0],v=lt.isFunction(b);if(v||!(1>=d||"string"!=typeof b||lt.support.checkClone)&&nn.test(b))return this.each(function(r){var o=p.eq(r);v&&(e[0]=b.call(this,r,n?o.html():t)),o.domManip(e,n,i)});if(d&&(c=lt.buildFragment(e,this[0].ownerDocument,!1,this),r=c.firstChild,1===c.childNodes.length&&(c=r),r)){for(n=n&&lt.nodeName(r,"tr"),s=lt.map(y(c,"script"),m),a=s.length;d>u;u++)o=c,u!==f&&(o=lt.clone(o,!0,!0),a&&lt.merge(s,y(o,"script"))),i.call(n&&lt.nodeName(this[u],"table")?h(this[u],"tbody"):this[u],o,u);if(a)for(l=s[s.length-1].ownerDocument,lt.map(s,g),u=0;a>u;u++)o=s[u],rn.test(o.type||"")&&!lt._data(o,"globalEval")&&lt.contains(l,o)&&(o.src?lt.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):lt.globalEval((o.text||o.textContent||o.innerHTML||"").replace(an,"")));c=r=null}return this}}),lt.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){lt.fn[e]=function(e){for(var n,i=0,r=[],o=lt(e),a=o.length-1;a>=i;i++)n=i===a?this:this.clone(!0),lt(o[i])[t](n),nt.apply(r,n.get());return this.pushStack(r)}}),lt.extend({clone:function(e,t,n){var i,r,o,a,s,l=lt.contains(e.ownerDocument,e);if(lt.support.html5Clone||lt.isXMLDoc(e)||!Gt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(cn.innerHTML=e.outerHTML,cn.removeChild(o=cn.firstChild)),!(lt.support.noCloneEvent&&lt.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||lt.isXMLDoc(e)))for(i=y(o),s=y(e),a=0;null!=(r=s[a]);++a)i[a]&&v(r,i[a]);if(t)if(n)for(s=s||y(e),i=i||y(o),a=0;null!=(r=s[a]);a++)b(r,i[a]);else b(e,o);return i=y(o,"script"),i.length>0&&f(i,!l&&y(e,"script")),i=s=r=null,o},buildFragment:function(e,t,n,i){for(var r,o,a,s,l,c,u,d=e.length,h=p(t),m=[],g=0;d>g;g++)if(o=e[g],o||0===o)if("object"===lt.type(o))lt.merge(m,o.nodeType?[o]:o);else if(Qt.test(o)){for(s=s||h.appendChild(t.createElement("div")),l=(Jt.exec(o)||["",""])[1].toLowerCase(),u=sn[l]||sn._default,s.innerHTML=u[1]+o.replace(Xt,"<$1></$2>")+u[2],r=u[0];r--;)s=s.lastChild;if(!lt.support.leadingWhitespace&&Yt.test(o)&&m.push(t.createTextNode(Yt.exec(o)[0])),!lt.support.tbody)for(o="table"!==l||Zt.test(o)?"<table>"!==u[1]||Zt.test(o)?0:s:s.firstChild,r=o&&o.childNodes.length;r--;)lt.nodeName(c=o.childNodes[r],"tbody")&&!c.childNodes.length&&o.removeChild(c);for(lt.merge(m,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=h.lastChild}else m.push(t.createTextNode(o));for(s&&h.removeChild(s),lt.support.appendChecked||lt.grep(y(m,"input"),_),g=0;o=m[g++];)if((!i||-1===lt.inArray(o,i))&&(a=lt.contains(o.ownerDocument,o),s=y(h.appendChild(o),"script"),a&&f(s),n))for(r=0;o=s[r++];)rn.test(o.type||"")&&n.push(o);return s=null,h},cleanData:function(e,t){for(var n,i,r,o,a=0,s=lt.expando,l=lt.cache,c=lt.support.deleteExpando,u=lt.event.special;null!=(n=e[a]);a++)if((t||lt.acceptData(n))&&(r=n[s],o=r&&l[r])){if(o.events)for(i in o.events)u[i]?lt.event.remove(n,i):lt.removeEvent(n,i,o.handle);l[r]&&(delete l[r],c?delete n[s]:typeof n.removeAttribute!==V?n.removeAttribute(s):n[s]=null,Q.push(r))}}});var un,dn,pn,hn=/alpha\([^)]*\)/i,mn=/opacity\s*=\s*([^)]*)/,gn=/^(top|right|bottom|left)$/,fn=/^(none|table(?!-c[ea]).+)/,bn=/^margin/,vn=RegExp("^("+ct+")(.*)$","i"),yn=RegExp("^("+ct+")(?!px)[a-z%]+$","i"),_n=RegExp("^([+-])=("+ct+")","i"),kn={BODY:"block"},xn={position:"absolute",visibility:"hidden",display:"block"},wn={letterSpacing:0,fontWeight:400},Cn=["Top","Right","Bottom","Left"],En=["Webkit","O","Moz","ms"];lt.fn.extend({css:function(e,n){return lt.access(this,function(e,n,i){var r,o,a={},s=0;if(lt.isArray(n)){for(o=dn(e),r=n.length;r>s;s++)a[n[s]]=lt.css(e,n[s],!1,o);return a}return i!==t?lt.style(e,n,i):lt.css(e,n)},e,n,arguments.length>1)},show:function(){return w(this,!0)},hide:function(){return w(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:x(this))?lt(this).show():lt(this).hide()})}}),lt.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=pn(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":lt.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=lt.camelCase(n),c=e.style;if(n=lt.cssProps[l]||(lt.cssProps[l]=k(c,l)),s=lt.cssHooks[n]||lt.cssHooks[l],i===t)return s&&"get"in s&&(o=s.get(e,!1,r))!==t?o:c[n];if(a=typeof i,"string"===a&&(o=_n.exec(i))&&(i=(o[1]+1)*o[2]+parseFloat(lt.css(e,n)),a="number"),!(null==i||"number"===a&&isNaN(i)||("number"!==a||lt.cssNumber[l]||(i+="px"),lt.support.clearCloneStyle||""!==i||0!==n.indexOf("background")||(c[n]="inherit"),s&&"set"in s&&(i=s.set(e,i,r))===t)))try{c[n]=i}catch(u){}}},css:function(e,n,i,r){var o,a,s,l=lt.camelCase(n);return n=lt.cssProps[l]||(lt.cssProps[l]=k(e.style,l)),s=lt.cssHooks[n]||lt.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,i)),a===t&&(a=pn(e,n,r)),"normal"===a&&n in wn&&(a=wn[n]),""===i||i?(o=parseFloat(a),i===!0||lt.isNumeric(o)?o||0:a):a},swap:function(e,t,n,i){var r,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];r=n.apply(e,i||[]);for(o in t)e.style[o]=a[o];return r}}),e.getComputedStyle?(dn=function(t){return e.getComputedStyle(t,null)},pn=function(e,n,i){var r,o,a,s=i||dn(e),l=s?s.getPropertyValue(n)||s[n]:t,c=e.style;return s&&(""!==l||lt.contains(e.ownerDocument,e)||(l=lt.style(e,n)),yn.test(l)&&bn.test(n)&&(r=c.width,o=c.minWidth,a=c.maxWidth,c.minWidth=c.maxWidth=c.width=l,l=s.width,c.width=r,c.minWidth=o,c.maxWidth=a)),l}):G.documentElement.currentStyle&&(dn=function(e){return e.currentStyle},pn=function(e,n,i){var r,o,a,s=i||dn(e),l=s?s[n]:t,c=e.style;return null==l&&c&&c[n]&&(l=c[n]),yn.test(l)&&!gn.test(n)&&(r=c.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),c.left="fontSize"===n?"1em":l,l=c.pixelLeft+"px",c.left=r,a&&(o.left=a)),""===l?"auto":l}),lt.each(["height","width"],function(e,n){lt.cssHooks[n]={get:function(e,i,r){return i?0===e.offsetWidth&&fn.test(lt.css(e,"display"))?lt.swap(e,xn,function(){return T(e,n,r)}):T(e,n,r):t},set:function(e,t,i){var r=i&&dn(e);return C(e,t,i?E(e,n,i,lt.support.boxSizing&&"border-box"===lt.css(e,"boxSizing",!1,r),r):0)}}}),lt.support.opacity||(lt.cssHooks.opacity={get:function(e,t){return mn.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,i=e.currentStyle,r=lt.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=i&&i.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===lt.trim(o.replace(hn,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||i&&!i.filter)||(n.filter=hn.test(o)?o.replace(hn,r):o+" "+r)}}),lt(function(){lt.support.reliableMarginRight||(lt.cssHooks.marginRight={get:function(e,n){return n?lt.swap(e,{display:"inline-block"},pn,[e,"marginRight"]):t}}),!lt.support.pixelPosition&&lt.fn.position&&lt.each(["top","left"],function(e,n){lt.cssHooks[n]={get:function(e,i){return i?(i=pn(e,n),yn.test(i)?lt(e).position()[n]+"px":i):t}}})}),lt.expr&&lt.expr.filters&&(lt.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!lt.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||lt.css(e,"display"))},lt.expr.filters.visible=function(e){return!lt.expr.filters.hidden(e)}),lt.each({margin:"",padding:"",border:"Width"},function(e,t){lt.cssHooks[e+t]={expand:function(n){for(var i=0,r={},o="string"==typeof n?n.split(" "):[n];4>i;i++)r[e+Cn[i]+t]=o[i]||o[i-2]||o[0];return r}},bn.test(e)||(lt.cssHooks[e+t].set=C)});var Tn=/%20/g,Sn=/\[\]$/,An=/\r?\n/g,Rn=/^(?:submit|button|image|reset|file)$/i,In=/^(?:input|select|textarea|keygen)/i;lt.fn.extend({serialize:function(){return lt.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=lt.prop(this,"elements");return e?lt.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!lt(this).is(":disabled")&&In.test(this.nodeName)&&!Rn.test(e)&&(this.checked||!tn.test(e))}).map(function(e,t){var n=lt(this).val();return null==n?null:lt.isArray(n)?lt.map(n,function(e){return{name:t.name,value:e.replace(An,"\r\n")}}):{name:t.name,value:n.replace(An,"\r\n")}}).get()}}),lt.param=function(e,n){var i,r=[],o=function(e,t){t=lt.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=lt.ajaxSettings&&lt.ajaxSettings.traditional),lt.isArray(e)||e.jquery&&!lt.isPlainObject(e))lt.each(e,function(){o(this.name,this.value)});else for(i in e)R(i,e[i],n,o);return r.join("&").replace(Tn,"+")},lt.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){lt.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),lt.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var Dn,On,Ln=lt.now(),Fn=/\?/,Nn=/#.*$/,Pn=/([?&])_=[^&]*/,Bn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Mn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,jn=/^(?:GET|HEAD)$/,zn=/^\/\//,$n=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Hn=lt.fn.load,Kn={},Un={},qn="*/".concat("*");try{On=Y.href}catch(Wn){On=G.createElement("a"),On.href="",On=On.href}Dn=$n.exec(On.toLowerCase())||[],lt.fn.load=function(e,n,i){if("string"!=typeof e&&Hn)return Hn.apply(this,arguments);var r,o,a,s=this,l=e.indexOf(" ");return l>=0&&(r=e.slice(l,e.length),e=e.slice(0,l)),lt.isFunction(n)?(i=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&lt.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(r?lt("<div>").append(lt.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,o||[e.responseText,t,e])}),this},lt.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){lt.fn[t]=function(e){return this.on(t,e)}}),lt.each(["get","post"],function(e,n){lt[n]=function(e,i,r,o){return lt.isFunction(i)&&(o=o||r,r=i,i=t),lt.ajax({url:e,type:n,dataType:o,data:i,success:r})}}),lt.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:On,type:"GET",isLocal:Mn.test(Dn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qn,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":lt.parseJSON,"text xml":lt.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?O(O(e,lt.ajaxSettings),t):O(lt.ajaxSettings,e)},ajaxPrefilter:I(Kn),ajaxTransport:I(Un),ajax:function(e,n){function i(e,n,i,r){var o,d,v,y,k,w=n;2!==_&&(_=2,l&&clearTimeout(l),u=t,s=r||"",x.readyState=e>0?4:0,i&&(y=L(p,x,i)),e>=200&&300>e||304===e?(p.ifModified&&(k=x.getResponseHeader("Last-Modified"),k&&(lt.lastModified[a]=k),k=x.getResponseHeader("etag"),k&&(lt.etag[a]=k)),204===e?(o=!0,w="nocontent"):304===e?(o=!0,w="notmodified"):(o=F(p,y),w=o.state,d=o.data,v=o.error,o=!v)):(v=w,(e||!w)&&(w="error",0>e&&(e=0))),x.status=e,x.statusText=(n||w)+"",o?g.resolveWith(h,[d,w,x]):g.rejectWith(h,[x,w,v]),x.statusCode(b),b=t,c&&m.trigger(o?"ajaxSuccess":"ajaxError",[x,p,o?d:v]),f.fireWith(h,[x,w]),c&&(m.trigger("ajaxComplete",[x,p]),--lt.active||lt.event.trigger("ajaxStop")))}"object"==typeof e&&(n=e,e=t),n=n||{};var r,o,a,s,l,c,u,d,p=lt.ajaxSetup({},n),h=p.context||p,m=p.context&&(h.nodeType||h.jquery)?lt(h):lt.event,g=lt.Deferred(),f=lt.Callbacks("once memory"),b=p.statusCode||{},v={},y={},_=0,k="canceled",x={readyState:0,getResponseHeader:function(e){var t;if(2===_){if(!d)for(d={};t=Bn.exec(s);)d[t[1].toLowerCase()]=t[2];t=d[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===_?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return _||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return _||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>_)for(t in e)b[t]=[b[t],e[t]];else x.always(e[x.status]);return this},abort:function(e){var t=e||k;return u&&u.abort(t),i(0,t),this}};if(g.promise(x).complete=f.add,x.success=x.done,x.error=x.fail,p.url=((e||p.url||On)+"").replace(Nn,"").replace(zn,Dn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=lt.trim(p.dataType||"*").toLowerCase().match(ut)||[""],null==p.crossDomain&&(r=$n.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===Dn[1]&&r[2]===Dn[2]&&(r[3]||("http:"===r[1]?80:443))==(Dn[3]||("http:"===Dn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=lt.param(p.data,p.traditional)),D(Kn,p,n,x),2===_)return x;c=p.global,c&&0===lt.active++&&lt.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!jn.test(p.type),a=p.url,p.hasContent||(p.data&&(a=p.url+=(Fn.test(a)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=Pn.test(a)?a.replace(Pn,"$1_="+Ln++):a+(Fn.test(a)?"&":"?")+"_="+Ln++)),p.ifModified&&(lt.lastModified[a]&&x.setRequestHeader("If-Modified-Since",lt.lastModified[a]),lt.etag[a]&&x.setRequestHeader("If-None-Match",lt.etag[a])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",p.contentType),x.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+qn+"; q=0.01":""):p.accepts["*"]);for(o in p.headers)x.setRequestHeader(o,p.headers[o]);if(p.beforeSend&&(p.beforeSend.call(h,x,p)===!1||2===_))return x.abort();k="abort";for(o in{success:1,error:1,complete:1})x[o](p[o]);if(u=D(Un,p,n,x)){x.readyState=1,c&&m.trigger("ajaxSend",[x,p]),p.async&&p.timeout>0&&(l=setTimeout(function(){x.abort("timeout")},p.timeout));try{_=1,u.send(v,i)}catch(w){if(!(2>_))throw w;i(-1,w)}}else i(-1,"No Transport");return x},getScript:function(e,n){return lt.get(e,t,n,"script")},getJSON:function(e,t,n){return lt.get(e,t,n,"json")}}),lt.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return lt.globalEval(e),e}}}),lt.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),lt.ajaxTransport("script",function(e){if(e.crossDomain){var n,i=G.head||lt("head")[0]||G.documentElement;return{send:function(t,r){n=G.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||r(200,"success"))},i.insertBefore(n,i.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Vn=[],Gn=/(=)\?(?=&|$)|\?\?/;lt.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Vn.pop()||lt.expando+"_"+Ln++;return this[e]=!0,e}}),lt.ajaxPrefilter("json jsonp",function(n,i,r){var o,a,s,l=n.jsonp!==!1&&(Gn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=lt.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Gn,"$1"+o):n.jsonp!==!1&&(n.url+=(Fn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||lt.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},r.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=i.jsonpCallback,Vn.push(o)),s&&lt.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Yn,Xn,Jn=0,Zn=e.ActiveXObject&&function(){var e;for(e in Yn)Yn[e](t,!0)};lt.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&N()||P()}:N,Xn=lt.ajaxSettings.xhr(),lt.support.cors=!!Xn&&"withCredentials"in Xn,Xn=lt.support.ajax=!!Xn,Xn&&lt.ajaxTransport(function(n){if(!n.crossDomain||lt.support.cors){var i;return{send:function(r,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest");try{for(s in r)l.setRequestHeader(s,r[s])}catch(c){}l.send(n.hasContent&&n.data||null),i=function(e,r){var s,c,u,d;try{if(i&&(r||4===l.readyState))if(i=t,a&&(l.onreadystatechange=lt.noop,Zn&&delete Yn[a]),r)4!==l.readyState&&l.abort();else{d={},s=l.status,c=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(d.text=l.responseText);try{u=l.statusText}catch(p){u=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=d.text?200:404}}catch(h){r||o(-1,h)}d&&o(s,u,d,c)},n.async?4===l.readyState?setTimeout(i):(a=++Jn,Zn&&(Yn||(Yn={},lt(e).unload(Zn)),Yn[a]=i),l.onreadystatechange=i):i()},abort:function(){i&&i(t,!0)}}}});var Qn,ei,ti=/^(?:toggle|show|hide)$/,ni=RegExp("^(?:([+-])=|)("+ct+")([a-z%]*)$","i"),ii=/queueHooks$/,ri=[$],oi={"*":[function(e,t){var n,i,r=this.createTween(e,t),o=ni.exec(t),a=r.cur(),s=+a||0,l=1,c=20;if(o){if(n=+o[2],i=o[3]||(lt.cssNumber[e]?"":"px"),"px"!==i&&s){s=lt.css(r.elem,e,!0)||n||1;do l=l||".5",s/=l,lt.style(r.elem,e,s+i);while(l!==(l=r.cur()/a)&&1!==l&&--c)}r.unit=i,r.start=s,r.end=o[1]?s+(o[1]+1)*n:n}return r}]};lt.Animation=lt.extend(j,{tweener:function(e,t){lt.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,i=0,r=e.length;r>i;i++)n=e[i],oi[n]=oi[n]||[],oi[n].unshift(t)},prefilter:function(e,t){t?ri.unshift(e):ri.push(e)}}),lt.Tween=H,H.prototype={constructor:H,init:function(e,t,n,i,r,o){this.elem=e,this.prop=n,this.easing=r||"swing",this.options=t,this.start=this.now=this.cur(),this.end=i,this.unit=o||(lt.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.pos=t=this.options.duration?lt.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):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=lt.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){lt.fx.step[e.prop]?lt.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[lt.cssProps[e.prop]]||lt.cssHooks[e.prop])?lt.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},lt.each(["toggle","show","hide"],function(e,t){var n=lt.fn[t];lt.fn[t]=function(e,i,r){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(K(t,!0),e,i,r)}}),lt.fn.extend({fadeTo:function(e,t,n,i){return this.filter(x).css("opacity",0).show().end().animate({opacity:t},e,n,i)},animate:function(e,t,n,i){var r=lt.isEmptyObject(e),o=lt.speed(t,n,i),a=function(){var t=j(this,lt.extend({},e),o);a.finish=function(){t.stop(!0)},(r||lt._data(this,"finish"))&&t.stop(!0)};return a.finish=a,r||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,i){var r=function(e){var t=e.stop;delete e.stop,t(i)};return"string"!=typeof e&&(i=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=lt.timers,a=lt._data(this);if(n)a[n]&&a[n].stop&&r(a[n]);else for(n in a)a[n]&&a[n].stop&&ii.test(n)&&r(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(i),t=!1,o.splice(n,1));(t||!i)&&lt.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=lt._data(this),i=n[e+"queue"],r=n[e+"queueHooks"],o=lt.timers,a=i?i.length:0;for(n.finish=!0,lt.queue(this,e,[]),r&&r.cur&&r.cur.finish&&r.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++)i[t]&&i[t].finish&&i[t].finish.call(this);delete n.finish})}}),lt.each({slideDown:K("show"),slideUp:K("hide"),slideToggle:K("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){lt.fn[e]=function(e,n,i){return this.animate(t,e,n,i)}}),lt.speed=function(e,t,n){var i=e&&"object"==typeof e?lt.extend({},e):{complete:n||!n&&t||lt.isFunction(e)&&e,duration:e,easing:n&&t||t&&!lt.isFunction(t)&&t};return i.duration=lt.fx.off?0:"number"==typeof i.duration?i.duration:i.duration in lt.fx.speeds?lt.fx.speeds[i.duration]:lt.fx.speeds._default,(null==i.queue||i.queue===!0)&&(i.queue="fx"),i.old=i.complete,i.complete=function(){lt.isFunction(i.old)&&i.old.call(this),i.queue&&lt.dequeue(this,i.queue)},i},lt.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},lt.timers=[],lt.fx=H.prototype.init,lt.fx.tick=function(){var e,n=lt.timers,i=0;for(Qn=lt.now();n.length>i;i++)e=n[i],e()||n[i]!==e||n.splice(i--,1);n.length||lt.fx.stop(),Qn=t},lt.fx.timer=function(e){e()&&lt.timers.push(e)&&lt.fx.start()},lt.fx.interval=13,lt.fx.start=function(){ei||(ei=setInterval(lt.fx.tick,lt.fx.interval))},lt.fx.stop=function(){clearInterval(ei),ei=null},lt.fx.speeds={slow:600,fast:200,_default:400},lt.fx.step={},lt.expr&&lt.expr.filters&&(lt.expr.filters.animated=function(e){return lt.grep(lt.timers,function(t){return e===t.elem}).length}),lt.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){lt.offset.setOffset(this,e,t)});var n,i,r={top:0,left:0},o=this[0],a=o&&o.ownerDocument;if(a)return n=a.documentElement,lt.contains(n,o)?(typeof o.getBoundingClientRect!==V&&(r=o.getBoundingClientRect()),i=U(a),{top:r.top+(i.pageYOffset||n.scrollTop)-(n.clientTop||0),left:r.left+(i.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):r},lt.offset={setOffset:function(e,t,n){var i=lt.css(e,"position");"static"===i&&(e.style.position="relative");var r,o,a=lt(e),s=a.offset(),l=lt.css(e,"top"),c=lt.css(e,"left"),u=("absolute"===i||"fixed"===i)&&lt.inArray("auto",[l,c])>-1,d={},p={};u?(p=a.position(),r=p.top,o=p.left):(r=parseFloat(l)||0,o=parseFloat(c)||0),lt.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(d.top=t.top-s.top+r),null!=t.left&&(d.left=t.left-s.left+o),"using"in t?t.using.call(e,d):a.css(d)}},lt.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},i=this[0];return"fixed"===lt.css(i,"position")?t=i.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),lt.nodeName(e[0],"html")||(n=e.offset()),n.top+=lt.css(e[0],"borderTopWidth",!0),n.left+=lt.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-lt.css(i,"marginTop",!0),left:t.left-n.left-lt.css(i,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||G.documentElement;e&&!lt.nodeName(e,"html")&&"static"===lt.css(e,"position");)e=e.offsetParent;return e||G.documentElement})}}),lt.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var i=/Y/.test(n);lt.fn[e]=function(r){return lt.access(this,function(e,r,o){var a=U(e);return o===t?a?n in a?a[n]:a.document.documentElement[r]:e[r]:(a?a.scrollTo(i?lt(a).scrollLeft():o,i?o:lt(a).scrollTop()):e[r]=o,t)},e,r,arguments.length,null)}}),lt.each({Height:"height",Width:"width"},function(e,n){lt.each({padding:"inner"+e,content:n,"":"outer"+e},function(i,r){lt.fn[r]=function(r,o){var a=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||o===!0?"margin":"border");return lt.access(this,function(n,i,r){var o;return lt.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])):r===t?lt.css(n,i,s):lt.style(n,i,r,s)},n,a?r:t,a,null)}})}),e.jQuery=e.$=lt,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return lt})})(window);
app/assets/plugins/x-editable/dist/jqueryui-editable/js/jqueryui-editable.js
henrino3/control-client
/*! X-editable - v1.5.1 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); //prerender: get input.$input this.input.prerender(); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value; this.input.value2input(value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = (''+msg).split('\n'); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); //get new value from input var newValue = this.input.input2value(); //validation: if validate returns string or truthy value - means error //if returns object like {newValue: '...'} => submitted value is reassigned to it var error = this.validate(newValue); if ($.type(error) === 'object' && error.newValue !== undefined) { newValue = error.newValue; this.input.value2input(newValue); if(typeof error.msg === 'string') { this.error(error.msg); this.showForm(); return; } } else if (error) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Value that will be displayed in input if original field value is empty (`null|undefined|''`). @property defaultValue @type string|object @default null @since 1.4.6 **/ defaultValue: null, /** Strategy for sending data on server. Can be `auto|always|never`. When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. Since 1.5.1 you can modify submitted value by returning object from `validate`: `{newValue: '...'}` or `{newValue: '...', msg: '...'}` @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; //engine $.fn.editableform.engine = 'jquery'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } if (typeof(valueProp) !== "function") { var idKey = valueProp || 'value'; valueProp = function (e) { return e[idKey]; }; } var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) { result.push(o); } } else { var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o; if(value == itemValue) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //method to call container on element containerDataName: null, //object name in element's .data() innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element defaults: {}, //container itself defaults init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks if(this.input.type === 'textarea') { this.$element.addClass('editable-pre-wrapped'); } //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty //for some inputs we need more smart check //e.g. wysihtml5 may have <br>, <p></p>, <img> if(typeof(this.input.isEmpty) === 'function') { this.isEmpty = this.input.isEmpty(this.$element); } else { this.isEmpty = $.trim(this.$element.html()) === ''; } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ if(bgColor === 'transparent') { bgColor = ''; } $e.css('background-color', bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 10); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case `url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'); // validation ok if($.isEmptyObject(errors)) { var ajaxOptions = {}; // for single element use url, success etc from options if($elems.length === 1) { var editable = $elems.data('editable'); //standard params var params = { name: editable.options.name || '', value: editable.input.value2submit(editable.value), pk: (typeof editable.options.pk === 'function') ? editable.options.pk.call(editable.options.scope) : editable.options.pk }; //additional params if(typeof editable.options.params === 'function') { params = editable.options.params.call(editable.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true); $.extend(params, editable.options.params); } ajaxOptions = { url: editable.options.url, data: params, type: 'POST' }; // use success / error from options config.success = config.success || editable.options.success; config.error = config.error || editable.options.error; // multiple elements } else { var values = this.editable('getValue'); ajaxOptions = { url: config.url, data: values, type: 'POST' }; } // ajax success callabck (response 200 OK) ajaxOptions.success = typeof config.success === 'function' ? function(response) { config.success.call($elems, response, config); } : $.noop; // ajax error callabck ajaxOptions.error = typeof config.error === 'function' ? function() { config.error.apply($elems, arguments); } : $.noop; // extend ajaxOptions if(config.ajaxOptions) { $.extend(ajaxOptions, config.ajaxOptions); } // extra data if(config.data) { $.extend(ajaxOptions.data, config.data); } // perform ajax request $.ajax(ajaxOptions); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; //for delegated targets do not store `editable` object for element //it's allows several different selectors. //see: https://github.com/vitalets/x-editable/issues/312 if(options && options.selector) { data = new Editable(this, options); return; } if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element)[this.options.escape ? 'text' : 'html']($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default null **/ inputclass: null, /** If `true` - html will be escaped in content of element via $.text() method. If `false` - html will not be escaped, $.html() used. When you use own `display` function, this option obviosly has no effect. @property escape @type boolean @since 1.5.0 @default true **/ escape: true, //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //ajaxOptions for source. Can be overwritten bt options.sourceOptions var ajaxOptions = $.extend({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }, this.options.sourceOptions); //loading sourceData from server $.ajax(ajaxOptions); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true, /** Additional ajax options to be used in $.ajax() when loading list from server. Useful to send extra parameters (`data` key) or change request method (`type` key). @property sourceOptions @type object|function @default null @since 1.5.0 **/ sourceOptions: null }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, //using `white-space: pre-wrap` solves \n <--> BR conversion very elegant! /* value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, */ activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { var attr; if($.isArray(data)) { for(var i=0; i<data.length; i++) { attr = {}; if(data[i].children) { attr.label = data[i].text; $el.append(fillItems($('<optgroup>', attr), data[i].children)); } else { attr.value = data[i].value; if(data[i].disabled) { attr.disabled = true; } $el.append($('<option>', attr).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } //$(element).text(text); $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData), escape = this.options.escape; if(checked.length) { $.each(checked, function(i, v) { var text = escape ? $.fn.editableutils.escape(v.text) : v.text; html.push(text); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range * time Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /* Time */ (function ($) { "use strict"; var Time = function (options) { this.init('time', options, Time.defaults); }; //inherit from abstract, as inheritance from text gives selection error. $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput); $.extend(Time.prototype, { render: function() { this.setClass(); } }); Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<input type="time">' }); $.fn.editabletypes.time = Time; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ //local source $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); //remote source (simple) $('#country').editable({ source: '/getCountries', select2: { placeholder: 'Select Country', minimumInputLength: 1 } }); //remote source (advanced) $('#country').editable({ select2: { placeholder: 'Select Country', allowClear: true, minimumInputLength: 3, id: function (item) { return item.CountryId; }, ajax: { url: '/getCountries', dataType: 'json', data: function (term, page) { return { query: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (item) { return item.CountryName; }, formatSelection: function (item) { return item.CountryName; }, initSelection: function (element, callback) { return $.get('/getCountryById', { query: element.val() }, function (data) { callback(data); }); } } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); //store function returning ID of item //should be here as used inautotext for local source this.idFunc = this.options.select2.id; if (typeof(this.idFunc) !== "function") { var idKey = this.idFunc || 'id'; this.idFunc = function (e) { return e[idKey]; }; } //store function that renders text in select2 this.formatSelection = this.options.select2.formatSelection; if (typeof(this.formatSelection) !== "function") { this.formatSelection = function (e) { return e.text; }; } }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //can not apply select2 here as it calls initSelection //over input that does not have correct value yet. //apply select2 only in value2input //this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data, that = this; if(this.options.select2.tags) { //in tags mode just assign value data = value; //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc); } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); } else { //can not get list of possible values //(e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? that.formatSelection(v) : v); }); } else if(data) { text = that.formatSelection(data); } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { // if value array => join it anyway if($.isArray(value)) { value = value.join(this.getSeparator()); } //for remote source just set value, text is updated by initSelection if(!this.$input.data('select2')) { this.$input.val(value); this.$input.select2(this.options.select2); } else { //second argument needed to separate initial change from user's click (for autosubmit) this.$input.val(value).trigger('change', true); //Uncaught Error: cannot call val() if initSelection() is not defined //this.$input.select2('val', value); } // if defined remote source AND no multiple mode AND no user's initSelection provided --> // we should somehow get text for provided id. // The solution is to use element's text as text for that id (exclude empty) if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) { // customId and customText are methods to extract `id` and `text` from data object // we can use this workaround only if user did not define these methods // otherwise we cant construct data object var customId = this.options.select2.id, customText = this.options.select2.formatSelection; if(!customId && !customText) { var $el = $(this.options.scope); if (!$el.data('editable').isEmpty) { var data = {id: value, text: $el.text()}; this.$input.select2('data', data); } } } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.getSeparator(); var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, getSeparator: function() { return this.options.select2.separator || $.fn.select2.defaults.separator; }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; }, destroy: function() { if(this.$input.data('select2')) { this.$input.select2('destroy'); } } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array|string|function @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.5 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(e) { this.$element.val(this.getValue()).change(); // update days count if month or year changes if (this.options.smartDays) { if ($(e.target).is('.month') || $(e.target).is('.year')) { this.fillCombo('day'); } } }, this)); this.$widget.find('select').css('width', 'auto'); // hide original input and insert widget this.$element.hide().after(this.$widget); // set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { for (var k in this.map) { var $c = this.$widget.find('.'+k); // set properties like this.$day, this.$month etc. this['$'+k] = $c.length ? $c : null; // fill with items this.fillCombo(k); } }, /* Fill combo with items */ fillCombo: function(k) { var $combo = this['$'+k]; if (!$combo) { return; } // define method name to fill items, e.g `fillDays` var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); var items = this[f](); var value = $combo.val(); $combo.empty(); for(var i=0; i<items.length; i++) { $combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } $combo.val(value); }, /* Initialize items of combos. Handles `firstItem` option */ fillCommon: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* fill day */ fillDay: function() { var items = this.fillCommon('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1, daysCount = 31; // detect days count (depends on month and year) // originally https://github.com/vitalets/combodate/pull/7 if (this.options.smartDays && this.$month && this.$year) { var month = parseInt(this.$month.val(), 10); var year = parseInt(this.$year.val(), 10); if (!isNaN(month) && !isNaN(year)) { daysCount = moment([year, month]).daysInMonth(); } } for (i = 1; i <= daysCount; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.fillCommon('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.fillCommon('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.fillCommon('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.fillCommon('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.fillCommon('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); // update days count if (this.options.smartDays) { this.fillCombo('day'); } this.$element.val(dt.format(this.options.format)).change(); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true, // whether to round minutes and seconds if step > 1 smartDays: false // whether days in combo depend on selected month: 31, 30, 28 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); if($.fn.editableform.engine === 'bs3') { this.$input.siblings().find('select').addClass('form-control'); } if(this.options.inputclass) { this.$input.siblings().find('select').addClass(this.options.inputclass); } //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on jQuery UI */ (function ($) { "use strict"; $.extend($.fn.editableform.Constructor.prototype, { initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } this.$form.find('.editable-submit').button({ icons: { primary: "ui-icon-check" }, text: false }).removeAttr('title'); this.$form.find('.editable-cancel').button({ icons: { primary: "ui-icon-closethick" }, text: false }).removeAttr('title'); } }); //error classes $.fn.editableform.errorGroupClass = null; $.fn.editableform.errorBlockClass = 'ui-state-error'; //engine $.fn.editableform.engine = 'jquery-ui'; }(window.jQuery)); /** * Editable jQuery UI Tooltip * --------------------- * requires jquery ui 1.9.x */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'tooltip', //jQuery method, aplying the widget //object name in element's .data() containerDataName: 'ui-tooltip', innerCss: '.ui-tooltip-content', defaults: $.ui.tooltip.prototype.options, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; //check that jQueryUI build contains tooltip widget if(!$.ui[this.containerName]) { $.error('Please use jQueryUI with "tooltip" widget! http://jqueryui.com/download'); return; } //defaults for tooltip for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, initContainer: function(){ this.handlePlacement(); $.extend(this.containerOptions, { items: '*', content: ' ', track: false, open: $.proxy(function() { //disable events hiding tooltip by default this.container()._on(this.container().element, { mouseleave: function(e){ e.stopImmediatePropagation(); }, focusout: function(e){ e.stopImmediatePropagation(); } }); }, this) }); this.call(this.containerOptions); //disable standart triggering tooltip events this.container()._off(this.container().element, 'mouseover focusin'); }, tip: function() { return this.container() ? this.container()._find(this.container().element) : null; }, innerShow: function() { this.call('open'); var label = this.options.title || this.$element.data( "ui-tooltip-title") || this.$element.data( "originalTitle"); this.tip().find(this.innerCss).empty().append($('<label>').text(label)); }, innerHide: function() { this.call('close'); }, innerDestroy: function() { /* tooltip destroys itself on hide */ }, setPosition: function() { this.tip().position( $.extend({ of: this.$element }, this.containerOptions.position ) ); }, handlePlacement: function() { var pos; switch(this.options.placement) { case 'top': pos = { my: "center bottom-5", at: "center top", collision: 'flipfit' }; break; case 'right': pos = { my: "left+5 center", at: "right center", collision: 'flipfit' }; break; case 'bottom': pos = { my: "center top+5", at: "center bottom", collision: 'flipfit' }; break; case 'left': pos = { my: "right-5 center", at: "left center", collision: 'flipfit' }; break; } this.containerOptions.position = pos; } }); }(window.jQuery)); /** jQuery UI Datepicker. Description and examples: http://jqueryui.com/datepicker. This input is also accessible as **date** type. Do not use it together with __bootstrap-datepicker__ as both apply <code>$().datepicker()</code> method. For **i18n** you should include js file from here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n. @class dateui @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { firstDay: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateUI = function (options) { this.init('dateui', options, DateUI.defaults); this.initPicker(options, DateUI.defaults); }; $.fn.editableutils.inherit(DateUI, $.fn.editabletypes.abstractinput); $.extend(DateUI.prototype, { initPicker: function(options, defaults) { //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //correct formats: replace yyyy with yy (for compatibility with bootstrap datepicker) this.options.viewformat = this.options.viewformat.replace('yyyy', 'yy'); this.options.format = this.options.format.replace('yyyy', 'yy'); //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { dateFormat: this.options.viewformat }); }, render: function () { this.$input.datepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = $.datepicker.formatDate(this.options.viewformat, value); DateUI.superclass.value2html.call(this, text, element); }, html2value: function(html) { if(typeof html !== 'string') { return html; } //if string does not match format, UI datepicker throws exception var d; try { d = $.datepicker.parseDate(this.options.viewformat, html); } catch(e) {} return d; }, value2str: function(value) { return $.datepicker.formatDate(this.options.format, value); }, str2value: function(str) { if(typeof str !== 'string') { return str; } //if string does not match format, UI datepicker throws exception var d; try { d = $.datepicker.parseDate(this.options.format, str); } catch(e) {} return d; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.datepicker('setDate', value); }, input2value: function() { return this.$input.datepicker('getDate'); }, activate: function() { }, clear: function() { this.$input.datepicker('setDate', null); // submit automatically whe that are no buttons if(this.isAutosubmit) { this.submit(); } }, autosubmit: function() { this.isAutosubmit = true; this.$input.on('mouseup', 'table.ui-datepicker-calendar a.ui-state-default', $.proxy(this.submit, this)); }, submit: function() { var $form = this.$input.closest('form'); setTimeout(function() { $form.submit(); }, 200); } }); DateUI.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Full list of tokens: http://docs.jquery.com/UI/Datepicker/formatDate @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://api.jqueryui.com/datepicker @property datepicker @type object @default { firstDay: 0, changeYear: true, changeMonth: true } **/ datepicker: { firstDay: 0, changeYear: true, changeMonth: true, showOtherMonths: true }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.dateui = DateUI; }(window.jQuery)); /** jQuery UI datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class dateuifield @extends dateui @since 1.4.0 **/ (function ($) { "use strict"; var DateUIField = function (options) { this.init('dateuifield', options, DateUIField.defaults); this.initPicker(options, DateUIField.defaults); }; $.fn.editableutils.inherit(DateUIField, $.fn.editabletypes.dateui); $.extend(DateUIField.prototype, { render: function () { // this.$input = this.$tpl.find('input'); this.$input.datepicker(this.options.datepicker); $.fn.editabletypes.text.prototype.renderClear.call(this); }, value2input: function(value) { this.$input.val($.datepicker.formatDate(this.options.viewformat, value)); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, toggleClear: function() { $.fn.editabletypes.text.prototype.toggleClear.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateUIField.defaults = $.extend({}, $.fn.editabletypes.dateui.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text"/>', /** @property inputclass @default null **/ inputclass: null, /* datepicker config */ datepicker: { showOn: "button", buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif", buttonImageOnly: true, firstDay: 0, changeYear: true, changeMonth: true, showOtherMonths: true }, /* disable clear link */ clear: false }); $.fn.editabletypes.dateuifield = DateUIField; }(window.jQuery));
examples/react-native/components/Error.js
aksonov/react-native-router-flux
import React from 'react'; import {View, Text, StyleSheet, Animated, Dimensions} from 'react-native'; import Button from 'react-native-button'; import {Actions} from 'react-native-router-flux'; const {height: deviceHeight} = Dimensions.get('window'); const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, backgroundColor: 'transparent', justifyContent: 'center', alignItems: 'center', }, }); export default class extends React.Component { constructor(props) { super(props); this.state = { offset: new Animated.Value(-deviceHeight), }; } componentDidMount() { Animated.timing(this.state.offset, { duration: 150, toValue: 0, }).start(); } closeModal() { Animated.timing(this.state.offset, { duration: 150, toValue: -deviceHeight, }).start(Actions.pop); } render() { return ( <Animated.View style={[ styles.container, {backgroundColor: 'rgba(52,52,52,0.5)'}, {transform: [{translateY: this.state.offset}]}, ]}> <View style={{ width: 250, height: 250, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', }}> <Text>{this.props.data}</Text> <Button onPress={this.closeModal.bind(this)}>Close</Button> </View> </Animated.View> ); } }
framework/scripts/syntaxHTML/static/libs/jquery.js
Chuban/moose
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license*/ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;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 x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.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(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.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?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},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||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.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||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},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:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.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 d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},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}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(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]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?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},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.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},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-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 S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(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?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.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+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===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]||at.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]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.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,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!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[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[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]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[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[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(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:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("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===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.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!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.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:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(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 xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.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?x.extend(e,r):r}},i={};return r.pipe=r.then,x.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=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.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],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.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;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[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%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.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&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),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 x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.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=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.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,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._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(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t: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,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.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 t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={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}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[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),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=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));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,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]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),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=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),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=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=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 x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):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,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.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))},x.Event=function(e,n){return this instanceof x.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&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.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()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._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 x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.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 x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.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,x(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(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.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?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(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(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.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,Ct=/^(?:checkbox|radio)$/i,Nt=/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:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.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 x.clone(this,e,t)})},html:function(e){return x.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)||!x.support.htmlSerialize&&mt.test(e)||!x.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&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._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++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.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)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(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||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.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),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(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,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(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 x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});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("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","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"===x.css(e,"display")||!x.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]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.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}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.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,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],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||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});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+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.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=x.support.boxSizing&&"border-box"===x.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&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<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=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.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,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.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=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.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)||(x.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;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.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(x.isArray(t))x.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"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},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)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.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(T)||[];if(x.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(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.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",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.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,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){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===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.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=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],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=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.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&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.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)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.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 Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=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 l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.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,Fn.push(o)),s&&x.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){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.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,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.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,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.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||(x.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?x.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=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.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)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.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=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._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=x.timers,a=x._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)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),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}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.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,x.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},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.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?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.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?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
src/components/Table/SkeletonTable.js
Bandwidth/shared-components
import React from 'react'; import styled from 'styled-components'; import Skeleton from 'skeletons/Skeleton'; import createArray from 'extensions/createArray'; const SkeletonTableContainer = styled.div` display: flex; flex-direction: column; & > * + * { margin-top: ${({ marginBetween }) => marginBetween}; } `; const SkeletonTableHeader = styled(Skeleton.Animated)` background: var(--skeleton-colors-dark); border-radius: 0.5em; `; const SkeletonTableRow = styled.div` display: flex; flex-direction: row; & > * + * { margin-left: ${({ marginBetween }) => marginBetween}; } & > * { flex-grow: 1; } `; const SkeletonTableCell = styled(Skeleton.Animated)` border-radius: 0.5em; animation-duration: var(--skeleton-pulse-fast); `; const SkeletonTable = ({ disableAnimation, width, rowHeight = '40px', columns = 3, rows = 4, marginBetween = '2px', }) => ( <SkeletonTableContainer disableAnimation={disableAnimation} width={width} marginBetween={marginBetween} > <SkeletonTableHeader disableAnimation={disableAnimation} height={rowHeight} /> {createArray(rows).map(rowIdx => ( <SkeletonTableRow marginBetween={marginBetween} key={rowIdx}> {createArray(columns).map(colIdx => ( <SkeletonTableCell pctOffset={colIdx / columns} key={colIdx} disableAnimation={disableAnimation} height={rowHeight} /> ))} </SkeletonTableRow> ))} </SkeletonTableContainer> ); SkeletonTable.Small = props => <SkeletonTable rowHeight="23px" {...props} />; /** * @component */ export default SkeletonTable;
src/components/settings-dialog/src/index.js
unindented/puzzle-chrome
import React, {Component, PropTypes} from 'react' import {Button, Dialog, DialogTitle, DialogContent, DialogActions, Slider} from 'react-mdl' import {autobind} from 'core-decorators' import dialogPolyfill from 'dialog-polyfill' import {t} from 'utils/i18n' import {minRows, maxRows, defaultRows, minCols, maxCols, defaultCols} from 'utils/settings' import _styles from './index.scss' export default class SettingsDialog extends Component { static propTypes = { open: PropTypes.bool, url: PropTypes.string.isRequired, rows: PropTypes.number, cols: PropTypes.number, onChangeRows: PropTypes.func, onChangeCols: PropTypes.func } state = {} @autobind handleDialogRef (dialog) { this._dialog = dialog } @autobind handleChangeRows (evt) { const {onChangeRows} = this.props onChangeRows && onChangeRows(parseInt(evt.target.value, 10)) } @autobind handleChangeCols (evt) { const {onChangeCols} = this.props onChangeCols && onChangeCols(parseInt(evt.target.value, 10)) } hasDialog () { const dialog = this._dialog && this._dialog.dialogRef return (dialog instanceof Node) && document.contains(dialog) } componentDidMount () { dialogPolyfill.registerDialog(this._dialog.dialogRef) } render () { const {open, url, rows: propsRows, cols: propsCols} = this.props const {rows: stateRows, cols: stateCols} = this.state const currentRows = stateRows || propsRows || defaultRows const currentCols = stateCols || propsCols || defaultCols const isOpen = this.hasDialog() && !!open return ( <Dialog className='app-settings-dialog' open={isOpen} ref={this.handleDialogRef} > <form method='get'> <DialogTitle> {t('msg_settings_dialog_title', currentRows, currentCols)} </DialogTitle> <DialogContent> <input type='hidden' name='url' value={btoa(url)} /> <div className='app-settings-dialog__field'> <label htmlFor='app-settings-dialog-rows'> {t('msg_settings_dialog_rows_label')}: </label> <Slider id='app-settings-dialog-rows' name='rows' min={minRows} max={maxRows} value={currentRows} onChange={this.handleChangeRows} /> </div> <div className='app-settings-dialog__field'> <label htmlFor='app-settings-dialog-rows'> {t('msg_settings_dialog_cols_label')}: </label> <Slider id='app-settings-dialog-cols' name='cols' min={minCols} max={maxCols} value={currentCols} onChange={this.handleChangeCols} /> </div> </DialogContent> <DialogActions> <Button type='submit' colored raised ripple> {t('msg_settings_dialog_submit_button')} </Button> </DialogActions> </form> </Dialog> ) } }
src/App.js
domark0721/react-redux-hot-boilerplate
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1>Hello, world.</h1> ); } }
test/Scrollbars/dragThumb.js
zxlin/react-custom-scrollbars
import { Scrollbars } from 'react-custom-scrollbars'; import { render, unmountComponentAtNode } from 'react-dom'; import React from 'react'; import simulant from 'simulant'; export default function createTests(scrollbarWidth) { // Not for mobile environment if (!scrollbarWidth) return; let node; beforeEach(() => { node = document.createElement('div'); document.body.appendChild(node); }); afterEach(() => { unmountComponentAtNode(node); document.body.removeChild(node); }); describe('when dragging horizontal thumb', () => { it('should scroll to the respective position', done => { render(( <Scrollbars style={{ width: 100, height: 100 }}> <div style={{ width: 200, height: 200 }}/> </Scrollbars> ), node, function callback() { setTimeout(() => { const { view, thumbHorizontal: thumb } = this; const { left } = thumb.getBoundingClientRect(); simulant.fire(thumb, 'mousedown', { target: thumb, clientX: left + 1 }); simulant.fire(document, 'mousemove', { clientX: left + 100 }); simulant.fire(document, 'mouseup'); expect(view.scrollLeft).toEqual(100); done(); }, 100); }); }); it('should disable selection', done => { render(( <Scrollbars style={{ width: 100, height: 100 }}> <div style={{ width: 200, height: 200 }}/> </Scrollbars> ), node, function callback() { setTimeout(() => { const { thumbHorizontal: thumb } = this; const { left } = thumb.getBoundingClientRect(); simulant.fire(thumb, 'mousedown', { target: thumb, clientX: left + 1 }); expect(document.body.style.webkitUserSelect).toEqual('none'); simulant.fire(document, 'mouseup'); expect(document.body.style.webkitUserSelect).toEqual(''); done(); }, 100); }); }); }); describe('when dragging vertical thumb', () => { it('should scroll to the respective position', done => { render(( <Scrollbars style={{ width: 100, height: 100 }}> <div style={{ width: 200, height: 200 }}/> </Scrollbars> ), node, function callback() { setTimeout(() => { const { view, thumbVertical: thumb } = this; const { top } = thumb.getBoundingClientRect(); simulant.fire(thumb, 'mousedown', { target: thumb, clientY: top + 1 }); simulant.fire(document, 'mousemove', { clientY: top + 100 }); simulant.fire(document, 'mouseup'); expect(view.scrollTop).toEqual(100); done(); }, 100); }); }); it('should disable selection', done => { render(( <Scrollbars style={{ width: 100, height: 100 }}> <div style={{ width: 200, height: 200 }}/> </Scrollbars> ), node, function callback() { setTimeout(() => { const { thumbVertical: thumb } = this; const { top } = thumb.getBoundingClientRect(); simulant.fire(thumb, 'mousedown', { target: thumb, clientY: top + 1 }); expect(document.body.style.webkitUserSelect).toEqual('none'); simulant.fire(document, 'mouseup'); expect(document.body.style.webkitUserSelect).toEqual(''); done(); }, 100); }); }); }); }
src/svg-icons/image/panorama-vertical.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePanoramaVertical = (props) => ( <SvgIcon {...props}> <path d="M19.94 21.12c-1.1-2.94-1.64-6.03-1.64-9.12 0-3.09.55-6.18 1.64-9.12.04-.11.06-.22.06-.31 0-.34-.23-.57-.63-.57H4.63c-.4 0-.63.23-.63.57 0 .1.02.2.06.31C5.16 5.82 5.71 8.91 5.71 12c0 3.09-.55 6.18-1.64 9.12-.05.11-.07.22-.07.31 0 .33.23.57.63.57h14.75c.39 0 .63-.24.63-.57-.01-.1-.03-.2-.07-.31zM6.54 20c.77-2.6 1.16-5.28 1.16-8 0-2.72-.39-5.4-1.16-8h10.91c-.77 2.6-1.16 5.28-1.16 8 0 2.72.39 5.4 1.16 8H6.54z"/> </SvgIcon> ); ImagePanoramaVertical = pure(ImagePanoramaVertical); ImagePanoramaVertical.displayName = 'ImagePanoramaVertical'; ImagePanoramaVertical.muiName = 'SvgIcon'; export default ImagePanoramaVertical;
app/javascript/mastodon/components/dropdown_menu.js
im-in-space/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from './icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { supportsPassiveEvents } from 'detect-passive-events'; import classNames from 'classnames'; import { CircularProgress } from 'mastodon/components/loading_indicator'; const listenerOptions = supportsPassiveEvents ? { passive: true } : false; let id = 0; class DropdownMenu extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { items: PropTypes.oneOfType([PropTypes.array, ImmutablePropTypes.list]).isRequired, loading: PropTypes.bool, scrollable: PropTypes.bool, onClose: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, openedViaKeyboard: PropTypes.bool, renderItem: PropTypes.func, renderHeader: PropTypes.func, onItemClick: PropTypes.func.isRequired, }; static defaultProps = { style: {}, placement: 'bottom', }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('keydown', this.handleKeyDown, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem && this.props.openedViaKeyboard) { this.focusedItem.focus({ preventScroll: true }); } this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('keydown', this.handleKeyDown, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } handleKeyDown = e => { const items = Array.from(this.node.querySelectorAll('a, button')); const index = items.indexOf(document.activeElement); let element = null; switch(e.key) { case 'ArrowDown': element = items[index+1] || items[0]; break; case 'ArrowUp': element = items[index-1] || items[items.length-1]; break; case 'Tab': if (e.shiftKey) { element = items[index-1] || items[items.length-1]; } else { element = items[index+1] || items[0]; } break; case 'Home': element = items[0]; break; case 'End': element = items[items.length-1]; break; case 'Escape': this.props.onClose(); break; } if (element) { element.focus(); e.preventDefault(); e.stopPropagation(); } } handleItemKeyPress = e => { if (e.key === 'Enter' || e.key === ' ') { this.handleClick(e); } } handleClick = e => { const { onItemClick } = this.props; onItemClick(e); } renderItem = (option, i) => { if (option === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { text, href = '#', target = '_blank', method } = option; return ( <li className='dropdown-menu__item' key={`${text}-${i}`}> <a href={href} target={target} data-method={method} rel='noopener noreferrer' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyPress={this.handleItemKeyPress} data-index={i}> {text} </a> </li> ); } render () { const { items, style, placement, arrowOffsetLeft, arrowOffsetTop, scrollable, renderHeader, loading } = this.props; const { mounted } = this.state; let renderItem = this.props.renderItem || this.renderItem; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}> <div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} /> <div className={classNames('dropdown-menu__container', { 'dropdown-menu__container--loading': loading })}> {loading && ( <CircularProgress size={30} strokeWidth={3.5} /> )} {!loading && renderHeader && ( <div className='dropdown-menu__container__header'> {renderHeader(items)} </div> )} {!loading && ( <ul className={classNames('dropdown-menu__container__list', { 'dropdown-menu__container__list--scrollable': scrollable })}> {items.map((option, i) => renderItem(option, i, { onClick: this.handleClick, onKeyPress: this.handleItemKeyPress }))} </ul> )} </div> </div> )} </Motion> ); } } export default class Dropdown extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { children: PropTypes.node, icon: PropTypes.string, items: PropTypes.oneOfType([PropTypes.array, ImmutablePropTypes.list]).isRequired, loading: PropTypes.bool, size: PropTypes.number, title: PropTypes.string, disabled: PropTypes.bool, scrollable: PropTypes.bool, status: ImmutablePropTypes.map, isUserTouching: PropTypes.func, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, dropdownPlacement: PropTypes.string, openDropdownId: PropTypes.number, openedViaKeyboard: PropTypes.bool, renderItem: PropTypes.func, renderHeader: PropTypes.func, onItemClick: PropTypes.func, }; static defaultProps = { title: 'Menu', }; state = { id: id++, }; handleClick = ({ target, type }) => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } else { const { top } = target.getBoundingClientRect(); const placement = top * 2 < innerHeight ? 'bottom' : 'top'; this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click'); } } handleClose = () => { if (this.activeElement) { this.activeElement.focus({ preventScroll: true }); this.activeElement = null; } this.props.onClose(this.state.id); } handleMouseDown = () => { if (!this.state.open) { this.activeElement = document.activeElement; } } handleButtonKeyDown = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleMouseDown(); break; } } handleKeyPress = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleClick(e); e.stopPropagation(); e.preventDefault(); break; } } handleItemClick = e => { const { onItemClick } = this.props; const i = Number(e.currentTarget.getAttribute('data-index')); const item = this.props.items[i]; this.handleClose(); if (typeof onItemClick === 'function') { e.preventDefault(); onItemClick(item, i); } else if (item && typeof item.action === 'function') { e.preventDefault(); item.action(); } else if (item && item.to) { e.preventDefault(); this.context.router.history.push(item.to); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } componentWillUnmount = () => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } } close = () => { this.handleClose(); } render () { const { icon, items, size, title, disabled, loading, scrollable, dropdownPlacement, openDropdownId, openedViaKeyboard, children, renderItem, renderHeader, } = this.props; const open = this.state.id === openDropdownId; const button = children ? React.cloneElement(React.Children.only(children), { ref: this.setTargetRef, onClick: this.handleClick, onMouseDown: this.handleMouseDown, onKeyDown: this.handleButtonKeyDown, onKeyPress: this.handleKeyPress, }) : ( <IconButton icon={icon} title={title} active={open} disabled={disabled} size={size} ref={this.setTargetRef} onClick={this.handleClick} onMouseDown={this.handleMouseDown} onKeyDown={this.handleButtonKeyDown} onKeyPress={this.handleKeyPress} /> ); return ( <React.Fragment> {button} <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}> <DropdownMenu items={items} loading={loading} scrollable={scrollable} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} renderItem={renderItem} renderHeader={renderHeader} onItemClick={this.handleItemClick} /> </Overlay> </React.Fragment> ); } }
src/svg-icons/action/cached.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCached = (props) => ( <SvgIcon {...props}> <path d="M19 8l-4 4h3c0 3.31-2.69 6-6 6-1.01 0-1.97-.25-2.8-.7l-1.46 1.46C8.97 19.54 10.43 20 12 20c4.42 0 8-3.58 8-8h3l-4-4zM6 12c0-3.31 2.69-6 6-6 1.01 0 1.97.25 2.8.7l1.46-1.46C15.03 4.46 13.57 4 12 4c-4.42 0-8 3.58-8 8H1l4 4 4-4H6z"/> </SvgIcon> ); ActionCached = pure(ActionCached); ActionCached.displayName = 'ActionCached'; ActionCached.muiName = 'SvgIcon'; export default ActionCached;
lib/jquery/jquery.min.js
BerneBee/BuildItB
/*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0; }return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}}),function(){var a;l.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,e;return c=d.getElementsByTagName("body")[0],c&&c.style?(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(d.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(e),a):void 0}}();var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),V=["Top","Right","Bottom","Left"],W=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function X(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&U.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var Y=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)Y(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/<tbody/i;function ia(a){Z.test(a.type)&&(a.defaultChecked=a.checked)}function ja(a,b,c,d,e){for(var f,g,h,i,j,k,m,o=a.length,p=ca(b),q=[],r=0;o>r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?"<table>"!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ma.test(f)?this.mouseHooks:la.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=g.srcElement||d),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,g):a},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button,h=b.fromElement;return null==a.pageX&&null!=b.clientX&&(e=a.target.ownerDocument||d,f=e.documentElement,c=e.body,a.pageX=b.clientX+(f&&f.scrollLeft||c&&c.scrollLeft||0)-(f&&f.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(f&&f.scrollTop||c&&c.scrollTop||0)-(f&&f.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?b.toElement:h),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ra()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ra()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=d.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?pa:qa):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=pa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=pa,a&&!this.isSimulated&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=pa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submit||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?n.prop(b,"form"):void 0;c&&!n._data(c,"submit")&&(n.event.add(c,"submit._submit",function(a){a._submitBubble=!0}),n._data(c,"submit",!0))})},postDispatch:function(a){a._submitBubble&&(delete a._submitBubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.change||(n.event.special.change={setup:function(){return ka.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._justChanged=!0)}),n.event.add(this,"click._change",function(a){this._justChanged&&!a.isTrigger&&(this._justChanged=!1),n.event.simulate("change",this,a)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;ka.test(b.nodeName)&&!n._data(b,"change")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a)}),n._data(b,"change",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!ka.test(this.nodeName)}}),l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d){return sa(this,a,b,c,d)},one:function(a,b,c,d){return sa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=qa),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ta=/ jQuery\d+="(?:null|\d+)"/g,ua=new RegExp("<(?:"+ba+")[\\s/>]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/<script|<style|<link/i,xa=/checked\s*(?:[^=]|=\s*.checked.)/i,ya=/^true\/(.*)/,za=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ja[0].contentWindow||Ja[0].contentDocument).document,b.write(),b.close(),c=La(a,b),Ja.detach()),Ka[a]=c),c}var Na=/^margin/,Oa=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Pa=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Qa=d.documentElement;!function(){var b,c,e,f,g,h,i=d.createElement("div"),j=d.createElement("div");if(j.style){j.style.cssText="float:left;opacity:.5",l.opacity="0.5"===j.style.opacity,l.cssFloat=!!j.style.cssFloat,j.style.backgroundClip="content-box",j.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===j.style.backgroundClip,i=d.createElement("div"),i.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",j.innerHTML="",i.appendChild(j),l.boxSizing=""===j.style.boxSizing||""===j.style.MozBoxSizing||""===j.style.WebkitBoxSizing,n.extend(l,{reliableHiddenOffsets:function(){return null==b&&k(),f},boxSizingReliable:function(){return null==b&&k(),e},pixelMarginRight:function(){return null==b&&k(),c},pixelPosition:function(){return null==b&&k(),b},reliableMarginRight:function(){return null==b&&k(),g},reliableMarginLeft:function(){return null==b&&k(),h}});function k(){var k,l,m=d.documentElement;m.appendChild(i),j.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",b=e=h=!1,c=g=!0,a.getComputedStyle&&(l=a.getComputedStyle(j),b="1%"!==(l||{}).top,h="2px"===(l||{}).marginLeft,e="4px"===(l||{width:"4px"}).width,j.style.marginRight="50%",c="4px"===(l||{marginRight:"4px"}).marginRight,k=j.appendChild(d.createElement("div")),k.style.cssText=j.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",k.style.marginRight=k.style.width="0",j.style.width="1px",g=!parseFloat((a.getComputedStyle(k)||{}).marginRight),j.removeChild(k)),j.style.display="none",f=0===j.getClientRects().length,f&&(j.style.display="",j.innerHTML="<table><tr><td></td><td>t</td></tr></table>",j.childNodes[0].style.borderCollapse="separate",k=j.getElementsByTagName("td"),k[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===k[0].offsetHeight,f&&(k[0].style.display="",k[1].style.display="none",f=0===k[0].offsetHeight)),m.removeChild(i)}}}();var Ra,Sa,Ta=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ra=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Oa.test(g)&&Na.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0===g?g:g+""}):Qa.currentStyle&&(Ra=function(a){return a.currentStyle},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Oa.test(g)&&!Ta.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Ua(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Va=/alpha\([^)]*\)/i,Wa=/opacity\s*=\s*([^)]*)/i,Xa=/^(none|table(?!-c[ea]).+)/,Ya=new RegExp("^("+T+")(.*)$","i"),Za={position:"absolute",visibility:"hidden",display:"block"},$a={letterSpacing:"0",fontWeight:"400"},_a=["Webkit","O","Moz","ms"],ab=d.createElement("div").style;function bb(a){if(a in ab)return a;var b=a.charAt(0).toUpperCase()+a.slice(1),c=_a.length;while(c--)if(a=_a[c]+b,a in ab)return a}function cb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&W(d)&&(f[g]=n._data(d,"olddisplay",Ma(d.nodeName)))):(e=W(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function db(a,b,c){var d=Ya.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function eb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+V[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+V[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+V[f]+"Width",!0,e))):(g+=n.css(a,"padding"+V[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+V[f]+"Width",!0,e)));return g}function fb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ra(a),g=l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Sa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Oa.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+eb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Sa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=U.exec(c))&&e[1]&&(c=X(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Sa(a,b,d)),"normal"===f&&b in $a&&(f=$a[b]),""===c||c?(e=parseFloat(f),c===!0||isFinite(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Xa.test(n.css(a,"display"))&&0===a.offsetWidth?Pa(a,Za,function(){return fb(a,b,d)}):fb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ra(a);return db(a,c,d?eb(a,b,d,l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Wa.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Va,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Va.test(f)?f.replace(Va,e):f+" "+e)}}),n.cssHooks.marginRight=Ua(l.reliableMarginRight,function(a,b){return b?Pa(a,{display:"inline-block"},Sa,[a,"marginRight"]):void 0}),n.cssHooks.marginLeft=Ua(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Sa(a,"marginLeft"))||(n.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Pa(a,{ marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px":void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+V[d]+b]=f[d]||f[d-2]||f[0];return e}},Na.test(a)||(n.cssHooks[a+b].set=db)}),n.fn.extend({css:function(a,b){return Y(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ra(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return cb(this,!0)},hide:function(){return cb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){W(this)?n(this).show():n(this).hide()})}});function gb(a,b,c,d,e){return new gb.prototype.init(a,b,c,d,e)}n.Tween=gb,gb.prototype={constructor:gb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=gb.propHooks[this.prop];return a&&a.get?a.get(this):gb.propHooks._default.get(this)},run:function(a){var b,c=gb.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):gb.propHooks._default.set(this),this}},gb.prototype.init.prototype=gb.prototype,gb.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},gb.propHooks.scrollTop=gb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=gb.prototype.init,n.fx.step={};var hb,ib,jb=/^(?:toggle|show|hide)$/,kb=/queueHooks$/;function lb(){return a.setTimeout(function(){hb=void 0}),hb=n.now()}function mb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=V[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function nb(a,b,c){for(var d,e=(qb.tweeners[b]||[]).concat(qb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ob(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&W(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k="none"===j?n._data(a,"olddisplay")||Ma(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==Ma(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],jb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(o))"inline"===("none"===j?Ma(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=nb(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function pb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function qb(a,b,c){var d,e,f=0,g=qb.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=hb||lb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:hb||lb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(pb(k,j.opts.specialEasing);g>f;f++)if(d=qb.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,nb,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(qb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return X(c.elem,a,U.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],qb.tweeners[c]=qb.tweeners[c]||[],qb.tweeners[c].unshift(b)},prefilters:[ob],prefilter:function(a,b){b?qb.prefilters.unshift(a):qb.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(W).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=qb(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&kb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(mb(b,!0),a,d,e)}}),n.each({slideDown:mb("show"),slideUp:mb("hide"),slideToggle:mb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(hb=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),hb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ib||(ib=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(ib),ib=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a,b=d.createElement("input"),c=d.createElement("div"),e=d.createElement("select"),f=e.appendChild(d.createElement("option"));c=d.createElement("div"),c.setAttribute("className","t"),c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],b.setAttribute("type","checkbox"),c.appendChild(b),a=c.getElementsByTagName("a")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==c.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=f.selected,l.enctype=!!d.createElement("form").enctype,e.disabled=!0,l.optDisabled=!f.disabled,b=d.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value}();var rb=/\r/g,sb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(sb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>-1)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var tb,ub,vb=n.expr.attrHandle,wb=/^(?:checked|selected)$/i,xb=l.getSetAttribute,yb=l.input;n.fn.extend({attr:function(a,b){return Y(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ub:tb)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?yb&&xb||!wb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(xb?c:d)}}),ub={set:function(a,b,c){return b===!1?n.removeAttr(a,c):yb&&xb||!wb.test(c)?a.setAttribute(!xb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=vb[b]||n.find.attr;yb&&xb||!wb.test(b)?vb[b]=function(a,b,d){var e,f;return d||(f=vb[b],vb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,vb[b]=f),e}:vb[b]=function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),yb&&xb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):tb&&tb.set(a,b,c)}}),xb||(tb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},vb.id=vb.name=vb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:tb.set},n.attrHooks.contenteditable={set:function(a,b,c){tb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var zb=/^(?:input|select|textarea|button|object)$/i,Ab=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return Y(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):zb.test(a.nodeName)||Ab.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Bb=/[\t\r\n\f]/g;function Cb(a){return n.attr(a,"class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,Cb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,Cb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,Cb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=Cb(this),b&&n._data(this,"__className__",b),n.attr(this,"class",b||a===!1?"":n._data(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+Cb(c)+" ").replace(Bb," ").indexOf(b)>-1)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Db=a.location,Eb=n.now(),Fb=/\?/,Gb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(Gb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new a.DOMParser,c=d.parseFromString(b,"text/xml")):(c=new a.ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var Hb=/#.*$/,Ib=/([?&])_=[^&]*/,Jb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Kb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Lb=/^(?:GET|HEAD)$/,Mb=/^\/\//,Nb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ob={},Pb={},Qb="*/".concat("*"),Rb=Db.href,Sb=Nb.exec(Rb.toLowerCase())||[];function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Vb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Wb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Xb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Rb,type:"GET",isLocal:Kb.test(Sb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Vb(Vb(a,n.ajaxSettings),b):Vb(n.ajaxSettings,a)},ajaxPrefilter:Tb(Ob),ajaxTransport:Tb(Pb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var d,e,f,g,h,i,j,k,l=n.ajaxSetup({},c),m=l.context||l,o=l.context&&(m.nodeType||m.jquery)?n(m):n.event,p=n.Deferred(),q=n.Callbacks("once memory"),r=l.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,getResponseHeader:function(a){var b;if(2===u){if(!k){k={};while(b=Jb.exec(g))k[b[1].toLowerCase()]=b[2]}b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===u?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return u||(a=t[c]=t[c]||a,s[a]=b),this},overrideMimeType:function(a){return u||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>u)for(b in a)r[b]=[r[b],a[b]];else w.always(a[w.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),y(0,b),this}};if(p.promise(w).complete=q.add,w.success=w.done,w.error=w.fail,l.url=((b||l.url||Rb)+"").replace(Hb,"").replace(Mb,Sb[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=n.trim(l.dataType||"*").toLowerCase().match(G)||[""],null==l.crossDomain&&(d=Nb.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Sb[1]&&d[2]===Sb[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Sb[3]||("http:"===Sb[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=n.param(l.data,l.traditional)),Ub(Ob,l,c,w),2===u)return w;i=n.event&&l.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Lb.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fb.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Ib.test(f)?f.replace(Ib,"$1_="+Eb++):f+(Fb.test(f)?"&":"?")+"_="+Eb++)),l.ifModified&&(n.lastModified[f]&&w.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&w.setRequestHeader("If-None-Match",n.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Qb+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}});function Yb(a){return a.style&&a.style.display||n.css(a,"display")}function Zb(a){if(!n.contains(a.ownerDocument||d,a))return!0;while(a&&1===a.nodeType){if("none"===Yb(a)||"hidden"===a.type)return!0;a=a.parentNode}return!1}n.expr.filters.hidden=function(a){return l.reliableHiddenOffsets()?a.offsetWidth<=0&&a.offsetHeight<=0&&!a.getClientRects().length:Zb(a)},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var $b=/%20/g,_b=/\[\]$/,ac=/\r?\n/g,bc=/^(?:submit|button|image|reset|file)$/i,cc=/^(?:input|select|textarea|keygen)/i;function dc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||_b.test(a)?d(a,e):dc(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)dc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)dc(c,a[c],b,e);return d.join("&").replace($b,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&cc.test(this.nodeName)&&!bc.test(a)&&(this.checked||!Z.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(ac,"\r\n")}}):{name:b.name,value:c.replace(ac,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return this.isLocal?ic():d.documentMode>8?hc():/^(get|post|head|put|delete|options)$/i.test(this.type)&&hc()||ic()}:hc;var ec=0,fc={},gc=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in fc)fc[a](void 0,!0)}),l.cors=!!gc&&"withCredentials"in gc,gc=l.ajax=!!gc,gc&&n.ajaxTransport(function(b){if(!b.crossDomain||l.cors){var c;return{send:function(d,e){var f,g=b.xhr(),h=++ec;if(g.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(f in b.xhrFields)g[f]=b.xhrFields[f];b.mimeType&&g.overrideMimeType&&g.overrideMimeType(b.mimeType),b.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=d.head||n("head")[0]||d.documentElement;return{send:function(e,f){b=d.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var jc=[],kc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=jc.pop()||n.expando+"_"+Eb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(kc.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&kc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(kc,"$1"+e):b.jsonp!==!1&&(b.url+=(Fb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,jc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ja([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var lc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&lc)return lc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h,a.length)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function mc(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?("undefined"!=typeof e.getBoundingClientRect&&(d=e.getBoundingClientRect()),c=mc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Qa})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return Y(this,function(a,d,e){var f=mc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ua(l.pixelPosition,function(a,c){return c?(c=Sa(a,b),Oa.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({ padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Y(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var nc=a.jQuery,oc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=oc),b&&a.jQuery===n&&(a.jQuery=nc),n},b||(a.jQuery=a.$=n),n});
examples/example-with-styleguidist/src/components/Button/Button.js
rofrischmann/fela
import React from 'react' import PropTypes from 'prop-types' import { createComponent } from 'react-fela' // declare fela styles const __buttonStyle = props => ({ padding: '.5em 1.5em', color: `${props.color || props.theme.colorGrey}`, 'background-color': props.theme.colorWhite, border: '1px solid currentColor', 'border-radius': props.theme.borderRadius, 'text-align': 'center', 'vertical-align': 'middle', cursor: 'pointer', fontSize: `${props.theme.buttonSizes[props.size] || props.theme.buttonSizes['normal']}`, }) const ButtonComponent = createComponent(__buttonStyle, 'button', [ 'color', 'size', 'onClick', ]) /** * The only true button. * Note: This component uses react-fela createComponent api to render styles for demo. */ export default function Button(props) { const { children, ...passDownProps } = props return <ButtonComponent {...passDownProps}>{children}</ButtonComponent> } Button.propTypes = { /** Button label */ children: PropTypes.oneOfType([ PropTypes.string.isRequired, PropTypes.number.isRequired, ]), /** The color for the button */ color: PropTypes.string, /** The size of the button */ size: PropTypes.oneOf(['small', 'normal', 'large']), /** Gets called when the user clicks on the button */ onClick: PropTypes.func, } Button.defaultProps = { color: '#333', size: 'normal', /* eslint-disable no-console */ onClick: event => { console.log('You have clicked me!', event.target) }, /* eslint-enable no-console */ }
ajax/libs/riot/2.3.0/riot+compiler.js
wout/cdnjs
/* Riot v2.3.0, @license MIT, (c) 2015 Muut Inc. + contributors */ ;(function(window, undefined) { 'use strict'; var riot = { version: 'v2.3.0', settings: {} }, // be aware, internal usage // ATTENTION: prefix the global dynamic variables with `__` // counter to give a unique id to all the Tag instances __uid = 0, // tags instances cache __virtualDom = [], // tags implementation cache __tagImpl = {}, /** * Const */ // riot specific prefixes RIOT_PREFIX = 'riot-', RIOT_TAG = RIOT_PREFIX + 'tag', // for typeof == '' comparisons T_STRING = 'string', T_OBJECT = 'object', T_UNDEF = 'undefined', T_FUNCTION = 'function', // special native tags that cannot be treated like the others SPECIAL_TAGS_REGEX = /^(?:opt(ion|group)|tbody|col|t[rhd])$/, RESERVED_WORDS_BLACKLIST = ['_item', '_id', '_parent', 'update', 'root', 'mount', 'unmount', 'mixin', 'isMounted', 'isLoop', 'tags', 'parent', 'opts', 'trigger', 'on', 'off', 'one'], // version# for IE 8-11, 0 for others IE_VERSION = (window && window.document || {}).documentMode | 0 /* istanbul ignore next */ riot.observable = function(el) { /** * Extend the original object or create a new empty one * @type { Object } */ el = el || {} /** * Private variables and methods */ var callbacks = {}, onEachEvent = function(e, fn) { e.replace(/\S+/g, fn) }, defineProperty = function (key, value) { Object.defineProperty(el, key, { value: value, enumerable: false, writable: false, configurable: false }) } /** * Listen to the given space separated list of `events` and execute the `callback` each time an event is triggered. * @param { String } events - events ids * @param { Function } fn - callback function * @returns { Object } el */ defineProperty('on', function(events, fn) { if (typeof fn != 'function') return el onEachEvent(events, function(name, pos) { (callbacks[name] = callbacks[name] || []).push(fn) fn.typed = pos > 0 }) return el }) /** * Removes the given space separated list of `events` listeners * @param { String } events - events ids * @param { Function } fn - callback function * @returns { Object } el */ defineProperty('off', function(events, fn) { if (events == '*') callbacks = {} else { onEachEvent(events, function(name) { if (fn) { var arr = callbacks[name] for (var i = 0, cb; cb = arr && arr[i]; ++i) { if (cb == fn) arr.splice(i--, 1) } } else delete callbacks[name] }) } return el }) /** * Listen to the given space separated list of `events` and execute the `callback` at most once * @param { String } events - events ids * @param { Function } fn - callback function * @returns { Object } el */ defineProperty('one', function(events, fn) { function on() { el.off(events, on) // V8 performance optimization // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments var arglen = arguments.length var args = new Array(arglen) for (var i = 0; i < arglen; i++) { args[i] = arguments[i] } fn.apply(el, args) } return el.on(events, on) }) /** * Execute all callback functions that listen to the given space separated list of `events` * @param { String } events - events ids * @returns { Object } el */ defineProperty('trigger', function(events) { // V8 performance optimization // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments var arglen = arguments.length - 1 var args = new Array(arglen) for (var i = 0; i < arglen; i++) { args[i] = arguments[i + 1] // skip first argument } onEachEvent(events, function(name) { var fns = (callbacks[name] || []).slice(0) for (var i = 0, fn; fn = fns[i]; ++i) { if (fn.busy) return fn.busy = 1 try { fn.apply(el, fn.typed ? [name].concat(args) : args) } catch (e) { /* error */} if (fns[i] !== fn) { i-- } fn.busy = 0 } if (callbacks.all && name != 'all') el.trigger.apply(el, ['all', name].concat(args)) }) return el }) return el } /* istanbul ignore next */ ;(function(riot) { if (!window) return; /** * Simple client-side router * @module riot-route */ var RE_ORIGIN = /^.+?\/+[^\/]+/, EVENT_LISTENER = 'EventListener', REMOVE_EVENT_LISTENER = 'remove' + EVENT_LISTENER, ADD_EVENT_LISTENER = 'add' + EVENT_LISTENER, HAS_ATTRIBUTE = 'hasAttribute', REPLACE = 'replace', POPSTATE = 'popstate', TRIGGER = 'trigger', win = window, doc = document, loc = win.history.location || win.location, // see html5-history-api prot = Router.prototype, // to minify more clickEvent = doc && doc.ontouchstart ? 'touchstart' : 'click', started = false, central = riot.observable(), base, current, parser, secondParser /** * Default parser. You can replace it via router.parser method. * @param {string} path - current path (normalized) * @returns {array} array */ function DEFAULT_PARSER(path) { return path.split(/[/?#]/) } /** * Default parser (second). You can replace it via router.parser method. * @param {string} path - current path (normalized) * @param {string} filter - filter string (normalized) * @returns {array} array */ function DEFAULT_SECOND_PARSER(path, filter) { var re = new RegExp('^' + filter[REPLACE](/\*/g, '([^/?#]+?)')[REPLACE](/\.\./, '.*') + '$'), args = path.match(re) if (args) return args.slice(1) } /** * Router class */ function Router() { this.$ = [] riot.observable(this) // make it observable central.on('stop', this.s.bind(this)) central.on('emit', this.e.bind(this)) } function normalize(path) { return path[REPLACE](/^\/|\/$/, '') } /** * Get the part after domain name * @param {string} href - fullpath * @returns {string} path from root */ function getPathFromRoot(href) { return (href || loc.href)[REPLACE](RE_ORIGIN, '') } /** * Get the part after base * @param {string} href - fullpath * @returns {string} path from base */ function getPathFromBase(href) { return base[0] == '#' ? (href || loc.href).split(base)[1] || '' : getPathFromRoot(href)[REPLACE](base, '') } function emit(force) { var path = getPathFromBase() if (force || path != current) { central[TRIGGER]('emit', path) current = path } } function click(e) { if ( e.which != 1 // not left click || e.metaKey || e.ctrlKey || e.shiftKey // or meta keys || e.defaultPrevented // or default prevented ) return var el = e.target while (el && el.nodeName != 'A') el = el.parentNode if ( !el || el.nodeName != 'A' // not A tag || el[HAS_ATTRIBUTE]('download') // has download attr || !el[HAS_ATTRIBUTE]('href') // has no href attr || el.target && el.target != '_self' // another window or frame || el.href.indexOf(loc.href.match(RE_ORIGIN)[0]) == -1 // cross origin ) return if (el.href != loc.href) { if (el.href.split('#')[0] == loc.href.split('#')[0]) return // internal jump go(getPathFromBase(el.href), el.title || doc.title) } e.preventDefault() } /** * Go to the path * @param {string} path - destination path * @param {string} title - page title */ function go(path, title) { title = title || doc.title // browsers ignores the second parameter `title` history.pushState(null, title, base + path) // so we need to set it manually doc.title = title emit() } /** * Go to path or set action * a single string: go there * two strings: go there with setting a title * a single function: set an action on the default route * a string/RegExp and a function: set an action on the route * @param {(string|function)} first - path / action / filter * @param {(string|RegExp|function)} second - title / action */ prot.m = function(first, second) { if (first[0] && (!second || second[0])) go(first, second) else if (second) this.r(first, second) else this.r('@', first) } /** * Stop routing */ prot.s = function() { this.off('*') this.$ = [] } /** * Emit * @param {string} path - path */ prot.e = function(path) { this.$.concat('@').some(function(filter) { var args = (filter == '@' ? parser : secondParser)(normalize(path), normalize(filter)) if (args) { this[TRIGGER].apply(null, [filter].concat(args)) return true // exit from loop } }, this) } /** * Register route * @param {string} filter - filter for matching to url * @param {function} action - action to register */ prot.r = function(filter, action) { if (filter != '@') this.$.push(filter) this.on(filter, action) } var mainRouter = new Router() var route = mainRouter.m.bind(mainRouter) /** * Create a sub router * @returns {function} the method of a new Router object */ route.create = function() { var newSubRouter = new Router() // stop only this sub-router newSubRouter.m.stop = newSubRouter.s.bind(newSubRouter) // return sub-router's main method return newSubRouter.m.bind(newSubRouter) } /** * Set the base of url * @param {(str|RegExp)} arg - a new base or '#' or '#!' */ route.base = function(arg) { base = arg || '#' current = getPathFromBase() // recalculate current path } /** Exec routing right now **/ route.exec = function() { emit(true) } /** * Replace the default router to yours * @param {function} fn - your parser function * @param {function} fn2 - your secondParser function */ route.parser = function(fn, fn2) { if (!fn && !fn2) { // reset parser for testing... parser = DEFAULT_PARSER secondParser = DEFAULT_SECOND_PARSER } if (fn) parser = fn if (fn2) secondParser = fn2 } /** * Helper function to get url query as an object * @returns {object} parsed query */ route.query = function() { var q = {} loc.href[REPLACE](/[?&](.+?)=([^&]*)/g, function(_, k, v) { q[k] = v }) return q } /** Stop routing **/ route.stop = function () { if (started) { win[REMOVE_EVENT_LISTENER](POPSTATE, emit) doc[REMOVE_EVENT_LISTENER](clickEvent, click) central[TRIGGER]('stop') started = false } } /** Start routing **/ route.start = function () { if (!started) { win[ADD_EVENT_LISTENER](POPSTATE, emit) doc[ADD_EVENT_LISTENER](clickEvent, click) started = true } } /** Prepare the router **/ route.base() route.parser() riot.route = route })(riot) /* istanbul ignore next */ /** * The riot template engine * @version 2.3.0 */ /** * @module brackets * * `brackets ` Returns a string or regex based on its parameter: * With a number returns the current left (0) or right (1) brackets. * With a regex, returns the original regex if the current brackets * are the default, or a new one with the default brackets replaced * by the current custom brackets. * WARNING: recreated regexes discards the `/i` and `/m` flags. * `brackets.settings` This object mirrors the `riot.settings` object, you can assign this * if riot is not in context. * `brackets.set ` The recommended option to change the current tiot brackets, check * its parameter and reconfigures the internal state immediately. */ var brackets = (function (UNDEF) { var REGLOB = 'g', MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g, STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'/g, S_QBSRC = STRINGS.source + '|' + /(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/])/.source + '|' + /\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source, DEFAULT = '{ }', FINDBRACES = { '(': _regExp('([()])|' + S_QBSRC, REGLOB), '[': _regExp('([[\\]])|' + S_QBSRC, REGLOB), '{': _regExp('([{}])|' + S_QBSRC, REGLOB) } var cachedBrackets = UNDEF, _regex, _pairs = [] function _regExp(source, flags) { return new RegExp(source, flags) } function _loopback(re) { return re } function _rewrite(re) { return new RegExp( re.source.replace(/{/g, _pairs[2]).replace(/}/g, _pairs[3]), re.global ? REGLOB : '' ) } function _reset(pair) { pair = pair || DEFAULT if (pair !== _pairs[8]) { var bp = pair.split(' ') if (pair === DEFAULT) { _pairs = bp.concat(bp) _regex = _loopback } else { if (bp.length !== 2 || /[\x00-\x1F<>a-zA-Z0-9'",;\\]/.test(pair)) { throw new Error('Unsupported brackets "' + pair + '"') } _pairs = bp.concat(pair.replace(/(?=[[\]()*+?.^$|])/g, '\\').split(' ')) _regex = _rewrite } _pairs[4] = _regex(_pairs[1].length > 1 ? /(?:^|[^\\]){[\S\s]*?}/ : /(?:^|[^\\]){[^}]*}/) _pairs[5] = _regex(/\\({|})/g) _pairs[6] = _regex(/(\\?)({)/g) _pairs[7] = _regExp('(\\\\?)(?:([[({])|(' + _pairs[3] + '))|' + S_QBSRC, REGLOB) _pairs[9] = _regExp(/^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S+)\s*}/) _pairs[8] = pair } _brackets.settings.brackets = cachedBrackets = pair } function _set(pair) { if (cachedBrackets !== pair) { _reset(pair) } } function _brackets(reOrIdx) { _set(_brackets.settings.brackets) return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _pairs[reOrIdx] } _brackets.split = function split(str, tmpl) { var parts = [], match, isexpr, start, pos, re = _brackets(6) isexpr = start = re.lastIndex = 0 while (match = re.exec(str)) { pos = match.index if (isexpr) { if (match[2]) { re.lastIndex = skipBraces(match[2], re.lastIndex) continue } if (!match[3]) continue } if (!match[1]) { unescapeStr(str.slice(start, pos)) start = re.lastIndex re = _pairs[6 + (isexpr ^= 1)] re.lastIndex = start } } if (str && start < str.length) { unescapeStr(str.slice(start)) } return parts function unescapeStr(str) { if (tmpl || isexpr) parts.push(str && str.replace(_pairs[5], '$1')) else parts.push(str) } function skipBraces(ch, pos) { var match, recch = FINDBRACES[ch], level = 1 recch.lastIndex = pos while (match = recch.exec(str)) { if (match[1] && !(match[1] === ch ? ++level : --level)) break } return match ? recch.lastIndex : str.length } } _brackets.hasExpr = function hasExpr(str) { return _brackets(4).test(str) } _brackets.loopKeys = function loopKeys(expr) { var m = expr.match(_brackets(9)) return m ? { key: m[1], pos: m[2], val: _pairs[0] + m[3] + _pairs[1] } : { val: expr.trim() } } _brackets.array = function array(pair) { if (pair != null) _reset(pair) return _pairs } /* istanbul ignore next: in the node version riot is not in the scope */ _brackets.settings = typeof riot !== 'undefined' && riot.settings || {} _brackets.set = _set _brackets.R_STRINGS = STRINGS _brackets.R_MLCOMMS = MLCOMMS _brackets.S_QBLOCKS = S_QBSRC _reset(_brackets.settings.brackets) return _brackets })() /** * @module tmpl * * tmpl - Root function, returns the template value, render with data * tmpl.hasExpr - Test the existence of a expression inside a string * tmpl.loopKeys - Get the keys for an 'each' loop (used by `_each`) */ var tmpl = (function () { var FALSE = !1, _cache = {} function _tmpl(str, data) { if (!str) return str return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr) } _tmpl.hasExpr = brackets.hasExpr _tmpl.loopKeys = brackets.loopKeys _tmpl.errorHandler = FALSE function _logErr(err, ctx) { if (_tmpl.errorHandler) { err.riotData = { tagName: ctx && ctx.root && ctx.root.tagName, _riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase } _tmpl.errorHandler(err) } } function _create(str) { var expr = _getTmpl(str) if (expr.slice(0, 11) !== "try{return ") expr = 'return ' + expr return new Function('E', expr + ';') // eslint-disable-line indent } var RE_QBLOCK = new RegExp(brackets.S_QBLOCKS, 'g'), RE_QBMARK = /\x01(\d+)~/g function _getTmpl(str) { var qstr = [], expr, parts = brackets.split(str, 1) if (parts.length > 2 || parts[0]) { var i, j, list = [] for (i = j = 0; i < parts.length; ++i) { expr = parts[i] if (expr && (expr = i & 1 ? _parseExpr(expr, 1, qstr) : '"' + expr .replace(/\\/g, '\\\\') .replace(/\r\n?|\n/g, '\\n') .replace(/"/g, '\\"') + '"' )) list[j++] = expr } expr = j < 2 ? list[0] : '[' + list.join(',') + '].join("")' } else { expr = _parseExpr(parts[1], 0, qstr) } if (qstr[0]) expr = expr.replace(RE_QBMARK, function (_, pos) { return qstr[pos] .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') }) return expr } var CS_IDENT = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\x01(\d+)~):/, RE_BRACE = /,|([[{(])|$/g function _parseExpr(expr, asText, qstr) { expr = expr .replace(RE_QBLOCK, function (s, div) { return s.length > 2 && !div ? '\x01' + (qstr.push(s) - 1) + '~' : s }) .replace(/\s+/g, ' ').trim() .replace(/\ ?([[\({},?\.:])\ ?/g, '$1') if (expr) { var list = [], cnt = 0, match while (expr && (match = expr.match(CS_IDENT)) && !match.index ) { var key, jsb, re = /,|([[{(])|$/g expr = RegExp.rightContext key = match[2] ? qstr[match[2]].slice(1, -1).trim().replace(/\s+/g, ' ') : match[1] while (jsb = (match = re.exec(expr))[1]) skipBraces(jsb, re) jsb = expr.slice(0, match.index) expr = RegExp.rightContext list[cnt++] = _wrapExpr(jsb, 1, key) } expr = !cnt ? _wrapExpr(expr, asText) : cnt > 1 ? '[' + list.join(',') + '].join(" ").trim()' : list[0] } return expr function skipBraces(jsb, re) { var match, lv = 1, ir = jsb === '(' ? /[()]/g : jsb === '[' ? /[[\]]/g : /[{}]/g ir.lastIndex = re.lastIndex while (match = ir.exec(expr)) { if (match[0] === jsb) ++lv else if (!--lv) break } re.lastIndex = lv ? expr.length : ir.lastIndex } } // istanbul ignore next: not both var JS_CONTEXT = '"in this?this:' + (typeof window !== 'object' ? 'global' : 'window') + ').' var JS_VARNAME = /[,{][$\w]+:|(^ *|[^$\w\.])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g function _wrapExpr(expr, asText, key) { var tb = FALSE expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) { if (mvar) { pos = tb ? 0 : pos + match.length if (mvar !== 'this' && mvar !== 'global' && mvar !== 'window') { match = p + '("' + mvar + JS_CONTEXT + mvar if (pos) tb = (s = s[pos]) === '.' || s === '(' || s === '[' } else if (pos) tb = !/^(?=(\.[$\w]+))\1(?:[^.[(]|$)/.test(s.slice(pos)) } return match }) if (tb) { expr = "try{return " + expr + '}catch(e){E(e,this)}' } if (key) { expr = (tb ? 'function(){' + expr + '}.call(this)' : '(' + expr + ')' ) + '?"' + key + '":""' } else if (asText) { expr = 'function(v){' + (tb ? expr.replace('return ', 'v=') : 'v=(' + expr + ')' ) + ';return v||v===0?v:""}.call(this)' } return expr } // istanbul ignore next: compatibility fix for beta versions _tmpl.parse = function (s) { return s } return _tmpl })() /* lib/browser/tag/mkdom.js Includes hacks needed for the Internet Explorer version 9 and bellow */ // http://kangax.github.io/compat-table/es5/#ie8 // http://codeplanet.io/dropping-ie8/ var mkdom = (function (checkIE) { var rootEls = { 'tr': 'tbody', 'th': 'tr', 'td': 'tr', 'tbody': 'table', 'col': 'colgroup' }, GENERIC = 'div' checkIE = checkIE && checkIE < 10 // creates any dom element in a div, table, or colgroup container function _mkdom(html) { var match = html && html.match(/^\s*<([-\w]+)/), tagName = match && match[1].toLowerCase(), rootTag = rootEls[tagName] || GENERIC, el = mkEl(rootTag) el.stub = true /* istanbul ignore next */ if (checkIE && tagName && (match = tagName.match(SPECIAL_TAGS_REGEX))) ie9elem(el, html, tagName, !!match[1]) else el.innerHTML = html return el } // creates tr, th, td, option, optgroup element for IE8-9 /* istanbul ignore next */ function ie9elem(el, html, tagName, select) { var div = mkEl(GENERIC), tag = select ? 'select>' : 'table>', child div.innerHTML = '<' + tag + html + '</' + tag child = $(tagName, div) if (child) el.appendChild(child) } // end ie9elem() return _mkdom })(IE_VERSION) /** * Convert the item looped into an object used to extend the child tag properties * @param { Object } expr - object containing the keys used to extend the children tags * @param { * } key - value to assign to the new object returned * @param { * } val - value containing the position of the item in the array * @returns { Object } - new object containing the values of the original item * * The variables 'key' and 'val' are arbitrary. * They depend on the collection type looped (Array, Object) * and on the expression used on the each tag * */ function mkitem(expr, key, val) { var item = {} item[expr.key] = key if (expr.pos) item[expr.pos] = val return item } /** * Unmount the redundant tags * @param { Array } items - array containing the current items to loop * @param { Array } tags - array containing all the children tags */ function unmountRedundant(items, tags) { var i = tags.length, j = items.length while (i > j) { var t = tags[--i] tags.splice(i, 1) t.unmount() } } /** * Move the nested custom tags in non custom loop tags * @param { Object } child - non custom loop tag * @param { Number } i - current position of the loop tag */ function moveNestedTags(child, i) { Object.keys(child.tags).forEach(function(tagName) { var tag = child.tags[tagName] if (isArray(tag)) each(tag, function (t) { moveChildTag(t, tagName, i) }) else moveChildTag(tag, tagName, i) }) } /** * Adds the elements for a virtual tag * @param { Tag } tag - the tag whose root's children will be inserted or appended * @param { Node } src - the node that will do the inserting or appending * @param { Tag } target - only if inserting, insert before this tag's first child */ function addVirtual(tag, src, target) { var el = tag._root tag._virts = [] while (el) { var sib = el.nextSibling if (target) src.insertBefore(el, target._root) else src.appendChild(el) tag._virts.push(el) // hold for unmounting el = sib } } /** * Move virtual tag and all child nodes * @param { Tag } tag - first child reference used to start move * @param { Node } src - the node that will do the inserting * @param { Tag } target - insert before this tag's first child * @param { Number } len - how many child nodes to move */ function moveVirtual(tag, src, target, len) { var el = tag._root for (var i = 0; i < len; i++) { var sib = el.nextSibling src.insertBefore(el, target._root) el = sib } } /** * Manage tags having the 'each' * @param { Object } dom - DOM node we need to loop * @param { Tag } parent - parent tag instance where the dom node is contained * @param { String } expr - string contained in the 'each' attribute */ function _each(dom, parent, expr) { // remove the each property from the original tag remAttr(dom, 'each') var mustReorder = typeof getAttr(dom, 'no-reorder') !== T_STRING || remAttr(dom, 'no-reorder'), tagName = getTagName(dom), impl = __tagImpl[tagName] || { tmpl: dom.outerHTML }, useRoot = SPECIAL_TAGS_REGEX.test(tagName), root = dom.parentNode, isSpecialTag = SPECIAL_TAGS_REGEX.test(tagName), ref = document.createTextNode(''), child = getTag(dom), tags = [], oldItems = [], checksum, isVirtual = dom.tagName == 'VIRTUAL' // parse the each expression expr = tmpl.loopKeys(expr) // insert a marked where the loop tags will be injected root.insertBefore(ref, dom) // clean template code parent.one('before-mount', function () { // remove the original DOM node dom.parentNode.removeChild(dom) if (root.stub) root = parent.root }).on('update', function () { // get the new items collection var items = tmpl(expr.val, parent), // create a fragment to hold the new DOM nodes to inject in the parent tag frag = document.createDocumentFragment() // object loop. any changes cause full redraw if (!isArray(items)) { checksum = items ? JSON.stringify(items) : '' items = !items ? [] : Object.keys(items).map(function (key) { return mkitem(expr, key, items[key]) }) } // loop all the new items each(items, function(item, i) { // reorder only if the items are objects var _mustReorder = mustReorder && item instanceof Object, oldPos = oldItems.indexOf(item), pos = ~oldPos && _mustReorder ? oldPos : i, // does a tag exist in this position? tag = tags[pos] item = !checksum && expr.key ? mkitem(expr, item, i) : item // new tag if ( !_mustReorder && !tag // with no-reorder we just update the old tags || _mustReorder && !~oldPos || !tag // by default we always try to reorder the DOM elements ) { tag = new Tag(impl, { parent: parent, isLoop: true, hasImpl: !!__tagImpl[tagName], root: useRoot ? root : dom.cloneNode(), item: item }, dom.innerHTML) tag.mount() if (isVirtual) tag._root = tag.root.firstChild // save reference for further moves or inserts // this tag must be appended if (i == tags.length) { if (isVirtual) addVirtual(tag, frag) else frag.appendChild(tag.root) } // this tag must be insert else { if (isVirtual) addVirtual(tag, root, tags[i]) else root.insertBefore(tag.root, tags[i].root) oldItems.splice(i, 0, item) } tags.splice(i, 0, tag) pos = i // handled here so no move } else tag.update(item) // reorder the tag if it's not located in its previous position if (pos !== i && _mustReorder) { // update the DOM if (isVirtual) moveVirtual(tag, root, tags[i], dom.childNodes.length) else root.insertBefore(tag.root, tags[i].root) // update the position attribute if it exists if (expr.pos) tag[expr.pos] = i // move the old tag instance tags.splice(i, 0, tags.splice(pos, 1)[0]) // move the old item oldItems.splice(i, 0, oldItems.splice(pos, 1)[0]) // if the loop tags are not custom // we need to move all their custom tags into the right position if (!child) moveNestedTags(tag, i) } // cache the original item to use it in the events bound to this node // and its children tag._item = item // cache the real parent tag internally defineProperty(tag, '_parent', parent) }) // remove the redundant tags unmountRedundant(items, tags) // insert the new nodes if (isSpecialTag) root.appendChild(frag) else root.insertBefore(frag, ref) // set the 'tags' property of the parent tag // if child is 'undefined' it means that we don't need to set this property // for example: // we don't need store the `myTag.tags['div']` property if we are looping a div tag // but we need to track the `myTag.tags['child']` property looping a custom child node named `child` if (child) parent.tags[tagName] = tags // clone the items array oldItems = items.slice() }) } function parseNamedElements(root, tag, childTags, forceParsingNamed) { walk(root, function(dom) { if (dom.nodeType == 1) { dom.isLoop = dom.isLoop || (dom.parentNode && dom.parentNode.isLoop || getAttr(dom, 'each')) ? 1 : 0 // custom child tag if (childTags) { var child = getTag(dom) if (child && !dom.isLoop) childTags.push(initChildTag(child, {root: dom, parent: tag}, dom.innerHTML, tag)) } if (!dom.isLoop || forceParsingNamed) setNamed(dom, tag, []) } }) } function parseExpressions(root, tag, expressions) { function addExpr(dom, val, extra) { if (tmpl.hasExpr(val)) { var expr = { dom: dom, expr: val } expressions.push(extend(expr, extra)) } } walk(root, function(dom) { var type = dom.nodeType // text node if (type == 3 && dom.parentNode.tagName != 'STYLE') addExpr(dom, dom.nodeValue) if (type != 1) return /* element */ // loop var attr = getAttr(dom, 'each') if (attr) { _each(dom, tag, attr); return false } // attribute expressions each(dom.attributes, function(attr) { var name = attr.name, bool = name.split('__')[1] addExpr(dom, attr.value, { attr: bool || name, bool: bool }) if (bool) { remAttr(dom, name); return false } }) // skip custom tags if (getTag(dom)) return false }) } function Tag(impl, conf, innerHTML) { var self = riot.observable(this), opts = inherit(conf.opts) || {}, dom = mkdom(impl.tmpl), parent = conf.parent, isLoop = conf.isLoop, hasImpl = conf.hasImpl, item = cleanUpData(conf.item), expressions = [], childTags = [], root = conf.root, fn = impl.fn, tagName = root.tagName.toLowerCase(), attr = {}, propsInSyncWithParent = [] if (fn && root._tag) root._tag.unmount(true) // not yet mounted this.isMounted = false root.isLoop = isLoop // keep a reference to the tag just created // so we will be able to mount this tag multiple times root._tag = this // create a unique id to this tag // it could be handy to use it also to improve the virtual dom rendering speed defineProperty(this, '_riot_id', ++__uid) // base 1 allows test !t._riot_id extend(this, { parent: parent, root: root, opts: opts, tags: {} }, item) // grab attributes each(root.attributes, function(el) { var val = el.value // remember attributes with expressions only if (tmpl.hasExpr(val)) attr[el.name] = val }) if (dom.innerHTML && !/^(select|optgroup|table|tbody|tr|col(?:group)?)$/.test(tagName)) // replace all the yield tags with the tag inner html dom.innerHTML = replaceYield(dom.innerHTML, innerHTML) // options function updateOpts() { var ctx = hasImpl && isLoop ? self : parent || self // update opts from current DOM attributes each(root.attributes, function(el) { opts[toCamel(el.name)] = tmpl(el.value, ctx) }) // recover those with expressions each(Object.keys(attr), function(name) { opts[toCamel(name)] = tmpl(attr[name], ctx) }) } function normalizeData(data) { for (var key in item) { if (typeof self[key] !== T_UNDEF && isWritable(self, key)) self[key] = data[key] } } function inheritFromParent () { if (!self.parent || !isLoop) return each(Object.keys(self.parent), function(k) { // some properties must be always in sync with the parent tag var mustSync = !contains(RESERVED_WORDS_BLACKLIST, k) && contains(propsInSyncWithParent, k) if (typeof self[k] === T_UNDEF || mustSync) { // track the property to keep in sync // so we can keep it updated if (!mustSync) propsInSyncWithParent.push(k) self[k] = self.parent[k] } }) } defineProperty(this, 'update', function(data) { // make sure the data passed will not override // the component core methods data = cleanUpData(data) // inherit properties from the parent inheritFromParent() // normalize the tag properties in case an item object was initially passed if (data && typeof item === T_OBJECT) { normalizeData(data) item = data } extend(self, data) updateOpts() self.trigger('update', data) update(expressions, self) self.trigger('updated') return this }) defineProperty(this, 'mixin', function() { each(arguments, function(mix) { mix = typeof mix === T_STRING ? riot.mixin(mix) : mix each(Object.keys(mix), function(key) { // bind methods to self if (key != 'init') self[key] = isFunction(mix[key]) ? mix[key].bind(self) : mix[key] }) // init method will be called automatically if (mix.init) mix.init.bind(self)() }) return this }) defineProperty(this, 'mount', function() { updateOpts() // initialiation if (fn) fn.call(self, opts) // parse layout after init. fn may calculate args for nested custom tags parseExpressions(dom, self, expressions) // mount the child tags toggle(true) // update the root adding custom attributes coming from the compiler // it fixes also #1087 if (impl.attrs || hasImpl) { walkAttributes(impl.attrs, function (k, v) { setAttr(root, k, v) }) parseExpressions(self.root, self, expressions) } if (!self.parent || isLoop) self.update(item) // internal use only, fixes #403 self.trigger('before-mount') if (isLoop && !hasImpl) { // update the root attribute for the looped elements self.root = root = dom.firstChild } else { while (dom.firstChild) root.appendChild(dom.firstChild) if (root.stub) self.root = root = parent.root } // parse the named dom nodes in the looped child // adding them to the parent as well if (isLoop) parseNamedElements(self.root, self.parent, null, true) // if it's not a child tag we can trigger its mount event if (!self.parent || self.parent.isMounted) { self.isMounted = true self.trigger('mount') } // otherwise we need to wait that the parent event gets triggered else self.parent.one('mount', function() { // avoid to trigger the `mount` event for the tags // not visible included in an if statement if (!isInStub(self.root)) { self.parent.isMounted = self.isMounted = true self.trigger('mount') } }) }) defineProperty(this, 'unmount', function(keepRootTag) { var el = root, p = el.parentNode, ptag self.trigger('before-unmount') // remove this tag instance from the global virtualDom variable __virtualDom.splice(__virtualDom.indexOf(self), 1) if (this._virts) { each(this._virts, function(v) { v.parentNode.removeChild(v) }) } if (p) { if (parent) { ptag = getImmediateCustomParentTag(parent) // remove this tag from the parent tags object // if there are multiple nested tags with same name.. // remove this element form the array if (isArray(ptag.tags[tagName])) each(ptag.tags[tagName], function(tag, i) { if (tag._riot_id == self._riot_id) ptag.tags[tagName].splice(i, 1) }) else // otherwise just delete the tag instance ptag.tags[tagName] = undefined } else while (el.firstChild) el.removeChild(el.firstChild) if (!keepRootTag) p.removeChild(el) else // the riot-tag attribute isn't needed anymore, remove it remAttr(p, 'riot-tag') } self.trigger('unmount') toggle() self.off('*') self.isMounted = false // somehow ie8 does not like `delete root._tag` root._tag = null }) function toggle(isMount) { // mount/unmount children each(childTags, function(child) { child[isMount ? 'mount' : 'unmount']() }) // listen/unlisten parent (events flow one way from parent to children) if (parent) { var evt = isMount ? 'on' : 'off' // the loop tags will be always in sync with the parent automatically if (isLoop) parent[evt]('unmount', self.unmount) else parent[evt]('update', self.update)[evt]('unmount', self.unmount) } } // named elements available for fn parseNamedElements(dom, this, childTags) } /** * Attach an event to a DOM node * @param { String } name - event name * @param { Function } handler - event callback * @param { Object } dom - dom node * @param { Tag } tag - tag instance */ function setEventHandler(name, handler, dom, tag) { dom[name] = function(e) { var ptag = tag._parent, item = tag._item, el if (!item) while (ptag && !item) { item = ptag._item ptag = ptag._parent } // cross browser event fix e = e || window.event // override the event properties if (isWritable(e, 'currentTarget')) e.currentTarget = dom if (isWritable(e, 'target')) e.target = e.srcElement if (isWritable(e, 'which')) e.which = e.charCode || e.keyCode e.item = item // prevent default behaviour (by default) if (handler.call(tag, e) !== true && !/radio|check/.test(dom.type)) { if (e.preventDefault) e.preventDefault() e.returnValue = false } if (!e.preventUpdate) { el = item ? getImmediateCustomParentTag(ptag) : tag el.update() } } } /** * Insert a DOM node replacing another one (used by if- attribute) * @param { Object } root - parent node * @param { Object } node - node replaced * @param { Object } before - node added */ function insertTo(root, node, before) { if (root) { root.insertBefore(before, node) root.removeChild(node) } } /** * Update the expressions in a Tag instance * @param { Array } expressions - expression that must be re evaluated * @param { Tag } tag - tag instance */ function update(expressions, tag) { each(expressions, function(expr, i) { var dom = expr.dom, attrName = expr.attr, value = tmpl(expr.expr, tag), parent = expr.dom.parentNode if (expr.bool) value = value ? attrName : false else if (value == null) value = '' // leave out riot- prefixes from strings inside textarea // fix #815: any value -> string if (parent && parent.tagName == 'TEXTAREA') value = ('' + value).replace(/riot-/g, '') // no change if (expr.value === value) return expr.value = value // text node if (!attrName) { dom.nodeValue = '' + value // #815 related return } // remove original attribute remAttr(dom, attrName) // event handler if (isFunction(value)) { setEventHandler(attrName, value, dom, tag) // if- conditional } else if (attrName == 'if') { var stub = expr.stub, add = function() { insertTo(stub.parentNode, stub, dom) }, remove = function() { insertTo(dom.parentNode, dom, stub) } // add to DOM if (value) { if (stub) { add() dom.inStub = false // avoid to trigger the mount event if the tags is not visible yet // maybe we can optimize this avoiding to mount the tag at all if (!isInStub(dom)) { walk(dom, function(el) { if (el._tag && !el._tag.isMounted) el._tag.isMounted = !!el._tag.trigger('mount') }) } } // remove from DOM } else { stub = expr.stub = stub || document.createTextNode('') // if the parentNode is defined we can easily replace the tag if (dom.parentNode) remove() // otherwise we need to wait the updated event else (tag.parent || tag).one('updated', remove) dom.inStub = true } // show / hide } else if (/^(show|hide)$/.test(attrName)) { if (attrName == 'hide') value = !value dom.style.display = value ? '' : 'none' // field value } else if (attrName == 'value') { dom.value = value // <img src="{ expr }"> } else if (startsWith(attrName, RIOT_PREFIX) && attrName != RIOT_TAG) { if (value) setAttr(dom, attrName.slice(RIOT_PREFIX.length), value) } else { if (expr.bool) { dom[attrName] = value if (!value) return } if (typeof value !== T_OBJECT) setAttr(dom, attrName, value) } }) } /** * Loops an array * @param { Array } els - collection of items * @param {Function} fn - callback function * @returns { Array } the array looped */ function each(els, fn) { for (var i = 0, len = (els || []).length, el; i < len; i++) { el = els[i] // return false -> remove current item during loop if (el != null && fn(el, i) === false) i-- } return els } /** * Detect if the argument passed is a function * @param { * } v - whatever you want to pass to this function * @returns { Boolean } - */ function isFunction(v) { return typeof v === T_FUNCTION || false // avoid IE problems } /** * Remove any DOM attribute from a node * @param { Object } dom - DOM node we want to update * @param { String } name - name of the property we want to remove */ function remAttr(dom, name) { dom.removeAttribute(name) } /** * Convert a string containing dashes to camle case * @param { String } string - input string * @returns { String } my-string -> myString */ function toCamel(string) { return string.replace(/(\-\w)/g, function(match) { return match.toUpperCase().replace('-', '') }) } /** * Get the value of any DOM attribute on a node * @param { Object } dom - DOM node we want to parse * @param { String } name - name of the attribute we want to get * @returns { String | undefined } name of the node attribute whether it exists */ function getAttr(dom, name) { return dom.getAttribute(name) } /** * Set any DOM attribute * @param { Object } dom - DOM node we want to update * @param { String } name - name of the property we want to set * @param { String } val - value of the property we want to set */ function setAttr(dom, name, val) { dom.setAttribute(name, val) } /** * Detect the tag implementation by a DOM node * @param { Object } dom - DOM node we need to parse to get its tag implementation * @returns { Object } it returns an object containing the implementation of a custom tag (template and boot function) */ function getTag(dom) { return dom.tagName && __tagImpl[getAttr(dom, RIOT_TAG) || dom.tagName.toLowerCase()] } /** * Add a child tag to its parent into the `tags` object * @param { Object } tag - child tag instance * @param { String } tagName - key where the new tag will be stored * @param { Object } parent - tag instance where the new child tag will be included */ function addChildTag(tag, tagName, parent) { var cachedTag = parent.tags[tagName] // if there are multiple children tags having the same name if (cachedTag) { // if the parent tags property is not yet an array // create it adding the first cached tag if (!isArray(cachedTag)) // don't add the same tag twice if (cachedTag !== tag) parent.tags[tagName] = [cachedTag] // add the new nested tag to the array if (!contains(parent.tags[tagName], tag)) parent.tags[tagName].push(tag) } else { parent.tags[tagName] = tag } } /** * Move the position of a custom tag in its parent tag * @param { Object } tag - child tag instance * @param { String } tagName - key where the tag was stored * @param { Number } newPos - index where the new tag will be stored */ function moveChildTag(tag, tagName, newPos) { var parent = tag.parent, tags // no parent no move if (!parent) return tags = parent.tags[tagName] if (isArray(tags)) tags.splice(newPos, 0, tags.splice(tags.indexOf(tag), 1)[0]) else addChildTag(tag, tagName, parent) } /** * Create a new child tag including it correctly into its parent * @param { Object } child - child tag implementation * @param { Object } opts - tag options containing the DOM node where the tag will be mounted * @param { String } innerHTML - inner html of the child node * @param { Object } parent - instance of the parent tag including the child custom tag * @returns { Object } instance of the new child tag just created */ function initChildTag(child, opts, innerHTML, parent) { var tag = new Tag(child, opts, innerHTML), tagName = getTagName(opts.root), ptag = getImmediateCustomParentTag(parent) // fix for the parent attribute in the looped elements tag.parent = ptag // store the real parent tag // in some cases this could be different from the custom parent tag // for example in nested loops tag._parent = parent // add this tag to the custom parent tag addChildTag(tag, tagName, ptag) // and also to the real parent tag if (ptag !== parent) addChildTag(tag, tagName, parent) // empty the child node once we got its template // to avoid that its children get compiled multiple times opts.root.innerHTML = '' return tag } /** * Loop backward all the parents tree to detect the first custom parent tag * @param { Object } tag - a Tag instance * @returns { Object } the instance of the first custom parent tag found */ function getImmediateCustomParentTag(tag) { var ptag = tag while (!getTag(ptag.root)) { if (!ptag.parent) break ptag = ptag.parent } return ptag } /** * Helper function to set an immutable property * @param { Object } el - object where the new property will be set * @param { String } key - object key where the new property will be stored * @param { * } value - value of the new property * @param { Object } options - set the propery overriding the default options * @returns { Object } - the initial object */ function defineProperty(el, key, value, options) { Object.defineProperty(el, key, extend({ value: value, enumerable: false, writable: false, configurable: false }, options)) return el } /** * Get the tag name of any DOM node * @param { Object } dom - DOM node we want to parse * @returns { String } name to identify this dom node in riot */ function getTagName(dom) { var child = getTag(dom), namedTag = getAttr(dom, 'name'), tagName = namedTag && !tmpl.hasExpr(namedTag) ? namedTag : child ? child.name : dom.tagName.toLowerCase() return tagName } /** * Extend any object with other properties * @param { Object } src - source object * @returns { Object } the resulting extended object * * var obj = { foo: 'baz' } * extend(obj, {bar: 'bar', foo: 'bar'}) * console.log(obj) => {bar: 'bar', foo: 'bar'} * */ function extend(src) { var obj, args = arguments for (var i = 1; i < args.length; ++i) { if (obj = args[i]) { for (var key in obj) { // check if this property of the source object could be overridden if (isWritable(src, key)) src[key] = obj[key] } } } return src } /** * Check whether an array contains an item * @param { Array } arr - target array * @param { * } item - item to test * @returns { Boolean } Does 'arr' contain 'item'? */ function contains(arr, item) { return ~arr.indexOf(item) } /** * Check whether an object is a kind of array * @param { * } a - anything * @returns {Boolean} is 'a' an array? */ function isArray(a) { return Array.isArray(a) || a instanceof Array } /** * Detect whether a property of an object could be overridden * @param { Object } obj - source object * @param { String } key - object property * @returns { Boolean } is this property writable? */ function isWritable(obj, key) { var props = Object.getOwnPropertyDescriptor(obj, key) return typeof obj[key] === T_UNDEF || props && props.writable } /** * With this function we avoid that the internal Tag methods get overridden * @param { Object } data - options we want to use to extend the tag instance * @returns { Object } clean object without containing the riot internal reserved words */ function cleanUpData(data) { if (!(data instanceof Tag) && !(data && typeof data.trigger == T_FUNCTION)) return data var o = {} for (var key in data) { if (!contains(RESERVED_WORDS_BLACKLIST, key)) o[key] = data[key] } return o } /** * Walk down recursively all the children tags starting dom node * @param { Object } dom - starting node where we will start the recursion * @param { Function } fn - callback to transform the child node just found */ function walk(dom, fn) { if (dom) { // stop the recursion if (fn(dom) === false) return else { dom = dom.firstChild while (dom) { walk(dom, fn) dom = dom.nextSibling } } } } /** * Minimize risk: only zero or one _space_ between attr & value * @param { String } html - html string we want to parse * @param { Function } fn - callback function to apply on any attribute found */ function walkAttributes(html, fn) { var m, re = /([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g while (m = re.exec(html)) { fn(m[1].toLowerCase(), m[2] || m[3] || m[4]) } } /** * Check whether a DOM node is in stub mode, useful for the riot 'if' directive * @param { Object } dom - DOM node we want to parse * @returns { Boolean } - */ function isInStub(dom) { while (dom) { if (dom.inStub) return true dom = dom.parentNode } return false } /** * Create a generic DOM node * @param { String } name - name of the DOM node we want to create * @returns { Object } DOM node just created */ function mkEl(name) { return document.createElement(name) } /** * Replace the yield tag from any tag template with the innerHTML of the * original tag in the page * @param { String } tmpl - tag implementation template * @param { String } innerHTML - original content of the tag in the DOM * @returns { String } tag template updated without the yield tag */ function replaceYield(tmpl, innerHTML) { return tmpl.replace(/<(yield)\/?>(<\/\1>)?/gi, innerHTML || '') } /** * Shorter and fast way to select multiple nodes in the DOM * @param { String } selector - DOM selector * @param { Object } ctx - DOM node where the targets of our search will is located * @returns { Object } dom nodes found */ function $$(selector, ctx) { return (ctx || document).querySelectorAll(selector) } /** * Shorter and fast way to select a single node in the DOM * @param { String } selector - unique dom selector * @param { Object } ctx - DOM node where the target of our search will is located * @returns { Object } dom node found */ function $(selector, ctx) { return (ctx || document).querySelector(selector) } /** * Simple object prototypal inheritance * @param { Object } parent - parent object * @returns { Object } child instance */ function inherit(parent) { function Child() {} Child.prototype = parent return new Child() } /** * Get the name property needed to identify a DOM node in riot * @param { Object } dom - DOM node we need to parse * @returns { String | undefined } give us back a string to identify this dom node */ function getNamedKey(dom) { return getAttr(dom, 'id') || getAttr(dom, 'name') } /** * Set the named properties of a tag element * @param { Object } dom - DOM node we need to parse * @param { Object } parent - tag instance where the named dom element will be eventually added * @param { Array } keys - list of all the tag instance properties */ function setNamed(dom, parent, keys) { // get the key value we want to add to the tag instance var key = getNamedKey(dom), // add the node detected to a tag instance using the named property add = function(value) { // avoid to override the tag properties already set if (contains(keys, key)) return // check whether this value is an array var isArr = isArray(value) // if the key was never set if (!value) // set it once on the tag instance parent[key] = dom // if it was an array and not yet set else if (!isArr || isArr && !contains(value, dom)) { // add the dom node into the array if (isArr) value.push(dom) else parent[key] = [value, dom] } } // skip the elements with no named properties if (!key) return // check whether this key has been already evaluated if (tmpl.hasExpr(key)) // wait the first updated event only once parent.one('updated', function() { key = getNamedKey(dom) add(parent[key]) }) else add(parent[key]) } /** * Faster String startsWith alternative * @param { String } src - source string * @param { String } str - test string * @returns { Boolean } - */ function startsWith(src, str) { return src.slice(0, str.length) === str } /** * Function needed to inject in runtime the custom tags css */ var injectStyle = (function() { if (!window) return // skip injection on the server // create the style node var styleNode = mkEl('style'), placeholder = $('style[type=riot]') setAttr(styleNode, 'type', 'text/css') // inject the new node into the DOM -- in head if (placeholder) { placeholder.parentNode.replaceChild(styleNode, placeholder) placeholder = null } else document.getElementsByTagName('head')[0].appendChild(styleNode) /** * This is the function exported that will be used to update the style tag just created * innerHTML seems slow: http://jsperf.com/riot-insert-style * @param { String } css [description] */ return styleNode.styleSheet ? function (css) { styleNode.styleSheet.cssText += css } : function (css) { styleNode.innerHTML += css } })() /** * Mount a tag creating new Tag instance * @param { Object } root - dom node where the tag will be mounted * @param { String } tagName - name of the riot tag we want to mount * @param { Object } opts - options to pass to the Tag instance * @returns { Tag } a new Tag instance */ function mountTo(root, tagName, opts) { var tag = __tagImpl[tagName], // cache the inner HTML to fix #855 innerHTML = root._innerHTML = root._innerHTML || root.innerHTML // clear the inner html root.innerHTML = '' if (tag && root) tag = new Tag(tag, { root: root, opts: opts }, innerHTML) if (tag && tag.mount) { tag.mount() // add this tag to the virtualDom variable if (!contains(__virtualDom, tag)) __virtualDom.push(tag) } return tag } /** * Riot public api */ // share methods for other riot parts, e.g. compiler riot.util = { brackets: brackets, tmpl: tmpl } /** * Create a mixin that could be globally shared across all the tags */ riot.mixin = (function() { var mixins = {} /** * Create/Return a mixin by its name * @param { String } name - mixin name * @param { Object } mixin - mixin logic * @returns { Object } the mixin logic */ return function(name, mixin) { if (!mixin) return mixins[name] mixins[name] = mixin } })() /** * Create a new riot tag implementation * @param { String } name - name/id of the new riot tag * @param { String } html - tag template * @param { String } css - custom tag css * @param { String } attrs - root tag attributes * @param { Function } fn - user function * @returns { String } name/id of the tag just created */ riot.tag = function(name, html, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs if (/^[\w\-]+\s?=/.test(css)) { attrs = css css = '' } else attrs = '' } if (css) { if (isFunction(css)) fn = css else if (injectStyle) injectStyle(css) } __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn } return name } /** * Create a new riot tag implementation (for use by the compiler) * @param { String } name - name/id of the new riot tag * @param { String } html - tag template * @param { String } css - custom tag css * @param { String } attrs - root tag attributes * @param { Function } fn - user function * @param { string } [bpair] - brackets used in the compilation * @returns { String } name/id of the tag just created */ riot.tag2 = function(name, html, css, attrs, fn, bpair) { if (css && injectStyle) injectStyle(css) //if (bpair) riot.settings.brackets = bpair __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn } return name } /** * Mount a tag using a specific tag implementation * @param { String } selector - tag DOM selector * @param { String } tagName - tag implementation name * @param { Object } opts - tag logic * @returns { Array } new tags instances */ riot.mount = function(selector, tagName, opts) { var els, allTags, tags = [] // helper functions function addRiotTags(arr) { var list = '' each(arr, function (e) { list += ', *[' + RIOT_TAG + '="' + e.trim() + '"]' }) return list } function selectAllTags() { var keys = Object.keys(__tagImpl) return keys + addRiotTags(keys) } function pushTags(root) { var last if (root.tagName) { if (tagName && (!(last = getAttr(root, RIOT_TAG)) || last != tagName)) setAttr(root, RIOT_TAG, tagName) var tag = mountTo(root, tagName || root.getAttribute(RIOT_TAG) || root.tagName.toLowerCase(), opts) if (tag) tags.push(tag) } else if (root.length) each(root, pushTags) // assume nodeList } // ----- mount code ----- if (typeof tagName === T_OBJECT) { opts = tagName tagName = 0 } // crawl the DOM to find the tag if (typeof selector === T_STRING) { if (selector === '*') // select all the tags registered // and also the tags found with the riot-tag attribute set selector = allTags = selectAllTags() else // or just the ones named like the selector selector += addRiotTags(selector.split(',')) // make sure to pass always a selector // to the querySelectorAll function els = selector ? $$(selector) : [] } else // probably you have passed already a tag or a NodeList els = selector // select all the registered and mount them inside their root elements if (tagName === '*') { // get all custom tags tagName = allTags || selectAllTags() // if the root els it's just a single tag if (els.tagName) els = $$(tagName, els) else { // select all the children for all the different root elements var nodeList = [] each(els, function (_el) { nodeList.push($$(tagName, _el)) }) els = nodeList } // get rid of the tagName tagName = 0 } if (els.tagName) pushTags(els) else each(els, pushTags) return tags } /** * Update all the tags instances created * @returns { Array } all the tags instances */ riot.update = function() { return each(__virtualDom, function(tag) { tag.update() }) } /** * Export the Tag constructor */ riot.Tag = Tag /* istanbul ignore next */ /** * Compiler for riot custom tags * @version 2.3.0 */ /** * @module parsers */ var parsers = (function () { var _mods = {} function _try(name, req) { //eslint-disable-line no-redeclare switch (name) { case 'coffee': req = 'CoffeeScript' break case 'es6': req = 'babel' break default: if (!req) req = name break } return _mods[name] = window[req] } function _req(name, req) { return name in _mods ? _mods[name] : _try(name, req) } var _html = { jade: function (html) { return _req('jade').render(html, {pretty: true, doctype: 'html'}) } } var _css = { stylus: function (tag, css) { var stylus = _req('stylus'), nib = _req('nib') /* istanbul ignore next: can't run both */ return nib ? stylus(css).use(nib()).import('nib').render() : stylus.render(css) } } var _js = { none: function (js) { return js }, livescript: function (js) { return _req('livescript').compile(js, {bare: true, header: false}) }, typescript: function (js) { return _req('typescript')(js).replace(/\r\n?/g, '\n') }, es6: function (js) { return _req('es6').transform(js, { blacklist: ['useStrict', 'react'], sourceMaps: false, comments: false }).code }, babel: function (js) { return _req('babel').transform(js, { presets: ['es2015'], ast: false, sourceMaps: false, comments: false }).code }, coffee: function (js) { return _req('coffee').compile(js, {bare: true}) } } _js.javascript = _js.none _js.coffeescript = _js.coffee return {html: _html, css: _css, js: _js, _req: _req} })() riot.parsers = parsers /** * @module compiler */ var compile = (function () { var brackets = riot.util.brackets function _regEx(str, opt) { return new RegExp(str, opt) } var BOOL_ATTRS = _regEx( '^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|' + 'compact|controls|default|formnovalidate|hidden|inert|ismap|itemscope|loop|' + 'multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|' + 'selected|sortable|truespeed|typemustmatch)$'), RIOT_ATTRS = ['style', 'src', 'd'], VOID_TAGS = /^(?:input|img|br|wbr|hr|area|base|col|embed|keygen|link|meta|param|source|track)$/, HTML_ATTR = /\s*([-\w:\.\xA0-\xFF]+)\s*(?:=\s*('[^']+'|"[^"]+"|\S+))?/g, TRIM_TRAIL = /[ \t]+$/gm, _bp = null function q(s) { return "'" + (s ? s.replace(/\\/g, '\\\\').replace(/'/g, "\\'") : '') + "'" } function mktag(name, html, css, attrs, js, pcex) { var c = ', ', s = '}' + (pcex.length ? ', ' + q(_bp[8]) : '') + ');' if (/\S/.test(js)) { js = js.replace(/\n{3,}/g, '\n\n') if (js.slice(-1) !== '\n') s = '\n' + s } else js = '' return 'riot.tag2(' + q(name) + c + q(html) + c + q(css) + c + q(attrs) + ', function(opts) {\n' + js + s } function parseAttrs(str) { var list = [], match, k, v, DQ = '"' HTML_ATTR.lastIndex = 0 while (match = HTML_ATTR.exec(str)) { k = match[1].toLowerCase() v = match[2] if (!v) { list.push(k) } else { if (v[0] !== DQ) v = DQ + (v[0] === "'" ? v.slice(1, -1) : v) + DQ if (k === 'type' && v.toLowerCase() === '"number"') { v = DQ + _bp[0] + "'number'" + _bp[1] + DQ } else if (/\u0001\d/.test(v)) { if (BOOL_ATTRS.test(k)) { k = '__' + k } else if (~RIOT_ATTRS.indexOf(k)) { k = 'riot-' + k } } list.push(k + '=' + v) } } return list.join(' ') } function splitHtml(html, opts, pcex) { if (html && _bp[4].test(html)) { var jsfn = opts.expr && (opts.parser || opts.type) ? compileJS : 0, list = brackets.split(html), expr for (var i = 1; i < list.length; i += 2) { expr = list[i] if (expr[0] === '^') { expr = expr.slice(1) } else if (jsfn) { expr = jsfn(expr, opts).replace(/[\r\n]+/g, ' ').trim() if (expr.slice(-1) === ';') expr = expr.slice(0, -1) } list[i] = '\u0001' + (pcex.push(expr.trim()) - 1) + _bp[1] } html = list.join('') } return html } function restoreExpr(html, pcex) { if (pcex.length) { html = html .replace(/\u0001(\d+)/g, function (_, d) { return _bp[0] + pcex[d].replace(/"/g, '&quot;') }) } return html } var HTML_COMMENT = /<!--(?!>)[\S\s]*?-->/g, HTML_TAGS = /<([-\w]+)\s*([^"'\/>]*(?:(?:"[^"]*"|'[^']*'|\/[^>])[^'"\/>]*)*)(\/?)>/g function compileHTML(html, opts, pcex, intc) { if (!intc) { _bp = brackets.array(opts.brackets) html = html.replace(HTML_COMMENT, '').replace(TRIM_TRAIL, '') } if (!pcex) pcex = [] html = splitHtml(html, opts, pcex) .replace(HTML_TAGS, function (_, name, attr, ends) { name = name.toLowerCase() ends = ends && !VOID_TAGS.test(name) ? '></' + name : '' if (attr) name += ' ' + parseAttrs(attr) return '<' + name + ends + '>' }) html = opts.whitespace ? html.replace(/\r\n?|\n/g, '\\n') : html.trim().replace(/\s+/g, ' ') if (opts.compact) html = html.replace(/> <([-\w\/])/g, '><$1') return restoreExpr(html, pcex) } var JS_RMCOMMS = _regEx( '(' + brackets.S_QBLOCKS + ')|' + brackets.R_MLCOMMS.source + '|//[^\r\n]*', 'g'), JS_ES6SIGN = /^([ \t]*)([$_A-Za-z][$\w]*)\s*(\([^()]*\)\s*{)/m function riotjs(js) { var match, toes5, parts = [], pos js = js.replace(JS_RMCOMMS, function (m, q) { return q ? m : ' ' }) while (match = js.match(JS_ES6SIGN)) { parts.push(RegExp.leftContext) js = RegExp.rightContext pos = skipBlock(js) toes5 = !/^(?:if|while|for|switch|catch|function)$/.test(match[2]) if (toes5) match[0] = match[1] + 'this.' + match[2] + ' = function' + match[3] parts.push(match[0], js.slice(0, pos)) js = js.slice(pos) if (toes5 && !/^\s*.\s*bind\b/.test(js)) parts.push('.bind(this)') } return parts.length ? parts.join('') + js : js function skipBlock(str) { var re = _regEx('([{}])|' + brackets.S_QBLOCKS, 'g'), level = 1, match while (level && (match = re.exec(str))) { if (match[1]) match[1] === '{' ? ++level : --level } return level ? str.length : re.lastIndex } } function compileJS(js, opts, type) { if (!type) type = opts.type var parser = opts.parser || (type ? parsers.js[type] : riotjs) if (!parser) throw new Error('JS parser not found: "' + type + '"') return parser(js).replace(TRIM_TRAIL, '') } var CSS_SELECTOR = _regEx('(}|{|^)[ ;]*([^@ ;][^{}]*)(?={)|' + brackets.R_STRINGS.source, 'g') function scopedCSS(tag, style) { var scope = ':scope' return style.replace(CSS_SELECTOR, function (m, p1, p2) { if (!p2) return m p2 = p2.replace(/[^,]+/g, function (sel) { var s = sel.trim() if (s && s !== 'from' && s !== 'to' && s.slice(-1) !== '%') { if (s.indexOf(scope) < 0) s = scope + ' ' + s s = s.replace(scope, tag) + ',' + s.replace(scope, '[riot-tag="' + tag + '"]') } return sel.slice(-1) === ' ' ? s + ' ' : s }) return p1 ? p1 + ' ' + p2 : p2 }) } function compileCSS(style, tag, type, scoped) { if (type) { if (type === 'scoped-css') { scoped = true } else if (parsers.css[type]) { style = parsers.css[type](tag, style) } else if (type !== 'css') { throw new Error('CSS parser not found: "' + type + '"') } } style = style.replace(brackets.R_MLCOMMS, '').replace(/\s+/g, ' ').trim() return scoped ? scopedCSS(tag, style) : style } var TYPE_ATTR = /\stype\s*=\s*(?:['"]([^'"]+)['"]|(\S+))/i function getType(str) { if (str) { var match = str.match(TYPE_ATTR) str = match && (match[1] || match[2]) } return str ? str.replace('text/', '') : '' } function getCode(code, opts, attrs) { var type = getType(attrs) return compileJS(code, opts, type) } var END_TAGS = /\/>\n|<(?:\/[\w\-]+\s*|[\w\-]+(?:\s+(?:[-\w:\xA0-\xFF][\S\s]*?)?)?)>\n/g function splitBlocks(str) { var i, k, js = '', len = str.length k = str.indexOf('<') if (k < 0 || (i = str.lastIndexOf('>\n')) < 0 || k > i) return ['', str] i += 2 js = str.slice(i) str = str.slice(0, i) if (str[i - 3] !== '/') { if (str.match(END_TAGS)) { var s = RegExp.rightContext if (s) { js = s + js str = str.slice(0, len - js.length) } } else { js = str + js str = '' } } return [str, js] } function compileTemplate(lang, html) { var parser = parsers.html[lang] if (!parser) throw new Error('Template parser not found: "' + lang + '"') return parser(html) } var CUST_TAG = /^<([-\w]+)(?:\s+([^'"\/>]+(?:(?:"[^"]*"|'[^']*'|\/[^>])[^'"\/>]*)*)|\s*)?(?:\/>|>[ \t]*\n?([\s\S]*)^<\/\1\s*>|>(.*)<\/\1\s*>)/gim, STYLE = /<style(\s+[^>]*)?>\n?([^<]*(?:<(?!\/style\s*>)[^<]*)*)<\/style\s*>/gi, SCRIPT = _regEx(STYLE.source.replace(/tyle/g, 'cript'), 'gi') function compile(src, opts, url) { var label if (!opts) opts = {} _bp = brackets.array(opts.brackets) if (opts.template) src = compileTemplate(opts.template, src) label = url ? '//src: ' + url + '\n' : '' return label + src .replace(/\r\n?/g, '\n') .replace(CUST_TAG, function (_, tagName, attribs, body, body2) { var jscode = '', styles = '', html = '', pcex = [] tagName = tagName.toLowerCase() if (attribs) attribs = restoreExpr(parseAttrs(splitHtml(attribs, opts, pcex)), pcex) if (body2) body = body2 if (body && (body = body.replace(HTML_COMMENT, '')) && /\S/.test(body)) { if (body2) html = compileHTML(body2, opts, pcex, 1) else { body = body.replace(STYLE, function (_, _attrs, _style) { var scoped = _attrs && /\sscoped(\s|=|$)/i.test(_attrs) styles += (styles ? ' ' : '') + compileCSS(_style, tagName, getType(_attrs), scoped) return '' }) body = body.replace(SCRIPT, function (_, _attrs, _script) { jscode += (jscode ? '\n' : '') + getCode(_script, opts, _attrs) return '' }) var blocks = splitBlocks(body.replace(TRIM_TRAIL, '')) body = blocks[0] if (body) html = compileHTML(body, opts, pcex, 1) body = blocks[1] if (/\S/.test(body)) jscode += (jscode ? '\n' : '') + compileJS(body, opts) } } return mktag(tagName, html, styles, attribs, jscode, pcex) }) } return compile })() /* Compilation for the browser */ riot.compile = (function () { var doc = window.document, promise, ready function GET(url, fn, opts) { var req = new XMLHttpRequest() req.onreadystatechange = function() { if (req.readyState === 4 && (req.status === 200 || !req.status && req.responseText.length)) fn(req.responseText, opts, url) } req.open('GET', url, true) req.send('') } function unindent(src, dbg) { var indent = src.match(/^([ \t]*)</m) // only before first tag return indent && indent[1] ? src.replace(new RegExp('^' + indent[1], 'gm'), '') : src } function globalEval(js, opts, comp) { var node = doc.createElement('script'), root = doc.documentElement node.text = js root.appendChild(node) root.removeChild(node) } function compileScripts(fn) { var scripts = doc.querySelectorAll('script[type="riot/tag"]'), scriptsAmount = scripts.length function done() { promise.trigger('ready') ready = true if (fn) fn() } function compileTag(src, opts, url) { globalEval(compile(src, opts, url)) if (!--scriptsAmount) done() } if (!scriptsAmount) done() else { for (var i = 0; i < scripts.length; ++i) { var script = scripts[i], opts = {template: script.getAttribute('template')}, url = script.getAttribute('src') url ? GET(url, compileTag, opts) : compileTag(unindent(script.innerHTML), opts) } } } //// Entry point ----- return function (arg, fn) { if (typeof arg === 'string') { // fix in both, compile was called here and in globalEval if (/^\s*</.test(arg)) { var js = compile(unindent(arg)) // fix: pass unindented src to compile, don't fake test if (!fn) globalEval(js) return js } GET(arg, function (str) { var js = compile(str, {}, arg) globalEval(js) if (fn) fn(js, str) }) } else { // must be a function fn = typeof arg !== 'function' ? undefined : arg // all compiled if (ready) return fn && fn() // add to queue if (promise) { if (fn) promise.on('ready', fn) // grab riot/tag elements + load & execute them } else { promise = riot.observable() compileScripts(fn) } } } })() // reassign mount methods var mount = riot.mount riot.mount = function(a, b, c) { var ret riot.compile(function() { ret = mount(a, b, c) }) return ret } // support CommonJS, AMD & browser /* istanbul ignore next */ if (typeof exports === T_OBJECT) module.exports = riot else if (typeof define === 'function' && define.amd) define(function() { return (window.riot = riot) }) else window.riot = riot })(typeof window != 'undefined' ? window : void 0);
ajax/libs/milojs/0.2.0/milo.min.js
cdnjs/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);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.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){"use strict";function c(a,b){this.name=d.firstLowerCase(this.constructor.name),this.owner=a,this.config=b||{},this.init.apply(this,arguments)}var d=a("milo-core").proto;b.exports=c,d.extendProto(c,{init:function(){}})},{"milo-core":105}],2:[function(a,b){"use strict";function c(){function a(a,c){var f=b[c];e[c]=new a(this,f),d[c]={enumerable:!0,value:e[c]}}var b=this.facetsConfig||{},d={},e={};if(this.constructor==c)throw new Error("FacetedObject is an abstract class, can't be instantiated");this.facetsClasses&&j.eachKey(this.facetsClasses,a,this,!0),Object.defineProperties(this,d),j.defineProperty(this,"facets",e),this.init&&this.init.apply(this,arguments)}function d(a,b,c,d){k(a,Function),k(c,l.Optional(String)),c=j.firstLowerCase(c||a.name);var e=this.constructor.prototype.facetsClasses;if(e&&e[c])throw new Error("facet "+c+" is already part of the class "+this.constructor.name);if(this[c]){var f="facet "+c+" is already present in object";if(d===!1)return logger.error("FacetedObject addFacet: ",f);throw new Error(f)}var g=this.facets[c]=new a(this,b);return j.defineProperty(this,c,g,j.ENUM),g}function e(a){var b=this.prototype.facetsClasses;return b&&b[a]}function f(a){return this.hasFacet(a)?this.prototype.facetsConfig[a]:null}function g(a,b,c){function d(a,b,c){var d=a.prototype[c];return d?j(d).clone().extend(b||{})._():b}k(a,String),k(b,l.Optional(l.ObjectHash(l.Subclass(h,!0)))),k(c,l.Optional(Object)),c&&j.eachKey(c,function(a,c){if(!b.hasOwnProperty(c))throw new Error("configuration for facet ("+c+") passed that is not in class")});var e=j.createSubclass(this,a,!0);return b=d(this,b,"facetsClasses"),c=d(this,c,"facetsConfig"),j.extendProto(e,{facetsClasses:b,facetsConfig:c}),e}var h=a("./facet"),i=a("milo-core"),j=i.proto,k=i.util.check,l=k.Match;b.exports=c,j.extend(c,{createFacetedClass:g,hasFacet:e,getFacetConfig:f}),j.extendProto(c,{addFacet:d})},{"./facet":1,"milo-core":105}],3:[function(a,b){"use strict";function c(a){a&&this.setClass(a),this.__registeredClasses={}}function d(a,b){if(b=b||a.name,k(b,l.IdentifierString,"class name must be identifier string"),!this.FoundationClass)throw new Error("foundation class must be set before adding classes to registry");if(a!=this.FoundationClass&&k(a,l.Subclass(this.FoundationClass),"class must be a sub(class) of a foundation class"),this.__registeredClasses[b])throw new Error('class "'+b+'" is already registered');this.__registeredClasses[b]=a}function e(a){return k(a,String,"class name must be string"),this.__registeredClasses[a]}function f(a){k(a,l.OneOf(String,Function),"class or name must be supplied");var b="string"==typeof a?a:a.name;if(!this.__registeredClasses[b])throw new Error("class is not registered");delete this.__registeredClasses[b]}function g(){this.__registeredClasses={}}function h(a){k(a,Function),j.defineProperty(this,"FoundationClass",a,j.ENUM)}var i=a("milo-core"),j=i.proto,k=i.util.check,l=k.Match;b.exports=c,j.extendProto(c,{add:d,get:e,remove:f,clean:g,setClass:h})},{"milo-core":105}],4:[function(a,b){"use strict";function c(){return i.attrs.bind}function d(){if(this.node){var a=this.get();if(a)var b=a.match(n);if(!b)throw new Error("invalid bind attribute "+a);return this.compClass=b[1]||"Component",this.compFacets=b[2]&&b[2].split(o)||void 0,this.compName=b[3]||void 0,this}}function e(){if(l(this.compName,m.IdentifierString),!this.compClass)throw new Error("empty component class name "+this.compClass);return this}function f(){return this.compName=this.compName||milo.util.componentName(),p.replace("%compClass",this.compClass||"").replace("%compFacets",this.compFacets&&this.compFacets.length?"["+this.compFacets.join(", ")+"]":"").replace("%compName",this.compName)}function g(a,b,c,d){var e=new q(a);k.extend(e,{compClass:b,compName:c,compFacets:d}),e.decorate()}var h=a("./a_class"),i=a("../config"),j=a("milo-core"),k=j.proto,l=j.util.check,m=l.Match,n=/^([^\:\[\]]*)(?:\[([^\:\[\]]*)\])?\:?([^:]*)$/,o=/\s*(?:\,|\s)\s*/,p="%compClass%compFacets:%compName",q=k.createSubclass(h,"BindAttribute",!0);k.extendProto(q,{attrName:c,parse:d,validate:e,render:f}),k.extend(q,{setInfo:g}),b.exports=q},{"../config":64,"./a_class":5,"milo-core":105}],5:[function(a,b){"use strict";function c(a,b){this.name=b||this.attrName(),this.el=a,this.node=a.attributes[this.name]}function d(a,b){var c=this.prototype.attrName();if(a.removeAttribute(c),b){var d="["+c+"]",e=a.querySelectorAll(d);l.forEach(e,function(a){a.removeAttribute(c)})}}function e(){delete this.node}function f(){delete this.el,delete this.node}function g(){return this.el.getAttribute(this.name)}function h(a){this.el.setAttribute(this.name,a)}function i(){this.set(this.render())}function j(){throw new Error("calling the method of an absctract class")}{var k=a("milo-core"),l=k.proto,m=k.util.check;m.Match}b.exports=c,l.extend(c,{remove:d}),l.extendProto(c,{get:g,set:h,remove:e,decorate:i,destroy:f,attrName:j,parse:j,validate:j,render:j})},{"milo-core":105}],6:[function(a,b){"use strict";function c(){return h.attrs.load}function d(){return this.node?(this.loadUrl=this.get(),this):void 0}function e(){return this}function f(){return this.loadUrl}var g=a("./a_class"),h=a("../config"),i=a("milo-core").proto,j=i.createSubclass(g,"LoadAttribute",!0);i.extendProto(j,{attrName:c,parse:d,validate:e,render:f}),b.exports=j},{"../config":64,"./a_class":5,"milo-core":105}],7:[function(a,b){"use strict";b.exports={bind:a("./a_bind"),load:a("./a_load")}},{"./a_bind":4,"./a_load":6}],8:[function(a,b){"use strict";function c(a,b,c,d){return g(a,function(a,b,c,d){var e=new j(a,b,c,d);return i.create(e,d)},b,c,d)}function d(a,b,d,e){var f=c.scan(a,b,d,e);return c.create(f,void 0,e)}function e(a,b,c,d){return g(a,function(a,b,c,d){return new j(a,b,c,d)},b,c,d)}function f(a,b,c){var d=new k(a._rootEl,b),e=c===!1?"_safeAdd":"_add";return a._each(function(a){var b=n.clone(a);b.scope=d;var g=i.create(b,c);d[e](g,g.name),g.container&&(g.container.scope=f(a.container.scope,g.container,c))}),d}function g(a,b,c,d,e){function f(a,c,d){function f(a){var b=i.getComponent(a);b&&b.postMessageSync("childrenbound")}var h=new l(c);if(h.node&&d!==!1)var m=b(a,c,h,e),n="undefined"!=typeof m&&m.container;if(c.childNodes&&c.childNodes.length){if(n){var o=new k(c);m.container.scope=o,o._hostObject=m.container}g(c,n?o:a)}return n&&!m.container.scope&&(m.container.scope=new k(c)),m&&a[j](m,h.compName),f(c),m}function g(a,b){var c=p.children(a);return n.forEach(c,function(a){f(b,a,!0)}),b}var a=a||document.body,h=c||new k(a),j=e===!1?"_safeAdd":"_add";return f(h,a,d),h}{var h=(a("./services/mail"),a("./components/c_registry")),i=(a("./components/c_facets/cf_registry"),h.get("Component")),j=a("./components/c_info"),k=a("./components/scope"),l=a("./attributes/a_bind"),m=a("milo-core"),n=m.proto,o=m.util.check,p=a("./util/dom");o.Match}c.scan=e,c.create=f,c.twoPass=d,b.exports=c},{"./attributes/a_bind":4,"./components/c_facets/cf_registry":30,"./components/c_info":31,"./components/c_registry":32,"./components/scope":40,"./services/mail":70,"./util/dom":79,"milo-core":105}],9:[function(a,b){"use strict";var c=a("milo-core").classes,d={Facet:a("./abstract/facet"),FacetedObject:a("./abstract/faceted_object"),Scope:a("./components/scope"),ClassRegistry:a("./abstract/registry"),Mixin:c.Mixin,MessageSource:c.MessageSource,MessengerMessageSource:c.MessengerMessageSource,MessengerAPI:c.MessengerAPI,DOMEventsSource:a("./components/msg_src/dom_events"),Transaction:a("./command/transaction"),TransactionHistory:a("./command/transaction_history")};b.exports=d},{"./abstract/facet":1,"./abstract/faceted_object":2,"./abstract/registry":3,"./command/transaction":13,"./command/transaction_history":14,"./components/msg_src/dom_events":38,"./components/scope":40,"milo-core":105}],10:[function(a,b){"use strict";function c(a){this._maxLength=a||1/0,this.actions=[],this.position=0}function d(a){if(f.call(this),this.actions.push(a),this.actions.length>this._maxLength){var b=this.actions.shift();b.destroy()}return this.position=this.actions.length,this.position-1}function e(){this.actions.length&&(this.position--,this.actions.length--)}function f(){for(var a=this.position;a<this.actions.length;a++)this.actions[a].destroy();this.actions.length=this.position}function g(a){if(0!=this.position){var b=this.actions[--this.position];return b.undo(a),b}}function h(a){if(this.position!=this.actions.length){var b=this.actions[this.position++];return b.redo(a),b}}function i(){for(;this.position;)this.undo()}function j(){for(;this.position<this.actions.length;)this.redo()}function k(a){this.position&&(this.undo(),this.position?r.deferMethod(this,"undoAllAsync",a):a&&r.defer(a))}function l(a){this.position<this.actions.length&&(this.redo(),this.position<this.actions.length?r.deferMethod(this,"redoAllAsync",a):a&&r.defer(a))}function m(a,b){var c="string"==typeof a?function(b){b[a]()}:a;this.actions.forEach(c,b||this)}function n(a,b){this.actions.reverse(),this.each(a,b),this.actions.reverse()}function o(){return this.position&&this.actions[this.position-1]}function p(){var a=this.actions.map(function(a){return a.getDescription()});return{actions:a,position:this.position,length:a.length}}{var q=a("milo-core"),r=q.proto;q.util.logger}b.exports=c,r.extendProto(c,{store:d,deleteLast:e,undo:g,redo:h,undoAll:i,redoAll:j,undoAllAsync:k,redoAllAsync:l,each:m,eachReverse:n,getLastAction:o,getDescription:p})},{"milo-core":105}],11:[function(a,b){"use strict";var c=a("../abstract/registry"),d=a("./index"),e=new c(d);e.add(d),b.exports=e},{"../abstract/registry":3,"./index":12}],12:[function(a,b){"use strict";function c(){this.init.apply(this,arguments)}function d(a){t(a,u.Optional(Function)),this.func=a||function(){},this.args=s.slice(arguments,1)}function e(a){var b=this.func.apply(this,this.args);return a&&s.defer(a),b}function f(a){this[w]&&v.warn("Command setUndo: undo command is already set"),this[w]=a,a[w]=this}function g(){return this[w]}function h(a){var b=this.getUndo();if(!b)return v.error("Command undo called without undo command present");var c=b.execute();return a&&s.defer(a),c}function i(){this.args&&this.args.length&&v.warn("Command setArguments: command arguments are already set"),this.args=s.toArray(arguments)}function j(){return this.args}function k(){this.args=s.toArray(arguments)}function l(){this.args||(this.args=[]),s.appendArray(this.args,arguments)}function m(){return s.newApply(this,arguments)}function n(){throw new Error("createWithUndo should be implemented by subsclass")}function o(){delete this.func,delete this.args;var a=this[w];a&&(delete this[w][w],delete this[w],a.destroy())}function p(a){this.comment=a}function q(){return{func:this.func.name,comment:this.comment}}var r=a("milo-core"),s=r.proto,t=r.util.check,u=t.Match,v=r.util.logger,w="_undoCommand";b.exports=c,s.extendProto(c,{init:d,execute:e,setUndo:f,getUndo:g,undo:h,redo:e,setArguments:i,addArguments:l,getArguments:j,changeArguments:k,destroy:o,setComment:p,getDescription:q}),s.extend(c,{create:m,createWithUndo:n})},{"milo-core":105}],13:[function(a,b){"use strict";function c(){this.commands=new l}function d(){this.commands.each("execute")}function e(a){this.commands.undoAllAsync(a)}function f(a){this.commands.redoAllAsync(a)}function g(){this.commands.each("destroy")}function h(a){this.commands.store(a)}function i(a){a.commands.each(function(a){this.commands.store(a)},this)}function j(a){this.comment=a}function k(){var a=this.commands.getDescription();return{commands:a.actions,comment:this.comment}}var l=a("./actions_history"),m=a("milo-core").proto;b.exports=c,m.extendProto(c,{execute:d,undo:e,redo:f,destroy:g,storeCommand:h,merge:i,setComment:j,getDescription:k})},{"./actions_history":10,"milo-core":105}],14:[function(a,b){"use strict";function c(a){this.transactions=new r(a),this.currentBatch=void 0,this.currentTransaction=void 0,this[w]=!1}function d(a,b){if(b&&!this.currentTransaction&&!this.currentBatch){var c=this.transactions.getLastAction();return c.storeCommand(a),void k.call(this,"appended",c)}this.currentBatch||(this.currentBatch=new s),this.currentBatch.storeCommand(a),this[w]||(this[w]=!0,v.deferMethod(this,f))}function e(){this.currentBatch||this.currentTransaction?(this.currentBatch=void 0,this.currentTransaction=void 0):this.transactions.deleteLast()}function f(){this.currentBatch?(h.call(this),v.deferMethod(this,f)):(i.call(this),this[w]=!1)}function g(){h.call(this),i.call(this)}function h(){this.currentBatch&&(this.currentTransaction||(this.currentTransaction=new s),this.currentTransaction.merge(this.currentBatch),this.currentBatch=void 0)}function i(){if(this.currentTransaction){var a=this.currentTransaction;this.transactions.store(a),k.call(this,"stored",a),this.currentTransaction=void 0}}function j(a){this.endTransaction(),this.transactions.store(a),k.call(this,"stored",a)}function k(a,b){this._messenger&&this._messenger.postMessage(a,{transaction:b})}function l(a){var b=this.transactions.undo(a);return b&&k.call(this,"undone",b),b}function m(a){var b=this.transactions.redo(a);return b&&k.call(this,"redone",b),b}function n(){return this[w]}function o(){return this.transactions.getDescription()}function p(){return this._messenger=new u(this,u.defaultMethods)}function q(){this._messenger&&this._messenger.destroy(),delete this.transactions}var r=a("./actions_history"),s=a("./transaction"),t=a("milo-core"),u=(t.util.logger,t.Messenger),v=t.proto;b.exports=c;var w="_scheduled";v.extendProto(c,{storeCommand:d,endTransaction:g,storeTransaction:j,deleteLastTransaction:e,undo:l,redo:m,inTransaction:n,getDescription:o,useMessenger:p,destroy:q})},{"./actions_history":10,"./transaction":13,"milo-core":105}],15:[function(a,b){"use strict";function c(a,b){if(Array.isArray(b)){var c={};b.forEach(function(a){var b=X.firstLowerCase(a);c[b]={}}),b=c}var e;"object"==typeof b&&X.keys(b).length&&(e={},X.eachKey(b,function(a,b){var c=X.firstLowerCase(b),d=X.firstUpperCase(b);e[c]=S.get(d)}));var f=R.createFacetedClass.call(this,a,e,b);return d(a),f}function d(a){eb.registerDataType(a,e,f)}function e(a){var b=a.getState();return JSON.stringify(b)}function f(a){var b=X.jsonParse(a);return b?fb.createFromState(b):void 0}function g(a,b){var c=a.ComponentClass;if("function"!=typeof c){var d='create: component class should be function, "'+typeof c+'" passed';if(b!==!1)throw new Error(d);ab.error("Component",d,";using base Component class instead"),c=fb}var e=new c(a.scope,a.el,a.name,a);return a.extraFacetsClasses&&X.eachKey(a.extraFacetsClasses,function(a){e.hasFacet(a)||e.addFacet(a,void 0,void 0,b)}),e}function h(a,b){if(Y(a,fb),Y(b,Z.Optional(Boolean)),b&&!a.container)throw new Error("Cannot deep copy component without container facet");var c=a.dom?a.dom.copy(b):a.el.cloneNode(b),d=a.constructor,e=d.createOnElement(c,void 0,a.scope,a.extraFacets),f=a._getState(b||!1);return e.setState(f),X.deferMethod(e,"broadcast","stateready"),e}function i(a,b,c,d){Y(b,Z.Optional(String)),Y(c,Z.Optional(db)),Y(d,Z.Optional([String])),a&&b&&(a.innerHTML=b),a=a||j.call(this,b),c=c||k(a);var e=l.call(this,a,c,d);return e.broadcast("stateready"),e}function j(a){var b=S.get("Dom"),c=this.getFacetConfig("dom"),d=this.getFacetConfig("template"),e=d&&d.template,f={domConfig:c,template:e,content:a};return b.createElement(f)}function k(a){var b=fb.getContainingComponent(a,!1,"Container");return b?b.container.scope:new db(a)}function l(b,c,d){var e=new cb(b);e.compClass=this.name,e.compFacets=d,e.decorate();var f=a("../binder");return f(b,c),c[e.compName]}function m(b,c,d,e){Y(b,Z.ObjectIncluding({compName:Z.Optional(String),compClass:Z.Optional(String),extraFacets:Z.Optional([String]),facetsStates:Z.Optional(Object),outerHTML:String}));var f=a("../binder"),g=n(b,d),h=f(g,void 0,void 0,e),i=h._any();return c&&(i.scope=c,c._add(i)),i.setState(b),X.deferMethod(i,"broadcast","stateready"),i}function n(a,b){var c=document.createElement("div");c.innerHTML=a.outerHTML;var d=bb.children(c);if(1!=d.length)throw new Error("cannot create component: incorrect HTML, elements number: "+d.length+" (should be 1)");var e=d[0],f=new cb(e);return f.compName=b?_():a.compName,f.compClass=a.compClass,f.compFacets=a.extraFacets,f.decorate(),c}function o(a){var b=X.find(a.types,function(a){return hb.test(a)});if(b){var c=X.jsonParse(a.getData(b));if(c)return fb.createFromState(c,void 0,!0)}}function p(a,b,c,d){if(this.el=b||this.createElement(),this.el){var e=this.el[$.componentRef];e&&ab.warn("component "+c+" attached to element that already has component "+e.name),this.el[$.componentRef]=this}X.defineProperties(this,{componentInfo:d,extraFacets:[]},X.ENUM),this.name=c,this.scope=a;var f=new W(this);X.defineProperty(this,gb,f),this.allFacets("check"),this.allFacets("start"),this.start&&this.start()}function q(){}function r(){return"undefined"!=typeof document?(this.el=this.dom?this.dom.createElement():document.createElement("DIV"),this.el):void 0}function s(a){var b=X.firstLowerCase("function"==typeof a?a.name:a),c=this[b];return!c instanceof T&&ab.warn("expected facet",b,"but this property name is used for something else"),!!c}function t(a,b,c,d){Y(a,Z.OneOf(String,Z.Subclass(T))),Y(b,Z.Optional(Object)),Y(c,Z.Optional(String));var e;if("string"==typeof a){var f=X.firstUpperCase(a);e=S.get(f)}else e=a;c||(c=X.firstLowerCase(e.name)),this.extraFacets.push(c);var g=R.prototype.addFacet.call(this,e,b,c,d);g.check&&g.check(),g.start&&g.start()}function u(a){var b=X.slice(arguments,1);return X.mapKeys(this.facets,function(c){return c&&"function"==typeof c[a]?c[a].apply(c,b):void 0})}function v(a,b){a=a||_(),this.componentInfo.rename(a,!1),db.rename(this,a,b)}function w(a,b){this.scope&&(this.scope._remove(this.name,b),a||delete this.scope)}function x(a,b){a.insertBefore(this.el,b),this.setScopeParentFromDOM()}function y(){this.broadcast("getstatestarted",{rootComponent:this},void 0,!0);var a=this._getState(!0);return a.outerHTML=this.el.outerHTML,X.deferMethod(this,"broadcast","getstatecompleted",{rootComponent:this},void 0,!0),a}function z(a){return this.transfer?this.transfer.getState(a):this.getState(a)}function A(a){var b=this.allFacets("getState",a===!1?!1:!0);return b=X.filterKeys(b,function(a){return!!a}),{compName:this.name,compClass:this.constructor.name,extraFacets:this.extraFacets,facetsStates:b}}function B(a){a.facetsStates&&X.eachKey(a.facetsStates,function(a,b){var c=this[b];c&&"function"==typeof c.setState&&c.setState(a)},this)}function C(a){return D.call(this,E,a)}function D(a,b){Y(b,Z.Optional(Z.OneOf(Function,String)));var c=U._makeComponentConditionFunc(b);return a.call(this,c)}function E(a){var b;try{b=this.scope._hostObject.owner}catch(c){}return b?!a||a(b)?b:E.call(b,a):void 0}function F(a){return a=a||this.constructor,E.call(this,function(b){return b instanceof a})}function G(a){return D.call(this,H,a)}function H(a){var b,c=this;do c=E.call(c,a),c&&(b=c);while(c);return b}function I(a){return a=a||this.constructor,H.call(this,function(b){return b instanceof a})}function J(){for(var a,b,c=this.el.parentNode;c&&!b;)a=fb.getComponent(c),b=a&&a.container,c=c.parentNode;return this.remove(),b?(this.rename(void 0,!1),a.container.scope._add(this),a):void 0}function K(a,b){a.call(b,this),this.container&&this.container.scope._each(function(c){c.walkScopeTree(a,b)})}function L(a){return bb.treePathOf(this.el,a.el)}function M(a,b){var c=bb.getNodeAtTreePath(this.el,a,b);return fb.getComponent(c)}function N(a,b){var c=bb.insertAtTreePath(this.el,a,b.el);return c&&b.setScopeParentFromDOM(),c}function O(a,b,c,d){var e=d?"postMessageSync":"postMessage";this.walkScopeTree(function(d){d[e](a,b,c)})}function P(a){return this._destroyed?void(a||ab.warn("Component destroy: component is already destroyed")):(this.remove(!1,a),this.allFacets("destroy"),this[gb].destroy(),this.el&&(bb.detachComponent(this.el),bb.removeElement(this.el),delete this.el),this.componentInfo.destroy(),void(this._destroyed=!0))}function Q(){return this._destroyed}var R=a("../abstract/faceted_object"),S=a("./c_facets/cf_registry"),T=S.get("ComponentFacet"),U=a("./c_utils"),V=a("milo-core"),W=V.Messenger,X=V.proto,Y=V.util.check,Z=Y.Match,$=a("../config"),_=a("../util/component_name"),ab=V.util.logger,bb=a("../util/dom"),cb=a("../attributes/a_bind"),db=a("./scope"),eb=a("../util/storage"),fb=(U._makeComponentConditionFunc,X.createSubclass(R,"Component",!0));b.exports=fb,d("Component"),X.extend(fb,{createComponentClass:c,create:g,copy:h,createOnElement:i,isComponent:U.isComponent,getComponent:U.getComponent,getContainingComponent:U.getContainingComponent,createFromState:m,createFromDataTransfer:o}),delete fb.createFacetedClass,X.extendProto(fb,{init:p,start:q,createElement:r,hasFacet:s,addFacet:t,allFacets:u,rename:v,remove:w,insertInto:x,getState:y,getTransferState:z,_getState:A,setState:B,getScopeParent:C,getTopScopeParent:G,getScopeParentWithClass:F,getTopScopeParentWithClass:I,setScopeParentFromDOM:J,walkScopeTree:K,treePathOf:L,getComponentAtTreePath:M,insertAtTreePath:N,broadcast:O,destroy:P,isDestroyed:Q});var gb="_messenger";W.useWith(fb,gb,W.defaultMethods);var hb=/x-application\/milo-component\/([a-z_$][0-9a-z_$]*)(?:\/())/i},{"../abstract/faceted_object":2,"../attributes/a_bind":4,"../binder":8,"../config":64,"../util/component_name":76,"../util/dom":79,"../util/storage":89,"./c_facets/cf_registry":30,"./c_utils":33,"./scope":40,"milo-core":105}],16:[function(a,b){"use strict";function c(){this._createMessenger()}function d(){v.defineProperty(this,z,new t(this))}function e(){this.config.messages&&this.onConfigMessages(this.config.messages)}function f(a){var b=v.mapKeys(a,function(a,b){var c=typeof a;if("function"==c)return this.on(b,a);if("object"==c){var d=typeof a.context;if("object"==d)return this.on(b,a);if("string"==d){if(a.context==this.name||"facet"==a.context)a={subscriber:a.subscriber,context:this};else{if("owner"!=a.context)throw new Error("unknown subscriber context in configuration: "+a.context);a={subscriber:a.subscriber,context:this.owner}}return this.on(b,a)}throw new Error("unknown subscriber context type in configuration: "+d)}throw new Error("unknown subscriber type in configuration: "+c)},this);return b}function g(){this.require&&this.require.forEach(function(a){this.owner.hasFacet(a)||this.owner.addFacet(a)},this)}function h(){this[z]&&this[z].destroy(),this._destroyed=!0}function i(){var a=u.getContainingComponent(this.owner.el,!1,this.name);return a&&a[this.name]}function j(){var a=this.owner.getScopeParent(this.name);return a&&a[this.name]}function k(a,b,c){var d=a.call(this);d&&d.postMessage(b,c)}function l(a){this[z]._setMessageSource(a)}function m(){return this[z].getMessageSource()}function n(a,b){return this.getMessageSource().dispatchMessage(a,b)}function o(a,b){var c=new a(this,void 0,void 0,this.owner,b);this._setMessageSource(c),v.defineProperty(this,"_messageSource",c)}function p(a,b,c){var d=new a(this,void 0,b,this.owner,c);this._setMessageSource(d),v.defineProperty(this,"_messageSource",d)}function q(a){var b=this.prototype.require;return b&&(b.indexOf(v.firstUpperCase(a))>=0||b.indexOf(v.firstLowerCase(a))>=0)}var r=a("../abstract/facet"),s=a("milo-core"),t=s.Messenger,u=a("./c_utils"),v=s.proto,w=v.createSubclass(r,"ComponentFacet");b.exports=w;var x=v.partial(k,i),y=v.partial(k,j);v.extendProto(w,{init:c,start:e,check:g,destroy:h,onConfigMessages:f,domParent:i,postDomParent:x,scopeParent:j,postScopeParent:y,getMessageSource:m,dispatchSourceMessage:n,_createMessenger:d,_setMessageSource:l,_createMessageSource:o,_createMessageSourceWithAPI:p}),v.extend(w,{requiresFacet:q});var z="_messenger";t.useWith(w,z,t.defaultMethods)},{"../abstract/facet":1,"./c_utils":33,"milo-core":105}],17:[function(a,b){"use strict";function c(){return n(this.owner.el,this.scope,!1)}function d(){m.prototype.start.apply(this,arguments),this.scope=new o(this.owner.el,this)}function e(a){function b(){throw new Error("path "+a+" is invalid")}a=a.split(".");var c=a.length;(a[0]||2>c)&&b();for(var d=this.owner,e=1;c>e;e++){var f=a[e];if(v.test(f)||b(),!d.container)return;if(d=d.container.scope[f],!d)return}return d}function f(a){var b={scope:{}};return a!==!1&&this.scope._each(function(a,c){b.scope[c]=a._getState()}),b}function g(a){q.eachKey(a.scope,function(a,b){var c=this.scope[b];c?c.setState(a):r.warn('component "'+b+'" does not exist on scope')},this)}function h(){this.scope._each(function(a){a.destroy()}),this.scope._detachElement(),m.prototype.destroy.apply(this,arguments)}function i(a,b){t.unwrapElement(this.owner.el),this.scope&&this.scope._each(function(b){b.remove(),a!==!1&&b.rename(void 0,!1),this.owner.scope&&this.owner.scope._add(b)},this),b!==!1&&this.owner.destroy()}function j(a){this.scope._add(a),this.owner.el.appendChild(a.el)}function k(a,b){this.scope._add(a),this.el.insertBefore(a.el,b&&b.el)}function l(a){this.scope._remove(a),this.owner.el.removeChild(a.el)}var m=a("../c_facet"),n=a("../../binder"),o=a("../scope"),p=a("milo-core"),q=p.proto,r=p.util.logger,s=a("./cf_registry"),t=a("../../util/dom"),u=q.createSubclass(m,"Container");q.extendProto(u,{start:d,path:e,getState:f,setState:g,binder:c,destroy:h,unwrap:i,append:j,insertBefore:k,remove:l}),s.add(u),b.exports=u;var v=/^[A-Za-z][A-Za-z0-9\_\$]*$/},{"../../binder":8,"../../util/dom":79,"../c_facet":16,"../scope":40,"./cf_registry":30,"milo-core":105}],18:[function(a,b){"use strict";function c(){J.wrapMessengerMethods.call(this),D.prototype.start.apply(this,arguments),this.elData=H(this.owner.el),this._dataChangesQueue=[],this._prepareMessageSource(),this._path="."+this.owner.name,this._value=this.get(),this.onSync("",e),this.onSync("datachangesfinished",h),this.onSync("childdata",j),this.onSync("changedata",L)}function d(){var a=new G(this.owner),b=new F(this,S,a,this.owner);this._setMessageSource(b),P.defineProperty(this,"_dataEventsSource",b),C.prototype._createProxyMethod.call(a,"value","value",this)}function e(a,b){if(this._bubbleUpDataChange(b),this._queueDataChange(b),""===b.path){var c=M(b);this.postMessage("datachangesfinished",{transaction:c})}}function f(a){var b=this.scopeParent();if(b){var c=P.clone(a);c.path=(this._path||"."+this.owner.name)+c.path,b.postMessage("childdata",c||a)}}function g(a){this._dataChangesQueue.push(a)}function h(a,b){this._postDataChanges(b.inTransaction);var c=this.scopeParent();c&&c.postMessage("datachangesfinished",b)}function i(a){var b=this._dataChangesQueue.reverse();this.postMessageSync("datachanges",{changes:b,transaction:a}),this._dataChangesQueue=[]}function j(a,b){this.postMessage(b.path,b),this._bubbleUpDataChange(b),this._queueDataChange(b)}function k(a){var b=M(k),c=this.config.set;if("function"==typeof c){var d=c.call(this.owner,a);return d}N(this._set,b);var e=this._value,f=this._set(a),g={path:"",type:"changed",newValue:f,oldValue:e};return N(g,b),this.postMessage("",g),f}function l(a){function b(a,b,c,e){var f=e.replace("$$",c),g=this.path(f,"undefined"!=typeof b);g&&(N(g.set,d),a[c]=g.set(b))}var c,d=M(l);if(null!=a&&"object"==typeof a)if(Array.isArray(a)){c=[];var e=this.owner.list;if(e){var f=e.count(),g=a.length-f;g>=3&&(e._addItems(g),e._updateDataPaths(f,e.count())),a.forEach(function(a,d){b.call(this,c,a,d,"[$$]")},this);for(var h=e.count(),i=h-a.length;i-->0;)e._removeItem(a.length)}else Q.warn("Data: setting array data without List facet")}else c={},P.eachKey(a,function(a,d){b.call(this,c,a,d,".$$")},this);else c=this._setScalarValue(a);return this._value=c,c}function m(){var a=M(m),b=this.config.del;if("function"==typeof b){var c=b.call(this.owner);return O.call(this,a),c}var d=this._value;N(this._del,a),this._del();var e={path:"",type:"deleted",oldValue:d};N(e,a),this.postMessage("",e)}function n(){var a=M(n);N(this._set,a),this._set()}function o(a){return this.elData.set(this.owner.el,a)}function p(a){var b=this.config.get;return"function"==typeof b?b.call(this.owner,a):this._get(a)}function q(a){if(a!==!1){var b,c=this.owner;return c.list?(b=[],c.list.each(function(a,c){b[c]=a.data.get()}),c.container&&c.container.scope._each(function(a,d){!c.list.contains(a)&&a.data&&(b[d]=a.data.get())})):c.container?(b={},c.container.scope._each(function(a,c){a.data&&(b[c]=a.data.get())})):b=this._getScalarValue(),this._value=b,b}}function r(){return this.elData.get(this.owner.el)}function s(){var a,b=M(s),c=this.config.splice;if("function"==typeof c)return a=c.apply(this.owner,arguments),O.call(this,b),a;if(N(this._splice,b),a=this._splice.apply(this,arguments)){var d={path:"",type:"splice",index:a.spliceIndex,removed:a.removed,addedCount:a.addedCount,newValue:this._value};return N(d,b),this.postMessage("",d),a.removed}}function t(a,b){var c=M(t),d=this.owner.list;if(!d)return Q.warn("Data: cannot use splice method without List facet");var e=[],f=d.count();if(arguments[0]=a=K.normalizeSpliceIndex(a,f),b>0&&f>0){for(var g=a;a+b>g;g++){var h=d.item(a);if(h){var i=h.data.get();d._removeItem(a)}else Q.warn("Data: no item for index",g);e.push(i)}d._updateDataPaths(a,d.count())}var j=[],k=arguments.length,l=k>2,m=k-2;if(l){d._addItems(m,a);for(var g=2,n=a;k>g;g++,n++){var h=d.item(n);if(h){N(h.data.set,c);var i=h.data.set(arguments[g])}else Q.warn("Data: no item for index",n);j.push(i)}d._updateDataPaths(a,d.count())}return this._value=this.get(),{spliceIndex:a,removed:e,addedCount:l?m:0}}function u(){var a=this.config.len;return"function"==typeof a?a.call(this.owner):this._len()}function v(){return this.owner.list?this.owner.list.count():void Q.error("Data: len called without list facet")}function w(a,b){if(!a)return this;for(var c=J.parseAccessPath(a),d=this.owner,e=0,f=c.length;f>e;e++){var g=c[e],h=J.getPathNodeKey(g);if("array"==g.syntax&&d.list){var i=d.list.item(h);i||b===!1||(i=d.list._addItem(h),i.data._path=g.property),d=i}else d.container&&(d=d.container.scope[h]);var j=d&&d.data;if(!j)break}return j}function x(){return this._path}function y(){var a=this._path;return"["==a[0]?+a.slice(1,-1):a.slice(1)}function z(a){return{state:this.get(a)}}function A(a){return this.set(a.state)}var B=a("milo-core"),C=B.classes.Mixin,D=a("../c_facet"),E=a("./cf_registry"),F=(B.Messenger,a("../msg_src/dom_events")),G=a("../msg_api/data"),H=a("../msg_api/de_data"),I=B.Model,J=I._utils.path,K=I._utils.model,L=I._utils.changeDataHandler,M=L.getTransactionFlag,N=L.setTransactionFlag,O=L.postTransactionFinished,P=B.proto,Q=B.util.logger,R=P.createSubclass(D,"Data");P.extendProto(R,{start:c,getState:z,setState:A,get:p,set:k,del:m,splice:s,len:u,path:w,getPath:x,getKey:y,_get:q,_set:l,_del:n,_splice:t,_len:v,_setScalarValue:o,_getScalarValue:r,_bubbleUpDataChange:f,_queueDataChange:g,_postDataChanges:i,_prepareMessageSource:d}),E.add(R),b.exports=R,["push","pop","unshift","shift"].forEach(function(a){var b=I.Path.prototype[a];P.defineProperty(R.prototype,a,b)});var S={trigger:"trigger"}},{"../c_facet":16,"../msg_api/data":35,"../msg_api/de_data":36,"../msg_src/dom_events":38,"./cf_registry":30,"milo-core":105}],19:[function(a,b){"use strict";function c(a){var b=a.domConfig||{},c=b.tagName||"div",e=document.createElement(c),f=a.content,g=a.template;return d(e,b),"string"==typeof f&&(e.innerHTML=g?G.template(g)({content:f}):f),e}function d(a,b){var c=b&&b.cls,d=b&&b.attributes;d&&E.eachKey(d,function(b,c){a.setAttribute(c,b)}),c&&j(a,"add",c)}function e(){var a=this.owner.el;d(a,this.config);var b=window.getComputedStyle(a);this._visible=b&&"none"!=b.display}function f(){this.toggle(!0)}function g(){this.toggle(!1)}function h(a){a="undefined"==typeof a?!this._visible:!!a,this._visible=a;var b=this.owner.el; return b.style.display=a?"block":"none",a}function i(a,b,c){j(this.owner.el,a,b,c)}function j(a,b,c,d){function e(a){g?void 0===d?f[b](a):f[b](a,d):f[b](a)}var f=a.classList,g="toggle"==b;if(Array.isArray(c))c.forEach(e);else{if("string"!=typeof c)throw new Error("unknown type of CSS classes parameter");e(c)}}function k(){this.owner.el&&I.detachComponent(this.owner.el)}function l(a,b){if(!this.owner.el)throw new Error("Cannot call setStyle on owner with no element: "+this.owner.constructor.name);this.owner.el.style[a]=b}function m(a){for(var b in a)this.owner.el.style[b]=a[b]}function n(a){return this.owner.el&&this.owner.el.cloneNode(a)}function o(){var a=J.createElement(this.config);return a}function p(){I.removeElement(this.owner.el)}function q(a){this.owner.el.appendChild(a)}function r(a){var b=this.owner.el,c=b.firstChild;c?b.insertBefore(a,c):b.appendChild(a)}function s(a){for(;a.childNodes.length;)this.append(a.childNodes[0])}function t(a){for(;a.childNodes.length;)this.prepend(a.childNodes[a.childNodes.length-1])}function u(a){var b=this.owner.el,c=b.parentNode;c.insertBefore(a,b.nextSibling)}function v(a){var b=this.owner.el,c=b.parentNode;c.insertBefore(a,b)}function w(){var a=this.owner.getScopeParent();a&&a.el.appendChild(this.owner.el)}function x(){return I.children(this.owner.el)}function y(a,b){if(!K.hasOwnProperty(a))throw new Error("incorrect find direction: "+a);var c=this.owner.el,d=this.owner.scope,e=document.createTreeWalker(d._rootEl,NodeFilter.SHOW_ELEMENT);e.currentNode=c;for(var f=e[K[a]](),g=(Object.keys(d),!1);f;){var h=new H(f);if(h.node&&(h.parse().validate(),d.hasOwnProperty(h.compName))){var i=d[h.compName];if(!b||b(i)){g=!0;break}}e.currentNode=f,f=e[K[a]]()}return g?i:void 0}function z(){var a=window.getSelection();if(!a.isCollapsed)return!0;var b=a.focusNode&&a.focusNode.textContent,c=b&&" "==b.charAt(0)?1:0;if(a.anchorOffset!=c)return!0;var d=document.createTreeWalker(this.owner.el,NodeFilter.SHOW_TEXT);d.currentNode=a.anchorNode;var e=d.previousNode(),f=e?""==!e.nodeValue.trim():!1;return f}function A(){var a=window.getSelection();if(!a.isCollapsed)return!0;var b=a.focusNode&&a.focusNode.textContent,c=b&&" "==b.charAt(b.length-1)?a.anchorNode.length-1:a.anchorNode.length;if(a.anchorOffset<c)return!0;var d=document.createTreeWalker(this.owner.el,NodeFilter.SHOW_TEXT);d.currentNode=a.anchorNode;var e=d.nextNode(),f=e?""==!e.nodeValue.trim():!1;return f}var B=a("../c_facet"),C=a("./cf_registry"),D=a("milo-core"),E=D.proto,F=D.util.check,G=(F.Match,D.util.doT),H=(a("../../binder"),a("../../attributes/a_bind")),I=a("../../util/dom"),J=(a("../../config"),E.createSubclass(B,"Dom"));E.extend(J,{createElement:c}),E.extendProto(J,{start:e,show:f,hide:g,toggle:h,detach:k,remove:p,append:q,prepend:r,appendChildren:s,prependChildren:t,insertAfter:u,insertBefore:v,appendToScopeParent:w,children:x,setStyle:l,setStyles:m,copy:n,createElement:o,addCssClasses:E.partial(i,"add"),removeCssClasses:E.partial(i,"remove"),toggleCssClasses:E.partial(i,"toggle"),find:y,hasTextBeforeSelection:z,hasTextAfterSelection:A}),C.add(J),b.exports=J;var K={up:"previousNode",down:"nextNode"}},{"../../attributes/a_bind":4,"../../binder":8,"../../config":64,"../../util/dom":79,"../c_facet":16,"./cf_registry":30,"milo-core":105}],20:[function(a,b){"use strict";function c(){p.prototype.init.apply(this,arguments),this._createMessageSourceWithAPI(r),this._dragData={};var a=this.config._dataTypeInfo||"";this._dataTypeInfo="function"==typeof a?a:function(){return a}}function d(a){return this.owner.el.contains(a)?void(this._dragHandle=a):v.warn("drag handle should be inside element to be dragged")}function e(){p.prototype.start.apply(this,arguments),f.call(this),this.onMessages({mousedown:h,"mouseenter mouseleave mousemove":i,dragstart:j,drag:k,dragend:l}),this.owner.onMessages({getstatestarted:{subscriber:g,context:this},getstatecompleted:{subscriber:f,context:this}})}function f(){this.owner.el&&this.owner.el.setAttribute("draggable",!0)}function g(){this.owner.el&&this.owner.el.removeAttribute("draggable")}function h(a,b){this.__mouseDownTarget=b.target,n.call(this)&&(window.getSelection().empty(),b.stopPropagation())}function i(a,b){var c=n.call(this);this.owner.el.setAttribute("draggable",c),"false"!=document.body.getAttribute("data-dragEnableEvent")&&b.stopPropagation()}function j(a,b){function c(){var a=this.config.meta,b=a&&a.params,c=a&&a.data,d=u.result(b,e),g=u.result(c,e);this._dragMetaDataType=f.setComponentMeta(e,d,g),this._dragMetaData=g}function d(){this.config.dataTypes&&(this._dataTypesData=u.mapKeys(this.config.dataTypes,function(a,b){var c=a.call(this.owner,b);return"object"==typeof c&&(c=JSON.stringify(c)),c&&f.setData(b,c),c},this))}if(b.stopPropagation(),this.config.off||!n.call(this))return void b.preventDefault();var e=this.owner,f=new s(b);this._dragData=f.setComponentState(e),c.call(this),d.call(this),m.call(this,f),s.service.postMessageSync("dragdropstarted",{eventType:"dragstart",dragDrop:f,dragFacet:this})}function k(a,b){if(!o.call(this,b)){var c=new s(b);c.setComponentState(this.owner,this._dragData),c.setData(this._dragMetaDataType,this._dragMetaData),this._dataTypesData&&u.eachKey(this._dataTypesData,function(a,b){a&&c.setData(b,a)}),m.call(this,c)}}function l(a,b){if(!o.call(this,b)){b.stopPropagation();var c=new s(b);s.service.postMessageSync("completedragdrop",{eventType:"dragend",dragDrop:c,dragFacet:this})}}function m(a){var b=u.result(this.config.allowedEffects,this.owner);a.setAllowedEffects(b)}function n(){return!this._dragHandle||this._dragHandle.contains(this.__mouseDownTarget)}function o(a){return this.config.off?(a.preventDefault(),!0):!1}var p=a("../c_facet"),q=a("./cf_registry"),r=a("../msg_src/dom_events"),s=(a("../c_class"),a("../../util/dragdrop")),t=a("milo-core"),u=t.proto,v=t.util.logger,w=u.createSubclass(p,"Drag");u.extendProto(w,{init:c,start:e,setHandle:d}),q.add(w),b.exports=w},{"../../util/dragdrop":82,"../c_class":15,"../c_facet":16,"../msg_src/dom_events":38,"./cf_registry":30,"milo-core":105}],21:[function(a,b){"use strict";function c(){j.prototype.init.apply(this,arguments),this._createMessageSourceWithAPI(l,new m)}function d(){j.prototype.start.apply(this,arguments),this.owner.el.classList.add("cc-module-relative"),this.onMessages({"dragenter dragover":e,drop:f,"dragenter dragover dragleave drop dragin dragout":g})}function e(a,b){var c=new n(b);b.stopPropagation(),b.preventDefault(),q.call(this,c)||c.setDropEffect("none")}function f(a,b){b.stopPropagation();var c=new n(b);n.service.postMessageSync("dragdropcompleted",{eventType:"drop",dragDrop:c,dropFacet:this,component:this.owner})}function g(a,b){n.service.postMessageSync(a,{event:b,dropFacet:this,component:this.owner})}function h(a,b){var c=this.config.allow,d=!0;if(b=b||this.owner,c&&c.checkParent){var e=this.owner.getScopeParent("Drop");e&&(d=h.call(e.drop,a,b))}return d&&i.call(this,a,b)}function i(a,b){var c=this.config.allow;if(a.isComponent()){var d=c&&c.components,e=a.getComponentMeta();switch(typeof d){case"undefined":return!0;case"boolean":return d;case"string":return e&&e.compClass==d;case"function":return d.call(this.owner,e,a,b);case"object":if(Array.isArray(d))return d.indexOf(e&&e.compClass)>=0;var f=d[e&&e.compClass];return!!o.result(f,this.owner,e,a);default:throw new Error("Incorrect allowed components in config")}}else{var g=c&&c.dataTypes;switch(typeof g){case"undefined":return!1;case"string":return a.types.indexOf(g)>=0}}}var j=a("../c_facet"),k=a("./cf_registry"),l=a("../msg_src/dom_events"),m=a("../msg_api/drop"),n=a("../../util/dragdrop"),o=a("milo-core").proto,p=o.createSubclass(j,"Drop");o.extendProto(p,{init:c,start:d}),k.add(p),b.exports=p;var q=o.throttle(h,50)},{"../../util/dragdrop":82,"../c_facet":16,"../msg_api/drop":37,"../msg_src/dom_events":38,"./cf_registry":30,"milo-core":105}],22:[function(a,b){"use strict";function c(){d.prototype.init.apply(this,arguments);var a=new g(this,void 0,void 0,this.owner);this._setMessageSource(a),h.defineProperty(this,j,a)}var d=a("../c_facet"),e=a("./cf_registry"),f=a("milo-core"),g=(f.Messenger,a("../msg_src/dom_events")),h=f.proto,i=h.createSubclass(d,"Events");h.extendProto(i,{init:c}),e.add(i),b.exports=i;var j="_domEventsSource";g.useWith(i,j,["trigger"])},{"../c_facet":16,"../msg_src/dom_events":38,"./cf_registry":30,"milo-core":105}],23:[function(a,b){"use strict";function c(){k.prototype.init.apply(this,arguments);var a=new n(this,void 0,void 0,this.owner);this._setMessageSource(a),o.defineProperty(this,s,a)}function d(){function a(a){b.postMessage("domready",a)}k.prototype.start.apply(this,arguments);var b=this;milo(a)}function e(){k.prototype.destroy.apply(this,arguments)}function f(){return this.owner.el.contentWindow}function g(){var a=this.getWindow().document.readyState;return"loading"!=a?a:!1}function h(){var a=this.getWindow().milo;return this.isReady()&&a&&a.milo_version}function i(a){if("function"==typeof a){var b=this;this.whenMiloReady(function(){b.getWindow().milo(a)})}var c=this.getWindow();return c&&c.milo}function j(a,b){return function(c){function d(){c.apply(e,f)}var e=this,f=o.slice(arguments,1);a.call(this)?d():this.on(b,d)}}var k=a("../c_facet"),l=a("./cf_registry"),m=a("milo-core"),n=(m.Messenger,a("../msg_src/frame")),o=(a("../../services/de_constrs"),m.proto),p=o.createSubclass(k,"Frame"),q=j(g,"domready"),r=j(h,"message:miloready");o.extendProto(p,{init:c,start:d,destroy:e,getWindow:f,isReady:g,whenReady:q,isMiloReady:h,whenMiloReady:r,milo:i}),l.add(p),b.exports=p;var s="_messageSource";n.useWith(p,s,["trigger"])},{"../../services/de_constrs":68,"../c_facet":16,"../msg_src/frame":39,"./cf_registry":30,"milo-core":105}],24:[function(a,b){"use strict";function c(){return{state:{index:this.getIndex()}}}function d(a){this.setIndex(a.state.index)}function e(){return this.index}function f(a){this.index=a}function g(){this.list.removeItem(this.index)}function h(){this.list.extractItem(this.index)}var i=a("../c_facet"),j=a("./cf_registry"),k=a("milo-core"),l=(k.Model,k.proto),m=(a("../../services/mail"),l.createSubclass(i,"Item"));l.extendProto(m,{getState:c,setState:d,getIndex:e,setIndex:f,removeItem:g,extractItem:h,require:["Container","Dom","Data"]}),j.add(m),b.exports=m},{"../../services/mail":70,"../c_facet":16,"./cf_registry":30,"milo-core":105}],25:[function(a,b){"use strict";function c(){y.prototype.init.apply(this,arguments);C.defineProperties(this,{_listItems:[],_listItemsHash:{}}),C.defineProperty(this,"itemSample",null,C.WRIT)}function d(){this.owner.on("childrenbound",e)}function e(){var a=this.dom.children(),b=this.list._listItems,c=this.list._listItemsHash;if(a&&a.forEach(function(a){var d=z.getComponent(a);d&&d.item&&(b.push(d),c[d.name]=d,d.item.list=this.list)},this),b.length){var d=b[0];b.splice(0,1),delete c[d.name],b.forEach(function(a,b){a.item.setIndex(b)})}if(!d)throw new Error("No child component has Item facet");this.list.itemSample=d,d.dom.hide(),d.remove(!0),d.dom.removeCssClasses(L),d.walkScopeTree(function(a){delete a.el[K.componentRef]}),this.list._createCacheTemplate()}function f(){if(!this.itemSample)return!1;{var a=this.itemSample,b=a.el.cloneNode(!0),c=a.componentInfo.attr;C.clone(c)}c.compName="{{= it.componentName() }}",c.el=b,c.decorate();var d="{{ var i = it.count; while(i--) { }}"+b.outerHTML+"{{ } }}";this.itemsTemplate=F.compile(d)}function g(a){return this._listItems[a]}function h(){return this._listItems.length}function i(a,b){this._listItems.splice(a,0,b),this._listItemsHash[b.name]=b,b.item.list=this,b.item.setIndex(+a)}function k(a){return this._listItemsHash[a.name]==a}function l(a,b){return a=a||this.count(),this.owner.data.splice(a,0,b||{}),this.item(a)}function m(a){if(a=a||this.count(),this.item(a))throw Error("attempt to create item with ID of existing item");var b=z.copy(this.itemSample,!0),c=this._itemPreviousComponent(a);return c.el.parentNode?(c.dom.insertAfter(b.el),this._setItem(a,b),b.el.style.display="",n.call(this,a+1),b):E.warn("list item sample was removed from DOM, probably caused by wrong data. Reset list data with array")}function n(a,b){a=a||0,b=b||this.count();for(var c=a;b>c;c++){var d=this._listItems[c];d?d.item.setIndex(c):E.warn("List: no item at position",c)}}function o(a,b){var c=C.slice(arguments,2);c.length<a&&c.concat(C.repeat(a-c.length,{}));var d=[b,0].concat(c),e=this.owner.data;e.splice.apply(e,d)}function p(a,b){if(G(a,H.Integer),0>a)throw new Error("can't add negative number of items");if(0!=a){var c=this.itemsTemplate({componentName:J,count:a}),d=document.createElement("div");d.innerHTML=c,D(d,this.owner.container.scope);var e=I.children(d);if(a!=e.length&&E.error("number of items added is different from requested"),e&&e.length){var f=this.count(),g=0>b?0:"undefined"==typeof b||b>f?f:b,h=0==g?this.itemSample:this._listItems[g-1],i=document.createDocumentFragment(),j=[];if(e.forEach(function(a){var b=z.getComponent(a);return b?(j.push(b),this._setItem(g++,b),i.appendChild(a),void(a.style.display="")):E.error("List: element in new items is not a component")},this),n.call(this,g),!h.el.parentNode)return E.warn("list item sample was removed from DOM, probably caused by wrong data. Reset list data with array");h.dom.insertAfter(i),C.deferMethod(j,"forEach",function(a){a.broadcast("stateready")})}}}function q(a){return this.owner.data.splice(a,1)}function r(a){var b=this._removeItem(a,!1);return this._updateDataPaths(a,this.count()),b}function s(a,b){var c=this.item(a);return c?(this._listItems[a]=void 0,delete this._listItemsHash[c.name],b!==!1?c.destroy():(c.remove(),c.dom.remove()),this._listItems.splice(a,1),n.call(this,a),c):E.warn("attempt to remove list item with id that does not exist")}function t(a,b){var c=this.item(a);c.dom.insertAfter(b.el),this._removeItem(a),this._setItem(a,b)}function u(a){for(;a>=0&&!this._listItems[a];)a--;return a>=0?this._listItems[a]:this.itemSample}function v(a,b){for(var c=a;b>c;c++){var d=this.item(c);d?d.data._path="["+c+"]":E.warn("Data: no item for index",j)}}function w(a,b){this._listItems.forEach(function(b,c){b?a.apply(this,arguments):E.warn("List$each: item",c,"is undefined")},b||this)}function x(){this.itemSample&&this.itemSample.destroy(!0),y.prototype.destroy.apply(this,arguments)}var y=a("../c_facet"),z=a("../c_class"),A=a("./cf_registry"),B=a("milo-core"),C=B.proto,D=(a("../../services/mail"),a("../../binder")),E=B.util.logger,F=B.util.doT,G=B.util.check,H=G.Match,I=a("../../util/dom"),J=a("../../util/component_name"),K=a("../../config"),L="ml-list-item-sample",M=C.createSubclass(y,"List");C.extendProto(M,{init:c,start:d,destroy:x,require:["Container","Dom","Data"],_itemPreviousComponent:u,item:g,count:h,contains:k,addItem:l,addItems:o,replaceItem:t,removeItem:q,extractItem:r,each:w,_setItem:i,_removeItem:s,_addItem:m,_addItems:p,_createCacheTemplate:f,_updateDataPaths:v}),A.add(M),b.exports=M},{"../../binder":8,"../../config":64,"../../services/mail":70,"../../util/component_name":76,"../../util/dom":79,"../c_class":15,"../c_facet":16,"./cf_registry":30,"milo-core":105}],26:[function(a,b){"use strict";function c(){this.m=new k(this.config.data,this),h.prototype.init.apply(this,arguments)}function d(){var a=this.m.get();return"object"==typeof a&&(a=l.deepClone(a)),{state:a}}function e(a){return this.m.set(a.state)}function f(){this._messenger=this.m._messenger}function g(){this.m.destroy(),h.prototype.destroy.apply(this,arguments)}var h=a("../c_facet"),i=a("./cf_registry"),j=a("milo-core"),k=j.Model,l=(j.classes.Mixin,j.proto),m=l.createSubclass(h,"Model");l.extendProto(m,{init:c,getState:d,setState:e,_createMessenger:f,destroy:g}),i.add(m),b.exports=m,k.useWith(m,"m")},{"../c_facet":16,"./cf_registry":30,"milo-core":105}],27:[function(a,b){"use strict";function c(){this.m=new i(this.config.options,this),f.prototype.init.apply(this,arguments),this.m.proxyMethods(this)}function d(){this._messenger=this.m._messenger}function e(){this.m.destroy(),f.prototype.destroy.apply(this,arguments)}var f=a("../c_facet"),g=a("./cf_registry"),h=a("milo-core"),i=h.Model,j=h.proto,k=j.createSubclass(f,"Options");j.extendProto(k,{init:c,destroy:e,_createMessenger:d}),g.add(k),b.exports=k},{"../c_facet":16,"./cf_registry":30,"milo-core":105}],28:[function(a,b){"use strict";function c(){i.prototype.init.apply(this,arguments);var a=this.config.interpolate===!1?void 0:this.config.compile||milo.config.template.compile;this.set(this.config.template||"",a,this.config.compileOptions)}function d(){i.prototype.start.apply(this,arguments),this.config.autoRender&&(this.render(),this.config.autoBinder&&this.binder())}function e(){return this._template}function f(a,b,c){return m(a,o.OneOf(String,Function)),m(b,o.Optional(Function)),"function"==typeof a?this._template=a:(this._templateStr=a,b?this._compile=b:b=this._compile,b&&(this._template=b(a,c))),this}function g(a){return this.owner.el.innerHTML=this._template?this._template(a):this._templateStr,this}function h(){return this.owner.container?this.owner.container.binder():void n.error("TemplateFacet: Binder called without container facet.")}var i=a("../c_facet"),j=a("./cf_registry"),k=a("milo-core"),l=k.proto,m=k.util.check,n=k.util.logger,o=m.Match,p=(a("../../binder"),l.createSubclass(i,"Template"));l.extendProto(p,{init:c,start:d,set:f,getCompiled:e,render:g,binder:h}),j.add(p),b.exports=p},{"../../binder":8,"../c_facet":16,"./cf_registry":30,"milo-core":105}],29:[function(a,b){"use strict";function c(){j.prototype.init.apply(this,arguments),this._activeState="",this._defaultKey="",this._state={}}function d(){return this._state[this._activeState]||this._state[this._defaultKey]}function e(a){this._state[""]=a,this.setActiveState("")}function f(a){this._activeState=a}function g(a,b,c){if(!a)throw new Error("Transfer$setStateWithKey: no key");this._defaultKey=c?a:this._defaultKey||a,this._state[a]=b,this.setActiveState(a)}function h(a){return"string"==typeof a&&this._state[a]}function i(){var a=this.getState();return{compName:a&&a.compName,compClass:a&&a.compClass}}var j=a("../c_facet"),k=a("./cf_registry"),l=a("milo-core").proto,m=l.createSubclass(j,"Transfer");l.extendProto(m,{init:c,getState:d,setState:e,setActiveState:f,setStateWithKey:g,getStateWithKey:h,getComponentMeta:i}),k.add(m),b.exports=m},{"../c_facet":16,"./cf_registry":30,"milo-core":105}],30:[function(a,b){"use strict";var c=a("../../abstract/registry"),d=a("../c_facet"),e=new c(d);e.add(d),b.exports=e},{"../../abstract/registry":3,"../c_facet":16}],31:[function(a,b){"use strict";function c(a,b,c,d){c.parse().validate(),this.scope=a,this.el=b,this.attr=c,this.name=c.compName,this.ComponentClass=f(c,d),this.extraFacetsClasses=g(this.ComponentClass,c,d),this.ComponentClass&&i(this.ComponentClass,this.extraFacetsClasses)&&(this.container={})}function d(){delete this.el,this.attr.destroy()}function e(a,b){a=a||l(),m.rename(this,a,b),this.attr.compName=a,this.attr.decorate()}function f(a,b){var c=j.get(a.compClass);return c||h(b,"class "+a.compClass+" is not registered"),c}function g(a,b,c){var d=b.compFacets,e={};return Array.isArray(d)&&d.forEach(function(d){d=p.firstUpperCase(d),a.hasFacet(d)&&h(c,"class "+a.name+" already has facet "+d),e[d]&&h(c,"component "+b.compName+" already has facet "+d);var f=k.get(d);e[d]=f}),e}function h(a,b){if(a!==!1)throw new Error(b);o.error("ComponentInfo binder error:",b)}function i(a,b){function c(){return a.prototype.facetsClasses&&p.someKey(a.prototype.facetsClasses,d)}function d(a){return a.requiresFacet("container")}return a.hasFacet("container")||"Container"in b||p.someKey(b,d)||c()}var j=a("./c_registry"),k=a("./c_facets/cf_registry"),l=a("../util/component_name"),m=a("./scope"),n=a("milo-core"),o=n.util.logger,p=n.proto;b.exports=c,p.extendProto(c,{destroy:d,rename:e})},{"../util/component_name":76,"./c_facets/cf_registry":30,"./c_registry":32,"./scope":40,"milo-core":105}],32:[function(a,b){"use strict";var c=a("../abstract/registry"),d=a("./c_class"),e=new c(d);e.add(d),b.exports=e},{"../abstract/registry":3,"./c_class":15}],33:[function(a,b){"use strict";function c(a){return a.hasOwnProperty(h.componentRef)}function d(a){return a&&a[h.componentRef]}function e(a,b,c){j(b,k.Optional(Boolean)),j(c,k.Optional(k.OneOf(Function,String)));var d=f(c);return g(a,b,d)}function f(a){if("function"==typeof a)return a;if("string"==typeof a){var b=l.firstLowerCase(a);return function(a){return a.hasFacet(b)}}}function g(a,b,c){if(b!==!1){var e=d(a);if(e&&(!c||c(e)))return e}return a.parentNode?g(a.parentNode,!0,c):void 0}{var h=a("../config"),i=a("milo-core"),j=i.util.check,k=j.Match,l=i.proto;b.exports={isComponent:c,getComponent:d,getContainingComponent:e,_makeComponentConditionFunc:f}}},{"../config":64,"milo-core":105}],34:[function(a,b){"use strict";var c=a("../c_class"),d=a("../c_registry"),e=c.createComponentClass("View",["container"]);d.add(e),b.exports=e},{"../c_class":15,"../c_registry":32}],35:[function(a,b){"use strict";function c(a){j.prototype.init.apply(this,arguments),this.component=a,this.elData=h(a.el)}function d(){var a=this.component.data.config.get,b="function"==typeof a?a.call(this.component):this.elData.get(this.component.el);return this.component.data._value=b,b}function e(a){var b=this.component.data.config.event,c=b||this.elData.event(this.component.el);return""==a&&c?c:void 0}function f(a,b,c){return c.newValue!=c.oldValue}function g(){var a=this.component.data._value,b=this.value(),c={path:"",type:"changed",oldValue:a,newValue:b};return c}var h=a("./de_data"),i=a("milo-core"),j=i.classes.MessengerAPI,k=i.proto,l=i.util.check,m=(l.Match,k.createSubclass(j,"DataMsgAPI",!0));k.extendProto(m,{init:c,translateToSourceMessage:e,filterSourceMessage:f,createInternalData:g,value:d}),b.exports=m},{"./de_data":36,"milo-core":105}],36:[function(a,b){"use strict";function c(a){var b=h[a.type];return b?b.property:h.byDefault.property}function d(a){var b=h[a.type];return b?b.event:h.byDefault.event}var e=a("milo-core").proto,f=function(a){var b=a.tagName.toLowerCase(),c=g[b];return c||g.byDefault};b.exports=f;var g={byDefault:{property:"innerHTML"},div:{property:"innerHTML"},span:{property:"innerHTML",event:"input"},p:{property:"innerHTML",event:"input"},input:{property:c,event:d},textarea:{property:"value",event:"input"},select:{property:"value",event:"change"},img:{property:"src"},caption:{property:"innerHTML",event:"input"},thead:{property:"innerHTML",event:"input"},tbody:{property:"innerHTML",event:"input"},tfoot:{property:"innerHTML",event:"input"}};e.eachKey(g,function(a){var b=a.property,c=a.event;"function"!=typeof b&&(a.property=function(){return b});var d=a.property;"function"!=typeof c&&(a.event=function(){return c}),a.get||(a.get=function(a){return a[d(a)]}),a.set||(a.set=function(a,b){return a[d(a)]="undefined"==typeof b?"":b})});var h={byDefault:{property:"value",event:"input"},checkbox:{property:"checked",event:"change"},radio:{property:"checked",event:"change"},text:{property:"value",event:"input"}}},{"milo-core":105}],37:[function(a,b){"use strict";function c(a){return h.hasOwnProperty(a)?h[a]:a}function d(){delete this._currentTarget,delete this._inside}function e(a,b,c){var e=!0;return"dragenter"==a&&"dragin"==b?(this._currentTarget=c.target,e=!this._inside,this._inside=!0):"dragleave"==a&&"dragout"==b?(e=this._currentTarget==c.target,e&&d.call(this)):"drop"==a&&d.call(this),e}var f=a("milo-core").classes.MessengerAPI,g=_.createSubclass(f,"DropMsgAPI",!0);_.extendProto(g,{translateToSourceMessage:c,filterSourceMessage:e}),b.exports=g;var h={dragin:"dragenter",dragout:"dragleave"}},{"milo-core":105}],38:[function(a,b){"use strict";function c(a,b,c,d){k(d,i),this.component=d,h.prototype.init.apply(this,arguments)}function d(){h.prototype.destroy.apply(this,arguments),delete this.component}function e(){return this.component.el}var f=a("../../services/dom_source"),g=a("milo-core"),h=g.classes.MessageSource,i=a("../c_class"),j=g.proto,k=g.util.check,l=(k.Match,j.createSubclass(f,"DOMEventsSource",!0));j.extendProto(l,{init:c,destroy:d,emitter:e}),b.exports=l},{"../../services/dom_source":69,"../c_class":15,"milo-core":105}],39:[function(a,b){"use strict";function c(a,b,c,d){if(m(d,i),this.component=d,"iframe"!=d.el.tagName.toLowerCase())throw new Error("component for FrameMessageSource can only be attached to iframe element");k.prototype.init.apply(this,arguments)}function d(){return this.component.el.contentWindow}function e(){var a=this.frameWindow();a?a.addEventListener("message",this,!1):n.warn("FrameMessageSource: frame window is undefined")}function f(){var a=this.frameWindow();a?a.removeEventListener("message",this,!1):n.warn("FrameMessageSource: frame window is undefined")}function g(a,b){b=b||{},b.type=a,this.frameWindow().postMessage(b,"*")}function h(a){this.dispatchMessage(a.data.type,a)}var i=a("../c_class"),j=a("milo-core"),k=j.classes.MessageSource,l=j.proto,m=j.util.check,n=j.util.logger,o=(m.Match,l.createSubclass(k,"FrameMessageSource",!0));l.extendProto(o,{init:c,addSourceSubscriber:e,removeSourceSubscriber:f,trigger:g,frameWindow:d,handleEvent:h}),b.exports=o},{"../c_class":15,"milo-core":105}],40:[function(a,b){"use strict";function c(a,b){u.defineProperties(this,{_rootEl:a,_hostObject:b},u.WRIT)}function d(a,b){if("string"==typeof b?a.name=b:b=a.name,this.hasOwnProperty(b))throw new Error("duplicate object name: "+b);l(b),f.call(this,a,b)}function e(a,b){"string"==typeof b?a.name=b:b=a.name;var c=this.hasOwnProperty(b);c?x.error("Scope: duplicate object name: "+b):(c=!y.test(b),c&&x.error("Scope: name should start from letter, this name is not allowed: "+b)),c&&(b=v(),a.name=b),f.call(this,a,b)}function f(a,b){this[b]=a,a.scope=this,"function"==typeof a.postMessage&&a.postMessage("addedtoscope")}function g(a){w(a,c),a._each(d,this)}function h(a,b){b._add(a),this._remove(a.name),a.scope=b}function i(a){a._each(function(b){this._add(b,b.name),a._remove(b.name)},this)}function j(a,b){u.eachKey(this,a,b||this,!0)}function k(a,b){return u.filterKeys(this,a,b||this,!0)}function l(a){if(!y.test(a))throw new Error("name should start from letter, this name is not allowed: "+a)}function m(){return Object.keys(this).length}function n(){var a=Object.keys(this)[0];return a&&this[a]}function o(a,b){if(!(a in this))return void(b||x.warn("removing object that is not in scope"));var c=this[a];delete this[a],"function"==typeof c.postMessage&&c.postMessage("removedfromscope")}function p(){this._each(function(a,b){delete this[b].scope,delete this[b]},this)}function q(){this._rootEl=null}function r(a){return this.hasOwnProperty(a.name)}function s(a,b,c){a.scope&&c!==!1?(a.scope._remove(a.name),a.scope._add(a,b)):a.name=b}var t=a("milo-core"),u=t.proto,v=a("../util/component_name"),w=t.util.check,x=(w.Match,t.util.logger);u.extendProto(c,{_add:d,_safeAdd:e,_copy:g,_each:j,_move:h,_merge:i,_length:m,_any:n,_remove:o,_clean:p,_detachElement:q,_has:r,_filter:k}),u.extend(c,{rename:s}),b.exports=c;var y=/^[A-Za-z][A-Za-z0-9\_\$]*$/},{"../util/component_name":76,"milo-core":105}],41:[function(a,b){"use strict";function c(a){this.el.disabled=a}function d(){return!!this.el.disabled}var e=a("../c_class"),f=a("../c_registry"),g=a("milo-core").proto,h=e.createComponentClass("MLButton",{events:void 0,dom:{cls:"ml-ui-button"}});f.add(h),b.exports=h,g.extendProto(h,{disable:c,isDisabled:d})},{"../c_class":15,"../c_registry":32,"milo-core":105}],42:[function(a,b){"use strict";function c(){k.prototype.init.apply(this,arguments),this.on("childrenbound",d)}function d(){m.defineProperties(this,{_comboInput:this.container.scope.input,_comboList:this.container.scope.datalist}),this._comboList.template.set(o),this._comboInput.data.on("input",{subscriber:i,context:this})}function e(){return this._comboInput?this._comboInput.data.get():void 0}function f(a){return h.call(this,"set",a)}function g(){return h.call(this,"del",value)}function h(a,b){if(this._comboInput){var c=this._comboInput.data[a](b);return i.call(this),c}}function i(){this.data.dispatchSourceMessage(n)}function j(){this._comboList.template.render({comboOptions:this.model.get()})}var k=a("../c_class"),l=a("../c_registry"),m=a("milo-core").proto,n="mlcombochange",o='{{~ it.comboOptions :option }} <option value="{{= option.label }}"></option> {{~}}',p=k.createComponentClass("MLCombo",{events:void 0,data:{get:e,set:f,del:g,splice:void 0,event:n},model:{messages:{"***":{subscriber:j,context:"owner"}}},dom:{cls:"ml-ui-datalist"},container:void 0});l.add(p),b.exports=p,m.extendProto(p,{init:c})},{"../c_class":15,"../c_registry":32,"milo-core":105}],43:[function(a,b){"use strict";function c(){r.prototype.init.apply(this,arguments),this._dataValidation=function(){},this.model.set([]),this.once("childrenbound",j)}function d(a){"function"==typeof a&&(this._dataValidation=a)}function e(a){this._combo.setOptions(a)}function f(){this._combo.clearComboInput()}function g(a){this._combo.toggleAddButton(a)}function h(a){this._combo.setAddItemPrompt(a)}function i(){r.prototype.destroy.apply(this,arguments),this._connector&&milo.minder.destroyConnector(this._connector),this._connector=null}function j(){this.template.render().binder(),k.call(this)}function k(){t.defineProperties(this,{_combo:this.container.scope.combo,_list:this.container.scope.list}),this._connector=milo.minder(this._list.model,"<<<->>>",this.model),this._combo.data.on("",{subscriber:l,context:this}),this._combo.on("additem",{subscriber:q,context:this})}function l(a,b){b.newValue&&this._dataValidation(a,b,this._list.model.get())&&this._list.model.push(b.newValue),this._combo.data.del(),this._combo.data._value=""}function m(){this.data.dispatchSourceMessage(u)}function n(){var a=this.model.get();return"object"==typeof a?t.clone(a):a}function o(a){this.model.set(a)}function p(){return this.model.set([])}function q(a,b){this.postMessage("additem",b),this.events.postMessage("milo_combolistadditem",b)}var r=a("../c_class"),s=a("../c_registry"),t=a("milo-core").proto,u="mlcombolistchange",v=r.createComponentClass("MLComboList",{dom:{cls:"ml-ui-combo-list"},data:{get:n,set:o,del:p,event:u},events:void 0,container:void 0,model:{messages:{"***":{subscriber:m,context:"owner"}}},template:{template:'<div ml-bind="MLSuperCombo:combo"></div> <div ml-bind="MLList:list"> <div ml-bind="MLListItem:item" class="list-item"> <span ml-bind="[data]:label"></span> <span ml-bind="[events]:deleteBtn" class="glyphicon glyphicon-remove"></span> </div> </div>'}});s.add(v),b.exports=v,t.extendProto(v,{init:c,setOptions:e,setDataValidation:d,toggleAddButton:g,destroy:i,setAddItemPrompt:h,clearComboInput:f})},{"../c_class":15,"../c_registry":32,"milo-core":105}],44:[function(a,b){"use strict";function c(){return n.date(this.el.min)}function d(a){var b=n.toDate(a);this.el.min=b?k(b):""}function e(){return n.date(this.el.max)}function f(a){var b=n.toDate(a);this.el.max=b?k(b):""}function g(){return n.toDate(this.el.value)}function h(a){var b=n.toDate(a);this.el.value=b?k(b):"",j.call(this)}function i(){this.el.value="",j.call(this)}function j(){this.data.dispatchSourceMessage("input")}function k(a){function b(a){return 10>a?"0"+a:a}var c=[a.getFullYear(),b(a.getMonth()+1),b(a.getDate())],d=c.join("-");return d}var l=a("../c_class"),m=a("../c_registry"),n=a("milo-core").proto,o=l.createComponentClass("MLDate",{events:void 0,data:{get:g,set:h,del:i},dom:{cls:"ml-ui-date"}});n.extendProto(o,{getMin:c,setMin:d,getMax:e,setMax:f}),m.add(o),b.exports=o},{"../c_class":15,"../c_registry":32,"milo-core":105}],45:[function(a,b){"use strict";var c=a("../c_class"),d=a("../c_registry"),e=c.createComponentClass("MLDropTarget",["drop"]);d.add(e),b.exports=e},{"../c_class":15,"../c_registry":32}],46:[function(a,b){"use strict";function c(a){a.classList.toggle("ml-ui-foldtree--unfold")}function d(a,b){var c=b.getAttribute("data-item-id"),d=this._itemsMap[c]; this.postMessage("mlfoldtree_"+a,{item:d,el:b})}function e(a,b){var e=b.target;if(e.classList.contains("ml-ui-foldtree-button"))c(e.parentNode.parentNode);else{if(!e.classList.contains("ml-ui-foldtree-label"))return;d.call(this,a,e)}b.stopPropagation()}function f(a){this._itemTemplate=h.compile(a)}function g(a){function b(a){if(a.items)var d=_.map(a.items,function(a){var b=k();return c._itemsMap[b]=a,b});return n({itemIDs:d,data:a,itemTemplate:c._itemTemplate||m,treeTemplate:b})}var c=this;this._data=a,c._itemsMap={},this.el.innerHTML=b(a)}var h=a("milo-core").util.doT,i=a("../c_registry"),j=a("../c_class"),k=a("../../util/count"),l='<ul class="ml-ui-foldtree-list"> {{~ it.data.items :item:index }} {{ var hasSubTree = item.items && item.items.length; }} <li {{? hasSubTree }}class="ml-ui-foldtree--has-multiple"{{?}}> <div class="ml-ui-foldtree-item"> {{? hasSubTree }} <div class="ml-ui-foldtree-button"></div> {{?}} {{= it.itemTemplate({ item: item, id: it.itemIDs[index] }) }} </div> {{? hasSubTree }} {{= it.treeTemplate(item) }} {{?}} </li> {{~}} </ul>',m=h.compile(' <span class="ml-ui-foldtree-label" data-item-id="{{= it.id }}"> {{= it.item.label }} </span>'),n=h.compile(l),o=j.createComponentClass("MLFoldTree",{container:void 0,events:{messages:{"click dblclick":{subscriber:e,context:"owner"}}},dom:{cls:"ml-ui-foldtree-main"}});i.add(o),b.exports=o,_.extendProto(o,{setItemTemplate:f,renderTree:g})},{"../../util/count":77,"../c_class":15,"../c_registry":32,"milo-core":105}],47:[function(a,b){"use strict";var c=a("../c_class"),d=a("../c_registry"),e=c.createComponentClass("MLGroup",{container:void 0,data:void 0,events:void 0,dom:{cls:"ml-ui-group"}});d.add(e),b.exports=e},{"../c_class":15,"../c_registry":32}],48:[function(a,b){"use strict";var c=a("../c_class"),d=a("../c_registry"),e=c.createComponentClass("MLHyperlink",{events:void 0,data:void 0,dom:{cls:"ml-ui-hyperlink"}});d.add(e),b.exports=e},{"../c_class":15,"../c_registry":32}],49:[function(a,b){"use strict";function c(){i.prototype.init.apply(this,arguments)}function d(a){return this.model.set(a),a}function e(){var a=this.model.get();return a&&"object"==typeof a?k.clone(a):a}function f(){this.model.del()}function g(){this.data.dispatchSourceMessage(l)}function h(a,b){this.el.src=b.newValue,g.call(this)}var i=a("../c_class"),j=a("../c_registry"),k=a("milo-core").proto,l="mlimagechange",m=i.createComponentClass("MLImage",{data:{set:d,get:e,del:f,splice:void 0,event:l},model:{messages:{".src":{subscriber:h,context:"owner"}}},events:void 0,container:void 0,dom:{tagName:"img",cls:"ml-ui-image"}});j.add(m),b.exports=m,k.extendProto(m,{init:c})},{"../c_class":15,"../c_registry":32,"milo-core":105}],50:[function(a,b){"use strict";function c(a){this.el.disabled=a}function d(){return!!this.el.disabled}function e(a){this.el.setAttribute("maxlength",a)}var f=a("../c_class"),g=a("../c_registry"),h=a("milo-core").proto,i=f.createComponentClass("MLInput",{data:void 0,events:void 0,dom:{cls:"ml-ui-input"}});g.add(i),b.exports=i,h.extendProto(i,{disable:c,isDisabled:d,setMaxLength:e})},{"../c_class":15,"../c_registry":32,"milo-core":105}],51:[function(a,b){"use strict";function c(){p.prototype.init.apply(this,arguments),this.once("childrenbound",d),this.model.set([])}function d(){h.call(this)}function e(a){this._input.el.setAttribute("placeHolder",a)}function f(a){t=a||t}function g(){p.prototype.destroy.apply(this,arguments),this._connector&&milo.minder.destroyConnector(this._connector),this._connector=null}function h(){this.template.render().binder(),i.call(this)}function i(){r.defineProperties(this,{_input:this.container.scope.input,_button:this.container.scope.button,_list:this.container.scope.list}),this._connector=milo.minder(this._list.model,"<<<->>>",this.model),this._button.events.on("click",{subscriber:j,context:this})}function j(){var a=this._input.data.get(0);this._input.data&&t(a,function(a,b){this._list.model.push({label:a,value:b})}.bind(this)),this._input.data.del()}function k(){this.data.dispatchSourceMessage(s)}function l(){var a=this.model.get();return a?r.clone(a):void 0}function m(a){this.model.set(a)}function n(){return this.model.set([])}function o(){this.model.splice.apply(this.model,arguments)}var p=a("../c_class"),q=a("../c_registry"),r=a("milo-core").proto,s="mlinputlistchange",t=function(a,b){b(a)},u=p.createComponentClass("MLInputList",{dom:{cls:"ml-ui-input-list"},data:{get:l,set:m,del:n,splice:o,event:s},events:void 0,container:void 0,model:{messages:{"***":{subscriber:k,context:"owner"}}},template:{template:' <div ml-bind="MLList:list"> <div ml-bind="MLListItem:item" class="list-item"> <span ml-bind="[data]:label"></span> <span ml-bind="[events]:deleteBtn" class="glyphicon glyphicon-remove"></span> </div> </div> <input type="text" ml-bind="MLInput:input" class="form-control"> <button ml-bind="MLButton:button" class="btn btn-default"> Add </button>'}});q.add(u),b.exports=u,r.extendProto(u,{init:c,setAsync:f,setPlaceHolder:e,destroy:g})},{"../c_class":15,"../c_registry":32,"milo-core":105}],52:[function(a,b){"use strict";function c(){h.prototype.init.apply(this,arguments),this.on("childrenbound",g)}function d(){this._connector&&milo.minder.destroyConnector(this._connector),this._connector=null,h.prototype.destroy.apply(this,arguments)}function e(a){this.model.splice(a,1)}function f(a,b){var c=this.model.splice(a,1);return this.model.splice(b,0,c[0])}function g(){this.model.set([]),this._connector=milo.minder(this.model,"<<<-",this.data).deferChangeMode("<<<->>>")}var h=a("../c_class"),i=a("../c_registry"),j=a("milo-core").proto,k=h.createComponentClass("MLList",{dom:{cls:"ml-ui-list"},data:void 0,events:void 0,model:void 0,list:void 0});i.add(k),b.exports=k,j.extendProto(k,{init:c,destroy:d,removeItem:e,moveItem:f})},{"../c_class":15,"../c_registry":32,"milo-core":105}],53:[function(a,b){"use strict";function c(){q.prototype.init.apply(this,arguments),this.on("childrenbound",d)}function d(){var a=this.container.scope.deleteBtn;a&&a.events.on("click",{subscriber:this.removeItem,context:this})}function e(){try{var a=this.item.list.owner}catch(b){}a&&a.removeItem(this.item.index)}function f(a){var b=this.item.list.owner;b&&b.moveItem(this.item.index,a)}function g(a){return a.params&&a.params.index&&"MLListItem"==a.compClass}function h(){return this.isDropAllowed.apply(this,arguments)}function i(a,b){k.call(this);var c=new r(b),d=c.getComponentMeta(),e=c.getComponentState(),f=this.item.list.owner,g=d.params&&d.params.index;f.moveItem(+g,this.item.index,e)}function j(){this.dom.addCssClasses("ml-drag-over")}function k(){this.dom.removeCssClasses("ml-drag-over")}function l(){return{index:this.item.index}}function m(){var a=this.model.get();return null!==a&&"object"==typeof a?t.clone(a):a}function n(a){return"object"==typeof a&&this.data._set(a),this.model.set(a),p.call(this),a}function o(){this.data._del(),this.model.del(),p.call(this)}function p(){this.data.dispatchSourceMessage(u)}var q=a("../c_class"),r=a("../../util/dragdrop"),s=a("../c_registry"),t=a("milo-core").proto,u="mllistitemchange",v=q.createComponentClass("MLListItem",{container:void 0,dom:void 0,drag:{meta:{params:l}},drop:{messages:{dragenter:{subscriber:j,context:"owner"},dragover:{subscriber:j,context:"owner"},dragleave:{subscriber:k,context:"owner"},drop:{subscriber:i,context:"owner"}},allow:{components:h}},data:{get:m,set:n,del:o,event:u},model:void 0,item:void 0});s.add(v);var v=b.exports=v;t.extendProto(v,{init:c,moveItem:f,removeItem:e,isDropAllowed:g})},{"../../util/dragdrop":82,"../c_class":15,"../c_registry":32,"milo-core":105}],54:[function(a,b){"use strict";function c(){o.defineProperty(this,"_radioList",[],o.CONF),o.defineProperty(this,q,r+n()),this._renderOptions={},l.prototype.init.apply(this,arguments)}function d(a){this._renderOptions=a}function e(a){var b,c=this._radioList;return c.length?(c.forEach(function(c){c.checked=c.value==a,c.checked&&(b=a)}),i.call(this),b):void 0}function f(){var a=o.find(this._radioList,function(a){return a.checked});return a&&a.value||void 0}function g(){var a=this._radioList;return a.length&&a.forEach(function(a){a.checked=!1}),void i.call(this)}function h(a,b){"radio"==b.target.type&&i.call(this)}function i(){this.data.dispatchSourceMessage(p)}function j(){this.template.render({radioOptions:this.model.get(),elementName:this[q],_renderOptions:this._renderOptions});var a=this.el.querySelectorAll('input[type="radio"]'),b=o.toArray(a);this._radioList.length=0,this._radioList.splice.apply(this._radioList,[0,0].concat(b))}function k(){delete this._radioList,l.prototype.destroy.apply(this,arguments)}var l=a("../c_class"),m=a("../c_registry"),n=a("../../util/count"),o=a("milo-core").proto,p="mlradiogroupchange",q="_mlRadioGroupElementID",r="ml-radio-group-",s=l.createComponentClass("MLRadioGroup",{data:{set:e,get:f,del:g,splice:void 0,event:p},model:{messages:{"***":{subscriber:j,context:"owner"}}},events:{messages:{click:{subscriber:h,context:"owner"}}},container:void 0,dom:{cls:"ml-ui-radio-group"},template:{template:'{{~ it.radioOptions :option }} {{##def.elID:{{= it.elementName }}-{{= option.value }}#}} <span class="{{= it._renderOptions.optionCssClass || "'+r+'option" }}"> <input id="{{# def.elID }}" type="radio" value="{{= option.value }}" name="{{= it.elementName }}"> <label for="{{# def.elID }}">{{= option.label }}</label> </span> {{~}}'}});m.add(s),b.exports=s,o.extendProto(s,{init:c,destroy:k,setRenderOptions:d})},{"../../util/count":77,"../c_class":15,"../c_registry":32,"milo-core":105}],55:[function(a,b){"use strict";function c(a){var b={context:this,subscriber:e};this.model.off("**",b),this.model.set(a),this.model.on("**",b),e.call(this)}function d(a){this.el.disabled=a}function e(){this.template.render({selectOptions:this.model.get()})}var f=a("../c_class"),g=a("../c_registry"),h=a("milo-core").proto,i=f.createComponentClass("MLSelect",{dom:{cls:"ml-ui-select"},data:void 0,events:void 0,model:{messages:{"**":{subscriber:e,context:"owner"}}},template:{template:'{{~ it.selectOptions :option }} <option value="{{= option.value }}" {{? option.selected }}selected{{?}}>{{= option.label }}</option> {{~}}'}});g.add(i),b.exports=i,h.extendProto(i,{setOptions:c,disable:d})},{"../c_class":15,"../c_registry":32,"milo-core":105}],56:[function(a,b){"use strict";function c(){K.prototype.init.apply(this,arguments),this.once("childrenbound",d),N.defineProperties(this,{_optionsData:[],_filteredOptionsData:[]},N.WRIT)}function d(){this.template.render().binder(),e.call(this)}function e(){var a=this.container.scope;N.defineProperties(this,{_comboInput:a.input,_comboList:a.list,_comboOptions:a.options,_comboBefore:a.before,_comboAfter:a.after,_comboAddItemDiv:a.addItemDiv,_comboAddPrompt:a.addPrompt,_comboAddBtn:a.addBtn,_optionTemplate:O.compile(S)}),N.defineProperties(this,{_startIndex:0,_endIndex:T,_hidden:!1,_elementHeight:V,_total:0,_optionsHeight:200,_lastScrollPos:0,_currentValue:null,_selected:null,_isAddButtonShown:!1},N.WRIT),this.dom.setStyles({position:"relative"}),p(this._comboList,this._comboOptions,this),q(this._comboInput,this),r(this._comboAddBtn,this),this.events.on("keydown",{subscriber:y,context:this})}function f(a){this._hidden=!a,this._comboList.dom.toggle(a)}function g(){this._hidden=!1,this.el.classList.add(Q),this._comboList.dom.toggle(!0)}function h(){this._hidden=!0,this.el.classList.remove(Q),this._comboList.dom.toggle(!1)}function i(a,b){this._comboAddItemDiv.dom.toggle(a),b&&b.preserveState&&(this.__showAddOnClick=this._isAddButtonShown),this._isAddButtonShown=a}function j(a){this._addItemPrompt=a,this._comboAddPrompt.el.innerHTML=a,this.toggleAddButton(!1)}function k(a){this._optionsData=a,this.setFilteredOptions(a)}function l(a){this._optionsURL=a.url,this._formatOptionsURL=a.formatOptions||function(a){return a}}function m(a){var b=this._optionsURL,c=this._comboInput.data.get();a=a||N.noop,milo.util.request.post(b,{name:c},function(b,d){if(b)return P.error('Can not search for "'+c+'"'),a(new Error("Request error"));var e=N.jsonParse(d);e?a(null,e):a(new Error("Data error"))})}function n(a){return a?(this._filteredOptionsData=a,this._total=a.length,void this.update()):P.error("setFilteredOptions: parameter is undefined")}function o(){var a=this._hidden,b=this._filteredOptionsData.slice(this._startIndex,this._endIndex);this._comboOptions.template.render({comboOptions:b}),this._elementHeight=this._elementHeight||V,a&&this.hideOptions();var c=this._startIndex*this._elementHeight,d=(this._total-this._endIndex)*this._elementHeight;this._comboBefore.el.style.height=c+"px",this._comboAfter.el.style.height=d>0?d+"px":"0px"}function p(a,b,c){c.toggleAddButton(!1),b.template.set(S),a.dom.setStyles({overflow:"scroll",height:c._optionsHeight+"px",width:"100%",position:"absolute",zIndex:10}),c.hideOptions(),a.events.onMessages({click:{subscriber:G,context:c},scroll:{subscriber:H,context:c}})}function q(a,b){a.events.once("focus",function(){a.data.on("",{subscriber:v,context:b}),a.events.on("click",{subscriber:D,context:b}),a.events.on("keydown",{subscriber:E,context:b})})}function r(a,b){a.events.on("click",{subscriber:F,context:b})}function s(){return this._currentValue}function t(a){this._currentValue=a,this._comboInput.data.set(a&&a.label),N.deferMethod(this,"hideOptions")}function u(){this._currentValue=null,this._comboInput.data.set("")}function v(a,b){var c=b.newValue&&b.newValue.trim();if(this._optionsURL){var d=this;m.call(this,function(a,b){if(!a&&b)try{var e=b.data.map(d._formatOptionsURL);d.setOptions(e),x.call(d,c,d._optionsData)}catch(f){P.error("Data error",f)}})}else{var e=w.call(this,c);x.call(this,c,e)}}function w(a){return this._optionsData.filter(function(b){if(delete b.selected,b.label){var c=b.label.toLowerCase();return 0==c.trim().toLowerCase().indexOf(a.toLowerCase())}})}function x(a,b){function c(b){return b.label.toLowerCase()===a.toLowerCase()}a?(b.length&&N.find(b,c)?this.toggleAddButton(!1,{preserveState:!0}):this._addItemPrompt&&this.toggleAddButton(this._optionsData.length>1||this._optionsURL),b.length?(this.showOptions(),b[0].selected=!0,this._selected=b[0]):this.hideOptions()):this.toggleAddButton(!1,{preserveState:!0}),this.setFilteredOptions(b),this._comboList.el.scrollTop=0}function y(a,b){var c=X[b.keyCode];c&&z.call(this,c)}function z(a){var b=this.el.querySelectorAll(".selected")[0],c=this._comboList.el.scrollTop,d=b?b.offsetTop:0,e=d-c;if(b){var f=I.call(this,b),g=this._filteredOptionsData[f],h=this._filteredOptionsData[f+a];h&&(delete g.selected,h.selected=!0,this._selected=h,this.update())}else this._filteredOptionsData[0]&&(this._filteredOptionsData[0].selected=!0,this.update());e>this._optionsHeight-2*this._elementHeight&&1===a&&(this._comboList.el.scrollTop+=this._elementHeight*a*5),e<this._elementHeight&&-1===a&&(this._comboList.el.scrollTop+=this._elementHeight*a*5)}function A(){this._mouseIsOver=!0}function B(){var a=this;this._mouseIsOver=!1,this._mouseOutTimer&&clearInterval(this._mouseOutTimer),this._mouseOutTimer=setTimeout(function(){a._mouseIsOver||C.call(a)},750)}function C(){this.hideOptions(),this.toggleAddButton(!1,{preserveState:!0})}function D(){this.showOptions(),this.__showAddOnClick&&this.toggleAddButton(!0)}function E(a,b){13==b.keyCode&&this._selected&&J.call(this)}function F(){var a={label:this._comboInput.el.value};this.postMessage("additem",a),this.events.postMessage("milo_supercomboadditem",a),this.toggleAddButton(!1,{preserveState:!0})}function G(a,b){var c=I.call(this,b.target),d=this._filteredOptionsData[c];this._selected=d,J.call(this),this.update()}function H(a,b){var c=b.target.scrollTop,d=c>this._lastScrollPos?"down":"up",e=this._comboOptions.el.lastElementChild,f=this._comboOptions.el.firstElementChild,g=e?e.offsetTop:0,h=f?f.offsetTop:0,i=g-c-this._optionsHeight+this._elementHeight,j=c-h,k=Math.floor(j/this._elementHeight),l=Math.floor(i/this._elementHeight),m=Math.floor(c/this._elementHeight)-U;("down"==d&&U>l||"up"==d&&U>k)&&(this._startIndex=m>0?m:0,this._endIndex=m+T,this._elementHeight=e.style.height,this.update()),this._lastScrollPos=c}function I(a){return Number(a.getAttribute("data-value"))+this._startIndex}function J(){delete this._selected.selected,this.hideOptions(),this.toggleAddButton(!1),this._comboInput.data.off("",{subscriber:v,context:this}),this.data.set(this._selected),this.data.dispatchSourceMessage(R),this._comboInput.data.on("",{subscriber:v,context:this}),this._selected=null,this.setFilteredOptions(this._optionsData)}var K=a("../c_class"),L=a("../c_registry"),M=a("milo-core"),N=M.proto,O=M.util.doT,P=M.util.logger,Q="ml-ui-supercombo-open",R="mlsupercombochange",S='{{~ it.comboOptions :option:index }} <div {{? option.selected}}class="selected" {{?}}data-value="{{= index }}">{{= option.label }}</div> {{~}}',T=100,U=25,V=20,W=K.createComponentClass("MLSuperCombo",{events:{messages:{mouseleave:{subscriber:B,context:"owner"},mouseover:{subscriber:A,context:"owner"}}},data:{get:s,set:t,del:u,splice:void 0,event:R},dom:{cls:"ml-ui-supercombo"},template:{template:'<input ml-bind="[data, events]:input" class="form-control ml-ui-input"> <div ml-bind="[dom]:addItemDiv" class="ml-ui-supercombo-add"> <span ml-bind=":addPrompt"></span> <button ml-bind="[events, dom]:addBtn" class="btn btn-default ml-ui-button">Add</button> </div> <div ml-bind="[dom, events]:list" class="ml-ui-supercombo-dropdown"> <div ml-bind="[dom]:before"></div> <div ml-bind="[template, dom, events]:options" class="ml-ui-supercombo-options"></div> <div ml-bind="[dom]:after"></div> </div>'},container:void 0});L.add(W),b.exports=W,N.extendProto(W,{init:c,showOptions:g,hideOptions:h,toggleOptions:f,setOptions:k,initOptionsURL:l,setFilteredOptions:n,update:o,toggleAddButton:i,setAddItemPrompt:j,clearComboInput:u});var X={40:1,38:-1}},{"../c_class":15,"../c_registry":32,"milo-core":105}],57:[function(a,b){"use strict";var c=a("../c_class"),d=a("../c_registry"),e=c.createComponentClass("MLText",{data:void 0,events:void 0,dom:{cls:"ml-ui-text"}});d.add(e),b.exports=e},{"../c_class":15,"../c_registry":32}],58:[function(a,b){"use strict";function c(a){return this._autoresize?m.warn("MLTextarea startAutoresize: autoresize is already on"):(this._autoresize=!0,this._autoresizeOptions=a,e.call(this),void d.call(this,"on"))}function d(a){this.events[a]("click",{subscriber:e,context:this}),this.data[a]("",{subscriber:e,context:this})}function e(){this.el.style.height=0;var a=this.el.scrollHeight,b=this._autoresizeOptions.minHeight,c=this._autoresizeOptions.maxHeight;a=a>=c?c:b>=a?b:a,this.el.style.height=a+"px"}function f(){return this._autoresize?(this._autoresize=!1,void d.call(this,"off")):m.warn("MLTextarea stopAutoresize: autoresize is not on")}function g(){return this._autoresize}function h(a){this.el.disabled=a}var i=a("../c_class"),j=a("../c_registry"),k=a("milo-core"),l=k.proto,m=k.util.logger,n=i.createComponentClass("MLTextarea",{data:void 0,events:void 0,dom:{cls:"ml-ui-textarea"}});j.add(n),b.exports=n;l.extendProto(n,{startAutoresize:c,stopAutoresize:f,isAutoresized:g,disable:h})},{"../c_class":15,"../c_registry":32,"milo-core":105}],59:[function(a,b){"use strict";function c(){var a=this.el.value,b=a.match(j);if(b){var c=b[1],d=b[2];if(!(c>23||d>59)){var e=new Date(1970,0,1,c,d);return h.toDate(e)}}}function d(a){function b(a){return 10>a?"0"+a:a}var c=h.toDate(a);if(!c)return void(this.el.value="");var d=k.replace("hh",b(c.getHours())).replace("mm",b(c.getMinutes()));return this.el.value=d,d}function e(){this.el.value=""}var f=a("../c_class"),g=a("../c_registry"),h=a("milo-core").proto,i=f.createComponentClass("MLTime",{events:void 0,data:{get:c,set:d,del:e},dom:{cls:"ml-ui-time"}});g.add(i),b.exports=i;var j=/^([0-9]{1,2})(?:\:|\.)([0-9]{1,2})$/,k="hh:mm"},{"../c_class":15,"../c_registry":32,"milo-core":105}],60:[function(a,b){"use strict";var c=a("../c_class"),d=a("../c_registry"),e=c.createComponentClass("MLWrapper",{container:void 0,data:void 0,events:void 0,dom:{cls:"ml-ui-wrapper"}});d.add(e),b.exports=e},{"../c_class":15,"../c_registry":32}],61:[function(a,b){"use strict";function c(a){m(a,{message:String,type:n.Optional(String),close:n.Optional(Boolean),timeout:n.Optional(Number)});var b=q.createOnElement();a=f(a);var c=p[a.type];b.dom.addCssClasses(c),b._alert={options:a,visible:!1},b.template.render(a).binder();var d=b.container.scope;if(a.close&&d.closeBtn.events.on("click",{subscriber:e,context:b}),a.timeout){setTimeout(function(){b._alert.visible&&b.closeAlert()},a.timeout)}return b}function d(a){var b=q.createAlert(a);return b.openAlert(),b}function e(){this.closeAlert()}function f(a){return a=o.clone(a),a.close="undefined"==typeof a.close||a.close===!0,a.timeout=Math.floor(a.timeout),a.type=a.type||"info",a}function g(){i.call(this,!0)}function h(){i.call(this,!1),this.destroy()}function i(a){a="undefined"==typeof a?!this._alert.visible:!!a;var b=a?"add":"remove",c=a?"appendChild":"removeChild";this._alert.visible=a,document.body[c](this.el),this.dom.toggle(a),this.el.setAttribute("aria-hidden",!a),this.el.classList[b]("in"),this.el[a?"focus":"blur"]()}var j=a("../../c_class"),k=a("../../c_registry"),l=(a("../../../util/component_name"),a("milo-core")),m=(l.util.logger,l.util.check),n=m.Match,o=l.proto,p={success:"alert-success",warning:"alert-warning",info:"alert-info",danger:"alert-danger",fixed:"alert-fixed"},q=j.createComponentClass("MLAlert",{container:void 0,events:void 0,dom:{cls:["ml-bs-alert","alert","fade"],attributes:{role:"alert","aria-hidden":"true"}},template:{template:' {{? it.close }} <button ml-bind="[events]:closeBtn" type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> {{?}} {{= it.message}}'}});k.add(q),b.exports=q,o.extend(q,{createAlert:c,openAlert:d}),o.extendProto(q,{openAlert:g,closeAlert:h})},{"../../../util/component_name":76,"../../c_class":15,"../../c_registry":32,"milo-core":105}],62:[function(a,b){"use strict";function c(a,b){v(a,{title:w.Optional(String),html:w.Optional(String),text:w.Optional(String),close:w.Optional(w.OneOf(Boolean,{backdrop:w.Optional(Boolean),keyboard:w.Optional(Boolean),button:w.Optional(Boolean)})),buttons:w.Optional([{name:w.Optional(String),type:String,label:String,close:w.Optional(Boolean),result:w.Optional(String),data:w.Optional(w.Any),cls:w.Optional(String)}])});var c=A.createOnElement();a=i(a),c._dialog={options:a,visible:!1},c.template.render(a).binder();var e=c.container.scope;return a.close.backdrop&&c.events.on("click",{subscriber:f,context:c}),a.title&&a.close.button&&e.closeBtn.events.on("click",{subscriber:g,context:c}),a.buttons.forEach(function(a){var b={subscriber:x.partial(d,a),context:c};e[a.name].events.on("click",b)}),b&&b(c),c}function d(a){a.close!==!1&&k.call(this,!1);var b=x.result(a.data,this,a);e.call(this,a.result,b)}function e(a,b){var c=this._dialog.subscriber;"function"==typeof c?c.call(this,a,b):c.subscriber.call(c.context,a,b)}function f(a,b){b.target==this.el&&this.closeDialog("dismissed")}function g(){this.closeDialog("closed")}function h(a){D&&D._dialog.options.close.keyboard&&27==a.keyCode&&D.closeDialog("dismissed")}function i(a){return a=x.clone(a),a.buttons=x.clone(a.buttons||y),a.buttons.forEach(function(a){a.name=a.name||s()}),a.close="undefined"==typeof a.close||a.close===!0?x.object(z,!0):"object"==typeof a.close?x.mapToObject(z,function(b){return a.close[b]!==!1}):x.object(z,!1),a}function j(a,b,c){var d=A.createDialog(a,c);return d.openDialog(b),d}function k(a){a="undefined"==typeof a?!this._dialog.visible:!!a;var b=a?"add":"remove",c=a?"appendChild":"removeChild";this._dialog.visible=a,a&&!B&&l(),document.body[c](this.el),C&&document.body[c](C),this.dom.toggle(a),this.el.setAttribute("aria-hidden",!a),document.body.classList[b]("modal-open"),this.el.classList[b]("in"),D=a?this:void 0,this.el[a?"focus":"blur"]()}function l(){C=document.createElement("div"),C.className="modal-backdrop fade in",document.addEventListener("keydown",h),B=!0}function m(a){return v(a,w.OneOf(Function,{subscriber:Function,context:w.Any})),D?u.warn("MLDialog openDialog: can't open dialog, another dialog is already open"):(this._dialog.subscriber=a,void k.call(this,!0))}function n(a,b){return D?(a=a||"closed",k.call(this,!1),void e.call(this,a,b)):u.warn("MLDialog closeDialog: can't close dialog, no dialog open")}function o(){return D}function p(){document.removeEventListener("keydown",h),q.prototype.destroy.apply(this,arguments)}var q=a("../../c_class"),r=a("../../c_registry"),s=a("../../../util/component_name"),t=a("milo-core"),u=t.util.logger,v=t.util.check,w=v.Match,x=t.proto,y=[{type:"default",label:"OK",result:"OK"}],z=["backdrop","keyboard","button"],A=q.createComponentClass("MLDialog",{container:void 0,events:void 0,dom:{cls:["ml-bs-dialog","modal","fade"],attributes:{role:"dialog","aria-hidden":"true"}},template:{template:' <div class="modal-dialog"> <div class="modal-content"> {{? it.title }} <div class="modal-header"> {{? it.close.button }} <button ml-bind="[events]:closeBtn" type="button" class="close">&times;</button> {{?}} <h4 class="modal-title">{{= it.title }}</h4> </div> {{?}} {{? it.html || it.text }} <div class="modal-body" ml-bind="[container]:dialogBody"> {{? it.html }} {{= it.html }} {{??}} <p>{{= it.text }}</p> {{?}} </div> {{?}} {{? it.buttons && it.buttons.length }} <div class="modal-footer"> {{~ it.buttons :btn }} <button type="button" class="btn btn-{{= btn.type }}{{? btn.cls }} {{= btn.cls }}{{?}}" ml-bind="[events]:{{= btn.name }}">{{= btn.label }}</button> {{~}} </div> {{?}} </div> </div>'}});r.add(A),b.exports=A,x.extend(A,{createDialog:c,openDialog:j,getOpenedDialog:o}),x.extendProto(A,{openDialog:m,closeDialog:n,destroy:p});var B,C,D},{"../../../util/component_name":76,"../../c_class":15,"../../c_registry":32,"milo-core":105}],63:[function(a,b){"use strict";function c(){function a(a){var c=a.target,e=a.relatedTarget,f=i._dropdown.listeners;d(c)&&f.remove(c.contentWindow.document,"click",b),d(e)&&f.add(e.contentWindow.document,"click",b)}function b(a){i.el.contains(a.target)||i.hideMenu()}var c=this.el.querySelector("."+o),e=this.el.querySelector("."+p);if(!c||!e)return m.error("MLDropdown:",o,"or",p,"isn't found");var f=window.document,g=this.toggleMenu.bind(this,void 0),h=new n;this._dropdown={menu:e,visible:!1,listeners:h},this.hideMenu();var i=this;h.add(c,"click",g),h.add(f,"mouseout",a),h.add(f,"click",b)}function d(a){return a&&"IFRAME"==a.tagName}function e(){this._dropdown.listeners.removeAll(),delete this._dropdown,i.prototype.destroy.apply(this,arguments)}function f(){this.toggleMenu(!0)}function g(){this.toggleMenu(!1)}function h(a){a="undefined"==typeof a?!this._dropdown.visible:!!a,this._dropdown.visible=a;var b=this._dropdown.menu;b.style.display=a?"block":"none"}var i=a("../../c_class"),j=a("../../c_registry"),k=a("milo-core"),l=k.proto,m=k.util.logger,n=a("../../../util/dom_listeners"),o="dropdown-toggle",p="dropdown-menu",q=i.createComponentClass("MLDropdown",{events:void 0,dom:{cls:["ml-bs-dropdown","dropdown"]}});j.add(q),b.exports=q,l.extendProto(q,{start:c,destroy:e,toggleMenu:h,showMenu:f,hideMenu:g})},{"../../../util/dom_listeners":80,"../../c_class":15,"../../c_registry":32,"milo-core":105}],64:[function(a,b){"use strict";var c=a("milo-core"),d=(c.proto,c.util.doT),e=b.exports=c.config;e({attrs:{bind:"ml-bind",load:"ml-load"},componentRef:"___milo_component",componentPrefix:"milo_",template:{compile:d.compile},domStorage:{typeSuffix:":___milo_data_type",prefixSeparator:"/",root:"",messageKey:"___milo_message/",messageTimestamp:"___milo_timestamp",quotaExceeded:{throwError:!0,message:!1}},dragDrop:{dataTypes:{component:"x-application/milo/component",componentMetaTemplate:"x-application/milo/component-meta/%class/%name/%params",componentMetaRegex:/^x\-application\/milo\/component\-meta\/([a-z0-9]+)\/([a-z0-9]+)\/([a-z0-9]*)$/}},request:{jsonpTimeout:6e4,jsonpCallbackPrefix:"___milo_callback_",optionsKey:"___milo_options",defaults:{timeout:6e4}},websocket:{rpc:{timeout:15e3,responsePrefix:"response_"}}})},{"milo-core":105}],65:[function(a,b){"use strict";function c(a,b,c){milo(function(){d(a,b,c)})}function d(a,b,c){"function"==typeof a&&(c=a,a=void 0,b=!1),"function"==typeof b&&(c=b,b=!1),a=a||document.body,g.postMessage("loader",{state:"started"}),e(a,b,function(a){g.postMessage("loader",{state:"finished",views:a}),c(a)})}function e(a,b,c){var d=a.getAttribute(l.attrs.load)?[a]:a.querySelectorAll("["+l.attrs.load+"]"),e={},g=d.length,h=0;j.forEach(d,function(a){f(a,b,function(b){e[a.id]=b||a,h++,h==g&&c(e)})})}function f(a,b,c){if(k.children(a).length)throw new Error("can't load html into element that is not empty");var d=new m(a);d.parse().validate(),h.get(d.loadUrl,function(e,f){return e?(e.message=e.message||"can't load file "+d.loadUrl,void c(e)):(a.innerHTML=f,b&&m.remove(a),void c(null))})}var g=a("./services/mail"),h=a("./util/request"),i=a("milo-core"),j=(i.util.logger,i.proto),k=a("./util/dom"),l=a("./config"),m=a("./attributes/a_load");b.exports=c},{"./attributes/a_load":6,"./config":64,"./services/mail":70,"./util/dom":79,"./util/request":87,"milo-core":105}],66:[function(a,b){"use strict";function c(a){c.util.domReady(a)}function d(){e.destroy(),c.mail.destroy(),c.window.destroy(),c.util.destroy()}var e=a("milo-core"),f=e.proto;a("./use_facets"),a("./use_components"),f.extend(c,{Messenger:e.Messenger,Model:e.Model,minder:e.minder,loader:a("./loader"),binder:a("./binder"),mail:a("./services/mail"),window:a("./services/window"),config:a("./config"),util:a("./util"),classes:a("./classes"),attributes:a("./attributes"),ComponentFacet:a("./components/c_facet"),Component:a("./components/c_class"),Command:a("./command"),registry:a("./registry"),milo_version:"0.1.10",createComponentClass:a("./util/create_component_class"),destroy:d}),"object"==typeof b&&b.exports&&(b.exports=c),"object"==typeof window&&(window.milo=c,c.mail.trigger("miloready"))},{"./attributes":7,"./binder":8,"./classes":9,"./command":12,"./components/c_class":15,"./components/c_facet":16,"./config":64,"./loader":65,"./registry":67,"./services/mail":70,"./services/window":73,"./use_components":74,"./use_facets":75,"./util":85,"./util/create_component_class":78,"milo-core":105}],67:[function(a,b){"use strict"; b.exports={facets:a("./components/c_facets/cf_registry"),components:a("./components/c_registry"),commands:a("./command/cmd_registry")}},{"./command/cmd_registry":11,"./components/c_facets/cf_registry":30,"./components/c_registry":32}],68:[function(a,b){"use strict";var c=a("milo-core").proto,d={ClipboardEvent:["copy","cut","paste","beforecopy","beforecut","beforepaste"],Event:["input","readystatechange"],FocusEvent:["focus","blur","focusin","focusout"],KeyboardEvent:["keydown","keypress","keyup"],MouseEvent:["click","contextmenu","dblclick","mousedown","mouseup","mouseenter","mouseleave","mousemove","mouseout","mouseover","show"],TouchEvent:["touchstart","touchend","touchmove","touchenter","touchleave","touchcancel"]};if("undefined"!=typeof window)var e=window;else e={},c.eachKey(d,function(a,b){var d=c.makeFunction(b,"type","properties","this.type = type; _.extend(this, properties);");e[b]=d});var f={};c.eachKey(d,function(a,b){a.forEach(function(a){if(Object.hasOwnProperty(f,a))throw new Error("duplicate event type "+a);f[a]=e[b]})}),b.exports=f},{"milo-core":105}],69:[function(a,b){"use strict";function c(a,b,c,d){this.eventEmitter=d,k.prototype.init.apply(this,arguments)}function d(){k.prototype.destroy.apply(this,arguments),delete this.eventEmitter}function e(){return this.eventEmitter}function f(a,b){if(b&&"string"==typeof b){var c=q.test(b);b=b.replace(q,""),this.emitter()[a](b,this,c)}}function g(a){var b;"undefined"!=typeof window&&(b=a.eventPhase==window.Event.CAPTURING_PHASE),b&&(a+=r),this.dispatchMessage(a.type,a)}function h(a,b){this.messenger.postMessageSync(a,b)}function i(a,b){n(a,String),n(b,o.Optional(Object)),a=a.replace(q,"");var c=l[a];if("function"!=typeof c)throw new Error("unsupported event type");"undefined"!=typeof b&&(b.type=a);var d=new c(a,b),e=this.emitter().dispatchEvent(d);return e}var j=a("milo-core"),k=j.classes.MessageSource,l=(a("../components/c_class"),a("./de_constrs")),m=j.proto,n=j.util.check,o=n.Match,p=m.createSubclass(k,"DOMEmitterSource",!0);m.extendProto(p,{init:c,destroy:d,addSourceSubscriber:m.partial(f,"addEventListener"),removeSourceSubscriber:m.partial(f,"removeEventListener"),postMessage:h,trigger:i,emitter:e,handleEvent:g}),b.exports=p;var q=/__capture$/,r="__capture"},{"../components/c_class":15,"./de_constrs":68,"milo-core":105}],70:[function(a,b){"use strict";var c=a("milo-core"),d=c.Messenger,e=a("./mail_api"),f=a("./mail_source"),g=(c.proto,new d),h=new f(g,{trigger:"trigger"},new e);g._setMessageSource(h),b.exports=g},{"./mail_api":71,"./mail_source":72,"milo-core":105}],71:[function(a,b){"use strict";function c(a){return"domready"==a?"readystatechange":j.test(a)?"message":void 0}function d(a,b,c){return"readystatechange"==a?!0:"message"==a?k+c.data.type==b:void 0}var e=a("milo-core"),f=e.classes.MessengerAPI,g=e.proto,h=e.util.check,i=(h.Match,g.createSubclass(f,"MailMsgAPI",!0));g.extendProto(i,{translateToSourceMessage:c,filterSourceMessage:d}),b.exports=i;var j=/^message\:/,k="message:"},{"milo-core":105}],72:[function(a,b){"use strict";function c(a){if(e(a))if("loading"==document.readyState)document.addEventListener("readystatechange",this,!1);else{var b=l.readystatechange,c=new b("readystatechange",{target:document});this.dispatchMessage("readystatechange",c)}else this._windowSubscriberMethod("addEventListener",a)}function d(a){e(a)?document.removeEventListener("readystatechange",this,!1):this._windowSubscriberMethod("removeEventListener",a)}function e(a){return"readystatechange"==a&&"object"==typeof document}function f(a){return"message"==a&&"object"==typeof window}function g(a,b){f(b)&&window[a]("message",this,!1)}function h(a){this.dispatchMessage(a.type,a)}function i(a,b){b=b||{},b.type="message:"+a,"object"==typeof window&&window.postMessage(b,"*")}var j=a("milo-core"),k=j.classes.MessageSource,l=a("../de_constrs"),m=j.proto,n=j.util.check,o=(n.Match,m.createSubclass(k,"MailMessageSource",!0));m.extendProto(o,{addSourceSubscriber:c,removeSourceSubscriber:d,trigger:i,_windowSubscriberMethod:g,handleEvent:h}),b.exports=o},{"../de_constrs":68,"milo-core":105}],73:[function(a,b){"use strict";function c(){return window.top==window.self||window.__karma__}var d=a("milo-core"),e=d.Messenger,f=a("./dom_source"),g=d.proto,h=new e,i=new f(h,{trigger:"trigger"},void 0,window);h._setMessageSource(i),b.exports=h,g.extend(h,{isTop:c})},{"./dom_source":69,"milo-core":105}],74:[function(a){"use strict";a("./components/classes/View"),a("./components/ui/Group"),a("./components/ui/Wrapper"),a("./components/ui/Text"),a("./components/ui/Select"),a("./components/ui/Input"),a("./components/ui/InputList"),a("./components/ui/Textarea"),a("./components/ui/RadioGroup"),a("./components/ui/Button"),a("./components/ui/Hyperlink"),a("./components/ui/List"),a("./components/ui/ListItem"),a("./components/ui/Time"),a("./components/ui/Date"),a("./components/ui/Combo"),a("./components/ui/SuperCombo"),a("./components/ui/ComboList"),a("./components/ui/Image"),a("./components/ui/DropTarget"),a("./components/ui/FoldTree"),a("./components/ui/bootstrap/Dropdown")},{"./components/classes/View":34,"./components/ui/Button":41,"./components/ui/Combo":42,"./components/ui/ComboList":43,"./components/ui/Date":44,"./components/ui/DropTarget":45,"./components/ui/FoldTree":46,"./components/ui/Group":47,"./components/ui/Hyperlink":48,"./components/ui/Image":49,"./components/ui/Input":50,"./components/ui/InputList":51,"./components/ui/List":52,"./components/ui/ListItem":53,"./components/ui/RadioGroup":54,"./components/ui/Select":55,"./components/ui/SuperCombo":56,"./components/ui/Text":57,"./components/ui/Textarea":58,"./components/ui/Time":59,"./components/ui/Wrapper":60,"./components/ui/bootstrap/Dropdown":63}],75:[function(a){"use strict";a("./components/c_facets/Dom"),a("./components/c_facets/Data"),a("./components/c_facets/Frame"),a("./components/c_facets/Events"),a("./components/c_facets/Options"),a("./components/c_facets/Template"),a("./components/c_facets/Container"),a("./components/c_facets/ModelFacet"),a("./components/c_facets/Drag"),a("./components/c_facets/Drop"),a("./components/c_facets/List"),a("./components/c_facets/Item"),a("./components/c_facets/Transfer")},{"./components/c_facets/Container":17,"./components/c_facets/Data":18,"./components/c_facets/Dom":19,"./components/c_facets/Drag":20,"./components/c_facets/Drop":21,"./components/c_facets/Events":22,"./components/c_facets/Frame":23,"./components/c_facets/Item":24,"./components/c_facets/List":25,"./components/c_facets/ModelFacet":26,"./components/c_facets/Options":27,"./components/c_facets/Template":28,"./components/c_facets/Transfer":29}],76:[function(a,b){"use strict";function c(){return f+d()}var d=a("./count"),e=a("../config"),f=e.componentPrefix;b.exports=c},{"../config":64,"./count":77}],77:[function(a,b){"use strict";function c(){var a=Date.now();return f=""+a,d==a?(e=""===e?0:e+1,f+="_"+e):(d=a,e=""),f}var d=Date.now(),e="",f=""+d;c.get=function(){return f},b.exports=c},{}],78:[function(a,b){"use strict";function c(a){var b=milo.registry.components,c=b.get(a.superClassName||"Component"),e=c.createComponentClass(a.className,a.facets);if(a.methods&&d.extendProto(e,a.methods),a.staticMethods){if(void 0!==a.staticMethods["super"])throw"'super' is a reserved keyword";d.extend(e,a.staticMethods)}return e["super"]=c.prototype,b.add(e),e}var d=a("milo-core").proto;b.exports=c},{"milo-core":105}],79:[function(a,b){"use strict";function c(a){return d(a.childNodes,Node.ELEMENT_NODE)}function d(a,b){return N.filter(a,function(a){return a.nodeType==b})}function e(a){for(;a;){if(a.nodeType==Node.ELEMENT_NODE)return a;a=a.parentNode}return null}function f(a){var b=a.ownerDocument;if(!b)return O.error("selectElementContents: element has no document");var c=b.createRange();c.selectNodeContents(a);var d=F(a),e=d.getSelection();e.removeAllRanges(),e.addRange(c)}function g(a){var b=p(a),c=q(a);b&&c&&k(b,0,c,c.textContent.length)}function h(a,b){var c=a.ownerDocument;if(!c)return O.error("setCaretPosition: element has no document");var d=c.createRange();d.setStart(a,b);var e=F(a),f=e.getSelection();f.removeAllRanges(),f.addRange(d)}function i(a){return j(a.anchorNode,a.anchorOffset,a.focusNode,a.focusOffset)}function j(a,b,c,d){var e=a.compareDocumentPosition(c);return e&Node.DOCUMENT_POSITION_FOLLOWING?1:e&Node.DOCUMENT_POSITION_PRECEDING?-1:a==c?d>b?1:b>d?-1:0:void 0}function k(a,b,c,d){var e=a.ownerDocument;if(!e)return O("setCaretPosition: element has no document");var f,g,h=-1==j(a,b,c,d),i=e.createRange(),k=F(a),l=k.getSelection();h?(i.setStart(c,d),i.setEnd(a,b),i.collapse(!1)):(i.setStart(a,b),i.setEnd(c,d)),f=i.commonAncestorContainer==Node.ELEMENT_NODE?i.commonAncestorContainer:i.commonAncestorContainer.parentElement,f.isContentEditable||(g=f.contentEditable,f.contentEditable="true"),l.removeAllRanges(),l.addRange(i),h&&l.extend(c,d),g&&(f.contentEditable=g)}function l(a){a=a||window;var b=a.getSelection();b.removeAllRanges()}function m(a,b){var c,d;for(c=a.offsetTop,d=a.offsetLeft,a=a.offsetParent;a;)c+=a.offsetTop+n(a,"Height",b),d+=a.offsetLeft+n(a,"Width",b),a=a.offsetParent;return{topOffset:c,leftOffset:d}}function n(a,b,c){if(c){var d="Height"==b?"top":"left",e=window.getComputedStyle(a),f=parseInt(e.getPropertyValue("border-"+d+"-width"),10);if(f)return f}return 0}function o(a){var b=a.parentNode;b&&(b.removeChild(a),b.normalize())}function p(a){if(a.nodeType==Node.TEXT_NODE)return a;var b=E(a,NodeFilter.SHOW_TEXT);return b.firstChild()}function q(a){if(a.nodeType==Node.TEXT_NODE)return a;var b=E(a,NodeFilter.SHOW_TEXT);return b.lastChild()}function r(a){var b=a.parentNode;if(b){var c=document.createDocumentFragment(),d=N.slice(a.childNodes);d.forEach(c.appendChild,c),b.replaceChild(c,a),b.normalize()}}function s(a,b){var c=b.parentNode;c&&(c.insertBefore(a,b),a.appendChild(b))}function t(a){return v(a,"trimRight")}function u(a){return v(a,"trimLeft")}function v(a,b){var c=a.length;return a.textContent=a.textContent[b](),c!==a.length}function w(a){delete a[L.componentRef]}function x(a){var b=document.createElement("DIV");return b.innerHTML=a,b.textContent||""}function y(a,b,c,d){for(var e=document.createTreeWalker(a,b);e.nextNode();){var f=c.call(d||a,e.currentNode);if(f===!1)break}}function z(a,b){function c(a){return a.contains(b)}if(a&&a.contains(b)){for(var d=[],e=a;e!=b;){var f=N.findIndex(e.childNodes,c);d.push(f),e=e.childNodes[f]}return d}}function A(a,b,c){if(b){var d=b.length;if(0===d)return a;for(var e=a,f=0;d>f;f++){var g=e.childNodes;if(!g){c||(e=void 0);break}var h=b[f],i=g[h];if(!i){e=c?g[g.length-1]:void 0;break}e=i}return e}}function B(a,b,c,d){var e=c.nodeType==Node.TEXT_NODE;if(a.contains(c)&&o(c),0!=b.length){var f=A(a,b.slice(0,-1),d),g=f.childNodes;if(!g){if(!d)return;f=f.parentNode,g=f.childNodes}var h=b[b.length-1],i=g[h];return i?(f.insertBefore(c,i),e&&f.normalize(),!0):0!==g.length||0!==h&&!d?(i=g[h-1],i||d?(f.appendChild(c),e&&f.normalize(),!0):void 0):(f.appendChild(c),e&&f.normalize(),!0)}}function C(a,b){var c,d=0;if(!Array.isArray(a)&&Array.isArray(b))return O.error("isTreePathBefore: One or both paths are not valid treepath arrays.");for(d;d<a.length;d++){if(a[d]<b[d]){c=!0;break}if(a[d]>b[d]){c=!1;break}}return"undefined"==typeof c&&a.length<b.length&&O.warn("isTreePathBefore: One node is inside another"),c||!1}function D(a){return a.replace(/[\u00A0-\u99999<>\&]/gim,function(a){return"&#"+a.charCodeAt(0)+";"})}function E(a,b){return b=b||NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,document.createTreeWalker(a,b)}function F(a){var b=a.ownerDocument;return b&&(b.defaultView||b.parentWindow)}function G(a,b){function c(b){var c=document.createRange(),d=!1;return c.selectNode(b),-1!=c.compareBoundaryPoints(window.Range.START_TO_START,a)&&1!=c.compareBoundaryPoints(window.Range.END_TO_END,a)&&(d=!0),c.detach(),d}for(var d,e=a.commonAncestorContainer,f=e.ownerDocument,g=f.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);d=g.nextNode();)c(d)&&b(d)}function H(a){var b=F(a.startContainer),c=b.milo.Component,d=[];return G(a,function(a){if(a.nodeType!=Node.TEXT_NODE){var b=c.getComponent(a);b&&d.push(b)}}),d}function I(a){var b=H(a);b.forEach(function(a){a.destroy(!0)}),a.deleteContents()}function J(a,b){return 0==a.compareBoundaryPoints(window.Range.START_TO_START,b)&&0==a.compareBoundaryPoints(window.Range.END_TO_END,b)}function K(a,b){var c=document.createElement("div");c.setAttribute("style","width: 1px; height: 1px; position:fixed; left:"+a+"px; top:"+b+"px; background-color:red; z-index: 100"),setTimeout(function(){document.body.appendChild(c)},200)}var L=a("../config"),M=a("milo-core"),N=M.proto,O=M.util.logger,P={children:c,filterNodeListByType:d,containingElement:e,selectElementContents:f,selectElementText:g,getElementOffset:m,setCaretPosition:h,getSelectionDirection:i,setSelection:k,clearSelection:l,removeElement:o,unwrapElement:r,wrapInElement:s,detachComponent:w,firstTextNode:p,lastTextNode:q,trimNodeRight:t,trimNodeLeft:u,stripHtml:x,htmlEntities:D,walkTree:y,createTreeWalker:E,treePathOf:z,getNodeAtTreePath:A,insertAtTreePath:B,isTreePathBefore:C,getNodeWindow:F,getComponentsFromRange:H,deleteRangeWithComponents:I,forEachNodesInRange:G,areRangesEqual:J,addDebugPoint:K};b.exports=P},{"../config":64,"milo-core":105}],80:[function(a,b){"use strict";function c(){this.listeners=[]}function d(a,b,c){this.listeners.push({target:a,eventType:b,handler:c}),a.addEventListener(b,c)}function e(a,b,c){var d={target:a,eventType:b,handler:c},e=h.findIndex(this.listeners,h.partial(h.isEqual,d));e>-1&&(this.listeners.splice(e,1),g(d))}function f(){this.listeners.forEach(g),this.listeners=[]}function g(a){a.target.removeEventListener(a.eventType,a.handler)}var h=a("milo-core").proto;b.exports=c,h.extendProto(c,{add:d,remove:e,removeAll:f})},{"milo-core":105}],81:[function(a,b){"use strict";function c(a){function b(){a.apply(c,i)}var c=this,i=f.slice(arguments,1);e.call(this)?b():(h||(document.addEventListener("readystatechange",d),h=!0),g.push(b))}function d(){document.removeEventListener("readystatechange",d),g.forEach(function(a){a()})}function e(){var a=document.readyState;return"loading"==a?!1:a}var f=a("milo-core").proto;b.exports=c;var g=[],h=!1;f.extend(c,{isReady:e})},{"milo-core":105}],82:[function(a,b){"use strict";function c(a){this.event=a,this.dataTransfer=a.dataTransfer,this.types=a.dataTransfer.types}function d(){return A.dataTypes.component}function e(){return C.indexOf(this.types,c.componentDataType())>=0}function f(){var a=c.componentDataType(),b=this.dataTransfer.getData(a),d=C.jsonParse(b);return d}function g(a,b){if(!b){var d=a.getTransferState({requestedBy:"drag"});b=JSON.stringify(d)}var e=c.componentDataType();return b&&this.dataTransfer.setData(e,b),this.dataTransfer.setData("text/html",a.el.outerHTML),b}function h(a,b,c){var d=j(a),e=C.toQueryString(b),f=A.dataTypes.componentMetaTemplate.replace("%class",i(d.compClass||"")).replace("%name",i(d.compName||"")).replace("%params",i(e||""));return c&&"object"==typeof c&&(c=JSON.stringify(c)),this.dataTransfer.setData(f,c||""),f}function i(a){return D.encode(a).toLowerCase()}function j(a){return a.transfer?a.transfer.getComponentMeta():{compClass:a.constructor.name,compName:a.name}}function k(){var a,b=C.find(this.types,function(b){return a=b.match(B),!!a});if(b){for(var c=1;4>c;c++)a[c]=D.decode(a[c]);return{compClass:a[1],compName:a[2],params:C.fromQueryString(a[3]),metaDataType:b,metaData:C.jsonParse(this.dataTransfer.getData(b))?C.jsonParse(this.dataTransfer.getData(b)):this.dataTransfer.getData(b)}}}function l(){return this.dataTransfer.effectAllowed}function m(a){this.dataTransfer.effectAllowed=a}function n(){return this.dataTransfer.dropEffect}function o(a){this.dataTransfer.dropEffect=a}function p(a){var b=this.getAllowedEffects(),c="copy"==a,d="move"==a,e="link"==a,f=c||e||d;switch(b){case"copy":case"move":case"link":return b==a;case"copyLink":return c||e;case"copyMove":return c||d;case"linkMove":return e||d;case"all":case"uninitialized":return f;case"none":return!1}}function q(a){return this.dataTransfer.getData(a)}function r(a,b){this.dataTransfer.setData(a,b)}function s(a){this.dataTransfer.clearData(a)}function t(a,b){E=b.dragDrop,F=b.dragFacet}function u(a,b){F&&F.postMessageSync("dragdropcompleted",b),E=void 0,F=void 0}function v(a,b){E&&G.postMessageSync("dragdropcompleted",b)}function w(){return E}function x(){G.offAll()}var y=(a("../components/c_class"),a("milo-core")),z=y.Messenger,A=a("../config").dragDrop,B=A.dataTypes.componentMetaRegex,C=y.proto,D=a("base32");b.exports=c,C.extend(c,{componentDataType:d}),C.extendProto(c,{isComponent:e,getComponentState:f,setComponentState:g,getComponentMeta:k,setComponentMeta:h,getAllowedEffects:l,setAllowedEffects:m,getDropEffect:n,setDropEffect:o,isEffectAllowed:p,getData:q,setData:r,clearData:s});var E,F,G=new z;C.extend(c,{service:G,destroy:x}),G.onMessages({dragdropstarted:t,dragdropcompleted:u,completedragdrop:v}),C.extend(G,{getCurrentDragDrop:w})},{"../components/c_class":15,"../config":64,base32:95,"milo-core":105}],83:[function(a,b){"use strict";function c(a){var b=e.makeFunction(a,"message",'this.name = "'+a+'"; this.message = message || "There was an error";');return e.makeSubclass(b,Error),b}function d(){throw new g.AbstractClass("calling the method of an absctract class")}var e=a("milo-core").proto,f=["AbstractClass","Mixin","Messenger","Component","Attribute","Binder","Loader","MailMessageSource","Facet","Scope","Model","DomFacet","EditableFacet","List","Connector","Registry","FrameMessageSource","Drop","Angular","StorageMessageSource"],g={toBeImplemented:d,createClass:c};f.forEach(function(a){g[a]=c(a+"Error")}),b.exports=g},{"milo-core":105}],84:[function(a,b){"use strict";function c(a,b,c){var d=f(a);if(!d)return void s.error("fragment.getState: range has no common container");var i=a.cloneContents(),j=e(i,c);g(d,j),b&&h(j);var k=j.getState();return t.deferMethod(j,"destroy"),k}function d(a,b,c){try{var d=f(a);if(!d)return void c(new Error("fragment.getState: range has no common container"));"function"==typeof b&&(c=b,b=!1);var i=a.cloneContents(),j=e(i);g(d,j),t.defer(function(){j.broadcast("stateready"),t.defer(function(){b&&h(j);var a=j.getState();j.destroy(),c(null,a)})})}catch(k){c(k)}}function e(a,b){var c=document.createElement("div"),d=new o(c);t.extend(d,{compClass:b||"Component",compFacets:b?[]:["container"],compName:"wrapper"}),d.decorate(),c.appendChild(a);var e=p(c);return e.wrapper}function f(a){var b=q.containingElement(a.commonAncestorContainer);return n.getContainingComponent(b,!0,"container")}function g(a,b){var c=a.container.scope;b.container.scope._each(function(a,b){var d=c[b];if(!d)return s.error("fragment.getState: conponent",b,"not found in range");var e=d._getState(!0);a.setState(e)})}function h(a){a.container.scope._each(function(a){a.rename()})}function i(a){var b=k(a);return a=j(b)}function j(a){var b=document.createRange();return a.siblings?(b.setStartBefore(a.start),b.setEndAfter(a.end)):b.selectNode(a.start),b}function k(a){var b=a.commonAncestorContainer,c=a.startContainer,d=a.endContainer;if(c==d)return c!=b&&s.error("deleteSelectionCommand logical error: start==end, but container is different"),{siblings:!1,start:c};if(c==b||d==b)return{siblings:!1,start:b};var e=l(b,c),f=l(b,d);return e&&f?e==f?(s.error("deleteSelectionCommand logical error: same siblings"),{siblings:!1,start:e}):{siblings:!0,start:e,end:f}:void 0}function l(a,b){return t.find(a.childNodes,function(a){return a.contains(b)})}function m(a){return function(b,c){var d={siblings:c.siblings,start:a(b,c.start)};return d.siblings&&(d.end=a(b,c.end)),d}}{var n=a("../components/c_class"),o=a("../attributes/a_bind"),p=a("../binder"),q=a("./dom"),r=a("milo-core"),s=r.util.logger,t=(r.util.check,r.proto),u=m(q.treePathOf),v=m(q.getNodeAtTreePath);b.exports={getState:c,getStateAsync:d,expandRangeToSiblings:i,getRangeSiblings:k,createRangeFromSiblings:j,createRangeFromNodes:j,createRangePaths:u,createRangeNodes:v}}},{"../attributes/a_bind":4,"../binder":8,"../components/c_class":15,"./dom":79,"milo-core":105}],85:[function(a,b){"use strict";function c(){e.request.destroy(),e.dragDrop.destroy()}var d=a("milo-core"),e={logger:d.util.logger,request:a("./request"),websocket:a("./websocket"),check:d.util.check,error:a("./error"),count:a("./count"),uniqueId:a("./count"),componentName:a("./component_name"),dom:a("./dom"),domListeners:a("./dom_listeners"),selection:a("./selection"),fragment:a("./fragment"),jsonParse:a("./json_parse"),storage:a("./storage"),domReady:a("./domready"),dragDrop:a("./dragdrop"),dialog:a("../components/ui/bootstrap/Dialog"),alert:a("../components/ui/bootstrap/Alert"),doT:d.util.doT,destroy:c};b.exports=e},{"../components/ui/bootstrap/Alert":61,"../components/ui/bootstrap/Dialog":62,"./component_name":76,"./count":77,"./dom":79,"./dom_listeners":80,"./domready":81,"./dragdrop":82,"./error":83,"./fragment":84,"./json_parse":86,"./request":87,"./selection":88,"./storage":89,"./websocket":92,"milo-core":105}],86:[function(a,b){"use strict";function c(a){try{return JSON.parse(a)}catch(b){}}b.exports=c},{}],87:[function(a,b){"use strict";function c(a){return function(){var b=Promise.prototype[a].apply(this,arguments);return f(b,this._request),b}}function d(a,b,c){function f(a){h(i,c,j,a.type)}b.url=a,b.contentType=b.contentType||"application/json;charset=UTF-8",z&&d.postMessageSync("request",{options:b});var i=new XMLHttpRequest;i.open(b.method,b.url,!0),i.setRequestHeader("Content-Type",b.contentType),g(i,b.headers),i.timeout=b.timeout||t.request.defaults.timeout,i.onreadystatechange=i.ontimeout=i.onabort=f;var j=e(i);return i.send(JSON.stringify(b.data)),i[t.request.optionsKey]=b,w.push(i),j.promise}function e(a){var b,c,d=new Promise(function(a,d){b=a,c=d});return f(d,a),d["catch"](r.noop),{promise:d,resolve:b,reject:c}}function f(a,b){return a._request=b,a.then=x,a["catch"]=y,a}function g(a,b){b&&r.eachKey(b,function(b,c){a.setRequestHeader(c,b)})}function h(a,b,c,e){function f(b){z&&d.postMessage(b,{status:status,response:a.responseText})}if(4==a.readyState&&(a.status||"readystatechange"!=e)){r.spliceItem(w,a);var g;try{if(a.status>=200&&a.status<400){try{f("success"),b&&b(null,a.responseText,a)}catch(h){g=h}c.resolve(a.responseText)}else{var i=a.status||e;try{f("error"),f("error"+i),b&&b(i,a.responseText,a)}catch(h){g=h}c.reject({reason:i,response:a.responseText})}}catch(h){g=g||h}if(a.onreadystatechange=a.ontimeout=a.onabort=void 0,w.length||f("requestscompleted"),g)throw new Error("Exception: "+g)}}function i(){z=new v(d,["on","once","onSync","off","onMessages","offMessages","postMessage","postMessageSync"])}function j(a,b){return d(a,{method:"GET"},b)}function k(a,b,c){return d(a,{method:"POST",data:b},c)}function l(a,b){var c=d(a,{method:"GET"}),e=c.then(JSON.parse);return b&&e.then(function(a){b(null,a)})["catch"](function(a){b(a.reason,a.response)}),e}function m(a,b){function c(a,c){r.spliceItem(w,window[k]);try{g(a?"error":"success",a,c),a&&(u.error("No JSONP response or timeout"),g("errorjsonptimeout",a)),b&&b(a,c)}catch(d){var e=d}if(a?i.reject(a):i.resolve(c),f(),w.length||g("requestscompleted"),e)throw e}function f(){clearTimeout(m),j.removeChild(h),delete window[k]}function g(a,b,c){z&&d.postMessage(a,{status:b,response:c})}var h=document.createElement("script"),i=e(h),j=window.document.head,k=t.request.jsonpCallbackPrefix+s(),l=r.extend({url:a},A);z&&d.postMessageSync("request",{options:l}),r.isEqual(r.omitKeys(l,"url"),A)||u.warn("Ignored not allowed request options change in JSONP request - only URL can be changed");var m=setTimeout(function(){var a=new Error("No JSONP response or no callback in response");c(a)},t.request.jsonpTimeout);return window[k]=r.partial(c,null),w.push(window[k]),h.type="text/javascript",h.src=l.url+(-1==l.url.indexOf("?")?"?":"&")+"callback="+k,j.appendChild(h),i.promise}function n(a,b,c,f){function i(a){f&&(j.upload.onprogress=void 0),h(j,c,k,a.type)}"string"==typeof a&&(a={method:"POST",url:a}),a.method=a.method||"POST",a.file=!0,z&&d.postMessageSync("request",{options:a});var j=new XMLHttpRequest;f&&(j.upload.onprogress=f),j.open(a.method,a.url,!0),g(j,a.headers),j.timeout=a.timeout||t.request.defaults.timeout,j.onreadystatechange=j.ontimeout=j.onabort=i;var k=e(j);if(a.binary)j.send(b);else{var l=new FormData;l.append("file",b),j.send(l)}return w.push(j),k.promise}function o(){z&&z.destroy(),d._destroyed=!0}function p(a,b){a=r.once(a),b&&r.delay(a,b,"timeout"),w.length?z.once("requestscompleted",a):r.defer(a)}var q=a("milo-core"),r=q.proto,s=a("./count"),t=a("../config"),u=q.util.logger,v=q.Messenger;b.exports=d;var w=[],x=c("then"),y=c("catch");r.extend(d,{get:j,post:k,json:l,jsonp:m,file:n,useMessenger:i,destroy:o,whenRequestsCompleted:p});var z,A={method:"GET",jsonp:!0}},{"../config":64,"./count":77,"milo-core":105}],88:[function(a,b){"use strict";function c(a){return!this instanceof c?new c(a):(this.window=a||window,void this.init())}function d(){this.selection=this.window.getSelection(),this.selection.rangeCount&&(this.range=this.selection.getRangeAt(0)),this.isCollapsed=this.selection.isCollapsed}function e(){return this.range?(this._text||(this._text=this.range.toString()),this._text):void 0}function f(){return this.range?(this._textNodes||(this._textNodes=h.call(this)),this._textNodes):void 0}function g(){this.selection.removeAllRanges()}function h(){var a=[];if(this.isCollapsed)return a;for(var b=this.range.startContainer,c=this.range.endContainer,d=this.range.commonAncestorContainer,e=this.window.document.createTreeWalker(d,NodeFilter.SHOW_TEXT),f=e.currentNode=b;f&&(!g||c.contains(f));){a.push(f);var g=g||c.contains(f);f=e.nextNode()}return a}function i(a,b){return this.range?("undefined"==typeof this[a]&&(this[a]=z(this.range[b])),this[a]):void 0}function j(a,b){return this.range?("undefined"==typeof this[a]&&(this[a]=F.getContainingComponent(this[b]())),this[a]):void 0}function k(){if(this._containedComponents)return this._containedComponents;var a=this._containedComponents=[];return this.isCollapsed||!this.range?a:B(this.range)}function l(a,b){if(!this.isCollapsed&&this.range){var c=this.containedComponents();c.forEach(a,b)}}function m(a){if(!this.isCollapsed&&this.range){var b=this._getPostDeleteSelectionPoint(a);C(this.range),this._selectAfterDelete(b),b.node.parentNode.normalize()}}function n(a){var b=this.range.startContainer,c=this.range.startOffset;return a&&this.range.startContainer!=this.range.endContainer&&(b=this.range.endContainer,c=0),{node:b,offset:c}}function o(a){var b=a.node,c=a.offset;if(b){b.nodeType==Node.TEXT_NODE&&(b.textContent=b.textContent.trimRight()),b.nodeValue||(b.nodeValue=" ");var d=c>b.length?b.length:c;A(b,d)}}function p(){return this.range}function q(a){var b=this.range,d=a.ownerDocument,e=d.defaultView||d.parentWindow;return b?c.createStateObject(a,b.startContainer,b.startOffset,b.endContainer,b.endOffset):{window:e}}function r(a,b,c,d,e){d=d||b,e=e||c;var f=a.ownerDocument,g=f.defaultView||f.parentWindow;return{window:g,rootEl:a,start:s(a,b,c),end:s(a,d,e)}}function s(a,b,c){var d=y.treePathOf(a,b);return d||E.error("Selection point is outside of root element"),{treePath:d,offset:c}}function t(a){var b=a.window.milo.util.dom;if(!(a.rootEl&&a.start&&a.end))return b.clearSelection(a.window),new c(a.window);var d=u(a.rootEl,a.start),e=u(a.rootEl,a.end);try{return b.setSelection(d,a.start.offset,e,a.end.offset),new c(a.window)}catch(f){E.error("Text selection: can't create selection",f,f.message)}}function u(a,b){var c=y.getNodeAtTreePath(a,b.treePath);return c||E.error("TextSelection createFromState: no node at treePath"),c}function v(a,b){var d,e=a.startContainer.ownerDocument.defaultView,f=e.getSelection();return f.removeAllRanges(),b?(d=a.cloneRange(),d.collapse(!1),f.addRange(d),f.extend(a.startContainer,a.startOffset)):f.addRange(a),new c(e)}function w(){var a,b,c=this.range.commonAncestorContainer.ownerDocument,d=this.range.cloneRange();return d.endContainer.nodeType!==Node.TEXT_NODE&&(a=c.createTreeWalker(c.body,NodeFilter.SHOW_TEXT),a.currentNode=d.endContainer,b=a.previousNode(),d.setEnd(b,b.length)),d}function x(){return y.getSelectionDirection(this.selection)}var y=a("../dom"),z=y.containingElement,A=y.setCaretPosition,B=y.getComponentsFromRange,C=y.deleteRangeWithComponents,D=a("milo-core"),E=D.util.logger,F=a("../../components/c_class"),G=D.proto;b.exports=c;var H=G.partial(i,"_startElement","startContainer"),I=G.partial(i,"_endElement","endContainer"),J=G.partial(i,"_containingElement","commonAncestorContainer"),K=G.partial(j,"_startComponent","startElement"),L=G.partial(j,"_endComponent","endElement"),M=G.partial(j,"_containingComponent","containingElement");G.extendProto(c,{init:d,text:e,textNodes:f,clear:g,startElement:H,endElement:I,containingElement:J,startComponent:K,endComponent:L,containingComponent:M,containedComponents:k,eachContainedComponent:l,del:m,_getPostDeleteSelectionPoint:n,_selectAfterDelete:o,getRange:p,getState:q,getNormalizedRange:w,getDirection:x}),G.extend(c,{createFromRange:v,createFromState:t,createStateObject:r})},{"../../components/c_class":15,"../dom":79,"milo-core":105}],89:[function(a,b){"use strict";function c(a,b,c){"undefined"!=typeof window&&(c=c||window,a=B.domStorage.root+(a?a+B.domStorage.prefixSeparator:""),C.defineProperties(this,{keyPrefix:a,sessionOnly:!!b,window:c,_storage:b?c.sessionStorage:c.localStorage,_typeSuffix:B.domStorage.typeSuffix,_keys:{}},C.WRIT))}function d(a){if("object"==typeof a)C.eachKey(a,function(a,b){this.setItem(b,a)},this);else{var b=arguments.length;if(b%2)throw new DomStorageError("DOMStorage: set should have even number of arguments or object");for(var c=0;b>c;c++){var d=arguments[c],e=arguments[++c];this.setItem(d,e)}}}function e(){var a={};return C.deepForEach(arguments,function(b){a[b]=this.getItem(b)},this),a}function f(){C.deepForEach(arguments,function(a){this.removeItem(a)},this)}function g(a){var b=this._storageKey(a);return null!=this._storage.getItem(b)}function h(a){var b=this._storageKey(a),c=o.call(this,b),d=this._storage.getItem(b),e=u(d,c);return e}function i(a,b){var c=this._storageKey(a),d=p.call(this,c,b),e=t(b,d);try{this._storage.setItem(c,e)}catch(f){if("QuotaExceededError"!=f.name)throw f;var g=B.domStorage.quotaExceeded;if(g.message&&milo.mail.postMessage("quotaexceedederror",b),g.throwError)throw f}this._keys[a]=!0,H[this.sessionOnly]._keys[c]=!0}function j(a){var b=this._storageKey(a);this._storage.removeItem(b),q.call(this,b),delete this._keys[a],delete H[this.sessionOnly]._keys[b]}function k(){var a=Object.keys(this._keys),b=a.filter(function(a){return this.hasItem(a)?!0:void delete this._keys[a]},this);return b}function l(){return this.get(this.getAllKeys())}function m(a){return this.keyPrefix+a}function n(a){return a.indexOf(this._typeSuffix)>=0?void 0:C.unPrefix(a,this.keyPrefix)}function o(a){return a=r.call(this,a),this._storage.getItem(a)}function p(a,b){var c=s(b);return a=r.call(this,a),this._storage.setItem(a,c),c}function q(a){a=r.call(this,a),this._storage.removeItem(a)}function r(a){return a+this._typeSuffix}function s(a){var b=typeof a,c=a&&a.constructor.name,d=I[c];return d||("object"!=b?b:null==a?"null":a.constructor.name)}function t(a,b){b=b||s(a);var c=J[b];return c?c(a,b):a&&a.toString==Object.prototype.toString?JSON.stringify(a):""+a}function u(a,b){var c=K[b];return c?c(a,b):a}function v(a,b,c,d){b&&(J[a]=b),c&&(K[a]=c),I[a]=d||a}function w(){var a=new A(this),b=new z(this,void 0,a);C.defineProperties(this,{_messenger:b,_messageSource:a},C.WRIT)}function x(){this._storage=void 0,this.window=void 0,this._messenger&&this._messenger.destroy(),this._destroyed=!0}{var y=a("milo-core"),z=y.Messenger,A=a("./msg_src"),B=a("../../config"),C=y.proto,D=y.util.check;D.Match}a("./model"),b.exports=c;var E={"true":{},"false":{}};C.extendProto(c,{get:e,set:d,remove:f,hasItem:g,getItem:h,setItem:i,removeItem:j,_storageKey:m,_domStorageKey:n,getAllKeys:k,getAllItems:l,createMessenger:w,destroy:x}),z.useWith(c,"_messenger",z.defaultMethods),A.useWith(c,"_messageSource",["trigger"]); var F=new c("",!0),G=new c("",!1),H={"true":F,"false":G};C.extend(c,{registerDataType:v,local:G,session:F,storage:H,_storedKeys:E});var I={},J={Array:JSON.stringify},K={Object:C.jsonParse,Array:C.jsonParse,Date:function(a){return new Date(a)},"boolean":function(a){return"true"==a},number:Number,"function":C.toFunction,RegExp:C.toRegExp}},{"../../config":64,"./model":90,"./msg_src":91,"milo-core":105}],90:[function(a){"use strict";function b(){var b=a("./index");b.registerDataType("Model",c,d),b.registerDataType("ModelPath",c,d,"Model")}function c(a){var b=a.get();return JSON.stringify(b)}function d(a){var b=g.jsonParse(a);return new f(b)}var e=a("milo-core"),f=e.Model,g=e.proto;f.registerWithDOMStorage=b},{"./index":89,"milo-core":105}],91:[function(a,b){"use strict";function c(a){if("DOMStorage"!=a.constructor.name)throw new Error("hostObject should be an instance of DOMStorage");this.storage=a,this.messageKey=l.domStorage.messageKey,this.window=a.window,j.prototype.init.apply(this,arguments)}function d(){this.window.addEventListener("storage",this,!1)}function e(){this.window.removeEventListener("storage",this,!1)}function f(a,b){this.messenger.postMessageSync(a,b)}function g(a,b){var c=this.messageKey+a;b=b||{},b[l.domStorage.messageTimestamp]=m(),k.deferMethod(this.storage,"setItem",c,b)}function h(a){if(a.storageArea==this.storage._storage){var b=this.storage._domStorageKey(a.key);if(b){var c=k.unPrefix(b,this.messageKey);if(c){var d=this.storage.getItem(b);d&&this.dispatchMessage(c,d)}}}}var i=a("milo-core"),j=i.classes.MessageSource,k=i.proto,l=a("../../config"),m=a("../../util/count"),n=k.createSubclass(j,"StorageMessageSource",!0);k.extendProto(n,{init:c,addSourceSubscriber:d,removeSourceSubscriber:e,postMessage:f,trigger:g,handleEvent:h}),b.exports=n},{"../../config":64,"../../util/count":77,"milo-core":105}],92:[function(a,b){"use strict";function c(){var a=new d,b=new e(a,{send:"trigger",connect:"connect"},new f);return a._setMessageSource(b),a}var d=a("milo-core").Messenger,e=a("./msg_src"),f=a("./msg_api");b.exports=c},{"./msg_api":93,"./msg_src":94,"milo-core":105}],93:[function(a,b){"use strict";function c(a){return k.indexOf(a)>=0?a:"message"}function d(a,b,c){if(k.indexOf(b)>=0)return!0;if("message"==a){var d=c&&c.type;return d==b}}function e(a,b,c){var d="message"==a?h.jsonParse(c.data)||c.data:c;return d}var f=a("milo-core"),g=f.classes.MessengerAPI,h=f.proto,i=f.util.check,j=(i.Match,h.createSubclass(g,"WSMsgAPI",!0));h.extendProto(j,{translateToSourceMessage:c,filterSourceMessage:d,createInternalData:e}),b.exports=j;var k=["open","close","error","message"]},{"milo-core":105}],94:[function(a,b){"use strict";function c(a){this._options=a=a||{};var b=a.host||window.location.host.replace(/:.*/,""),c=a.port||"8080";this._ws&&(this._ws.onopen=this.ws.onmessage=this.ws.onclose=this.ws.onerror=void 0,this._ws.close()),this._ws=new WebSocket("ws://"+b+":"+c)}function d(a){f.call(this,"addEventListener",a)}function e(a){f.call(this,"removeEventListener",a)}function f(a,b){return this._ws?void this._ws[a](b,this):l.error("websocket is not created")}function g(a){this.dispatchMessage(a.type,a)}function h(a,b,c){function d(){f("off",b.callbackCorrId),c(new Error("websocket rpc: timeout"))}function e(a,b){if(clearInterval(h),"object"==typeof b){var d=b.error?new Error(b.error):null;c(d,b.data)}else c(new Error("websocket rpc: invalid response data"),b)}function f(a,b){g.messenger[a](n.websocket.rpc.responsePrefix+b,e)}if(!this._ws)return l.error("websocket is not created");b=b||{},b.type=a;var g=this;if(c){b.callbackCorrId=m();var h=k.delay(d,n.websocket.rpc.timeout);f("once",b.callbackCorrId)}this._ws.send(JSON.stringify(b))}var i=a("milo-core"),j=i.classes.MessageSource,k=i.proto,l=i.util.logger,m=a("../../util/count"),n=a("../../config"),o=i.util.check,p=(o.Match,k.createSubclass(j,"WSMessageSource",!0));k.extendProto(p,{addSourceSubscriber:d,removeSourceSubscriber:e,handleEvent:g,connect:c,trigger:h}),b.exports=p},{"../../config":64,"../../util/count":77,"milo-core":105}],95:[function(a,b){!function(){function a(){var a=0,b=0;this.output="",this.readByte=function(c){return"string"==typeof c&&(c=c.charCodeAt(0)),0>a?b|=c>>-a:b=c<<a&248,a>3?(a-=8,1):(4>a&&(this.output+=f[b>>3],a+=5),0)},this.finish=function(c){var d=this.output+(0>a?f[b>>3]:"")+(c?"$":"");return this.output="",d}}function c(){var a=0,b=0;this.output="",this.readChar=function(c){"string"!=typeof c&&"number"==typeof c&&(c=String.fromCharCode(c)),c=c.toLowerCase();var d=h()[c];"undefined"!=typeof d&&(d<<=3,b|=d>>>a,a+=5,a>=8&&(this.output+=String.fromCharCode(b),a-=8,b=a>0?d<<5-a&255:0))},this.finish=function(b){var c=this.output+(0>a?f[bits>>3]:"")+(b?"$":"");return this.output="",c}}function d(b){var c=new a,d=c.update(b,!0);return d}function e(a){var b=new c,d=b.update(a,!0);return d}var f="0123456789abcdefghjkmnpqrtuvwxyz",g={o:0,i:1,l:1,s:5},h=function(){for(var a={},b=0;b<f.length;b++)a[f[b]]=b;for(var c in g)g.hasOwnProperty(c)&&(a[c]=a[""+g[c]]);return h=function(){return a},a};a.prototype.update=function(a,b){for(var c=0;c<a.length;)c+=this.readByte(a[c]);var d=this.output;return this.output="",b&&(d+=this.finish()),d},c.prototype.update=function(a,b){for(var c=0;c<a.length;c++)this.readChar(a[c]);var d=this.output;return this.output="",b&&(d+=this.finish()),d};var i={Decoder:c,Encoder:a,encode:d,decode:e};"undefined"!=typeof window&&(window.base32=i),"undefined"!=typeof b&&b.exports&&(b.exports=i)}()},{}],96:[function(){},{}],97:[function(a,b){"use strict";function c(a,b){l(a,m.Optional(m.OneOf(Object,Function))),k.defineProperty(this,"_hostObject",a),b&&this._createProxyMethods(b),this.init&&this.init.apply(this,arguments)}function d(a,b,c){if(c=c||this._hostObject,c[a])throw new Error("method "+a+" already defined in host object");var d=this[b];l(d,Function);var e=d.bind(this);k.defineProperty(c,a,e,k.WRIT)}function e(a,b){l(a,m.Optional(m.OneOf([String],m.ObjectHash(String)))),Array.isArray(a)?a.forEach(function(a){d.call(this,a,a,b)},this):k.eachKey(a,function(a,c){d.call(this,c,a,b)},this)}function f(a,b,c){l(a,Function),l(c,m.IdentifierString);var d=n.mixin.instancePropertiesMap,e=a[d]=a[d]||{};if(e[b.name])throw new Error("Mixin: instance property for method with name "+b.name+" is already set");e[b.name]=c}function g(a,b,c,d){var e=this.prototype[c];l(e,Function);var g=h.call(this,e);k.defineProperty(a.prototype,d,g,k.WRIT),f(a,e,b)}function h(a){return function(){var b=i.call(this,a.name);return a.apply(b,arguments)}}function i(a){if(this instanceof c)return this;var b=this.constructor[n.mixin.instancePropertiesMap];return this[b[a]]}function j(a,b,c){l(c,m.Optional(m.OneOf([String],m.ObjectHash(String)))),Array.isArray(c)?c.forEach(function(c){g.call(this,a,b,c,c)},this):k.eachKey(c,function(c,d){g.call(this,a,b,c,d)},this)}var k=a("mol-proto"),l=a("../util/check"),m=l.Match,n=a("../config");b.exports=c,k.extendProto(c,{_createProxyMethod:d,_createProxyMethods:e}),k.extend(c,{useWith:j})},{"../config":99,"../util/check":116,"mol-proto":122}],98:[function(a,b){"use strict";var c={Mixin:a("./abstract/mixin"),MessageSource:a("./messenger/m_source"),MessengerMessageSource:a("./messenger/msngr_source"),MessengerAPI:a("./messenger/m_api"),MessengerRegexpAPI:a("./messenger/m_api_rx")};b.exports=c},{"./abstract/mixin":97,"./messenger/m_api":101,"./messenger/m_api_rx":102,"./messenger/m_source":103,"./messenger/msngr_source":104}],99:[function(a,b){"use strict";function c(a){d.deepExtend(c,a)}var d=a("mol-proto");b.exports=c,c({mixin:{instancePropertiesMap:"___mixin_instances"},check:!0,debug:!1})},{"mol-proto":122}],100:[function(a,b){"use strict";function c(a,b,c){c&&this._setMessageSource(c),d.call(this)}function d(){I.defineProperties(this,{_messageSubscribers:{},_patternMessageSubscribers:{}},I.CONF)}function e(){this.offAll();var a=this.getMessageSource();a&&a.destroy()}function f(a,b){return k.call(this,a,b)}function g(a,b){return k.call(this,a,b,{dispatchTimes:1})}function h(a,b){return k.call(this,a,b,{dispatchTimes:1,sync:!0})}function i(a,b){return k.call(this,a,b,{sync:!0})}function j(a,b){return k.call(this,a,b,{sync:!1})}function k(a,b,c){return J(a,K.OneOf(String,[String],RegExp)),J(b,K.OneOf(Function,{subscriber:Function,context:K.Any,options:K.Optional(Object)})),"function"==typeof b&&(b={subscriber:b,context:this._hostObject}),c&&(b.options=b.options||{},I.extend(b.options,c)),l.call(this,a,b)}function l(a,b){return I.defineProperty(b,"__messages",a),m.call(this,"_registerSubscriber",a,b)}function m(a,b,c){"string"==typeof b&&(b=b.split(M));var d=this._chooseSubscribersHash(b);if(b instanceof RegExp)return this[a](d,b,c);var e=!1;return b.forEach(function(b){var f=this[a](d,b,c);e=e||f},this),e}function n(a,b,c){if(!a[b]||!a[b].length){a[b]=[],b instanceof RegExp&&(a[b].pattern=b),this._messageSource&&this._messageSource.onSubscriberAdded(b);var d=!0}var e=a[b],f=d||-1==o.call(this,e,c);return f&&e.push(c),f}function o(a,b){return I.findIndex(a,function(a){return b.subscriber==a.subscriber&&b.context==a.context})}function p(a){J(a,K.ObjectHash(K.OneOf(Function,{subscriber:Function,context:K.Any})));var b=I.mapKeys(a,function(a,b){return this.on(b,a)},this);return b}function q(a,b){return J(a,K.OneOf(String,[String],RegExp)),J(b,K.Optional(K.OneOf(Function,{subscriber:Function,context:K.Any,options:K.Optional(Object)}))),r.call(this,a,b)}function r(a,b){return m.call(this,"_removeSubscriber",a,b)}function s(a,b,c){var d=a[b];if(!d||!d.length)return!1;if(c){"function"==typeof c&&(c={subscriber:c,context:this._hostObject});var e=o.call(this,d,c);if(-1==e)return!1;d.splice(e,1),d.length||this._removeAllSubscribers(a,b)}else this._removeAllSubscribers(a,b);return!0}function t(a,b){delete a[b],this._messageSource&&"string"==typeof b&&this._messageSource.onSubscriberRemoved(b)}function u(a){J(a,K.ObjectHash(K.Optional(K.OneOf(Function,{subscriber:Function,context:K.Any}))));var b=I.mapKeys(a,function(a,b){return this.off(b,a)},this);return b}function v(){w.call(this,this._patternMessageSubscribers),w.call(this,this._messageSubscribers)}function w(a){I.eachKey(a,function(b,c){this._removeAllSubscribers(a,c)},this)}function x(a,b,c,d){J(a,K.OneOf(String,RegExp)),J(c,K.Optional(Function));var e=this._chooseSubscribersHash(a),f=e[a];this._callSubscribers(a,b,c,f,d),"string"==typeof a&&this._callPatternSubscribers(a,b,c,f,d)}function y(a,b,c){this.postMessage(a,b,c,!0)}function z(a,b,c,d,e){I.eachKey(this._patternMessageSubscribers,function(f){var g=f.pattern;if(g.test(a)){if(d)var f=f.filter(function(a){var b=o.call(this,d,a);return-1==b});this._callSubscribers(a,b,c,f,e)}},this)}function A(a,b,c,d,e){d&&d.length&&(d=d.slice(),d.forEach(function(d){this._callSubscriber(d,a,b,c,e)},this))}function B(a,b,c,d,e){var f=a.options&&a.options.sync,g=e&&f!==!1||f,h=a.options&&a.options.dispatchTimes;if(h)if(1>=h){var i=a.__messages;this.off(i,a)}else h>1&&a.options.dispatchTimes--;g?a.subscriber.call(a.context,b,c,d):I.deferMethod(a.subscriber,"call",a.context,b,c,d)}function C(a,b){J(a,K.OneOf(String,RegExp));var c=this._chooseSubscribersHash(a),d=c[a]?[].concat(c[a]):[];return b!==!1&&"string"==typeof a&&I.eachKey(this._patternMessageSubscribers,function(b){var c=b.pattern;b&&b.length&&c.test(a)&&I.appendArray(d,b)}),d.length?d:void 0}function D(a){return a instanceof RegExp?this._patternMessageSubscribers:this._messageSubscribers}function E(a){J(a,H),I.defineProperty(this,"_messageSource",a),a.messenger=this}function F(){return this._messageSource}var G=a("../abstract/mixin"),H=a("./m_source"),I=a("mol-proto"),J=a("../util/check"),K=J.Match,L=I.createSubclass(G,"Messenger"),M=L.messagesSplitRegExp=/\s*(?:\,|\s)\s*/;I.extendProto(L,{init:c,destroy:e,on:f,once:g,onceSync:h,onSync:i,onAsync:j,onMessage:f,off:q,offMessage:q,onMessages:p,offMessages:u,offAll:v,postMessage:x,postMessageSync:y,getSubscribers:C,getMessageSource:F,_chooseSubscribersHash:D,_registerSubscriber:n,_removeSubscriber:s,_removeAllSubscribers:t,_callPatternSubscribers:z,_callSubscribers:A,_callSubscriber:B,_setMessageSource:E}),L.defaultMethods={on:"on",onSync:"onSync",once:"once",onceSync:"onceSync",off:"off",onMessages:"onMessages",offMessages:"offMessages",postMessage:"postMessage",postMessageSync:"postMessageSync",getSubscribers:"getSubscribers"},b.exports=L,L.subscriptions=[]},{"../abstract/mixin":97,"../util/check":116,"./m_source":103,"mol-proto":122}],101:[function(a,b){"use strict";function c(){this.init&&this.init.apply(this,arguments)}function d(){l.defineProperty(this,"_internalMessages",{})}function e(){}function f(a){var b,c=this.translateToSourceMessage(a);if("undefined"!=typeof c)return this._internalMessages.hasOwnProperty(c)?(b=this._internalMessages[c],void(-1==b.indexOf(a)?b.push(a):m.warn("Duplicate addInternalMessage call for internal message "+a))):(b=this._internalMessages[c]=[],b.push(a),c)}function g(a){function b(){m.warn("notification received: un-subscribe from internal message "+a+" without previous subscription notification")}var c=this.translateToSourceMessage(a);if("undefined"!=typeof c){var d=this._internalMessages[c];if(d&&d.length){var e=d.indexOf(a);if(e>=0){if(d.splice(e,1),0==d.length)return delete this._internalMessages[c],c}else b()}else b()}}function h(a){return this._internalMessages[a]}function i(a){return a}function j(a,b,c){return c}function k(){return!0}var l=a("mol-proto"),m=a("../util/logger");b.exports=c,l.extendProto(c,{init:d,destroy:e,addInternalMessage:f,removeInternalMessage:g,getInternalMessages:h,translateToSourceMessage:i,createInternalData:j,filterSourceMessage:k})},{"../util/logger":118,"mol-proto":122}],102:[function(a,b){"use strict";function c(){g.prototype.init.apply(this,arguments),h.defineProperties(this,{_patternInternalMessages:{}}),this._catchAllSubscribed=!1}function d(){var a=g.prototype.addInternalMessage.apply(this,arguments);if(a&&a instanceof RegExp){if(this._internalMessages[a].pattern=a,this._patternInternalMessages[a]=this._internalMessages[a],this._catchAllSubscribed)return;return this._catchAllSubscribed=!0,/.*/}return a}function e(){var a=g.prototype.removeInternalMessage.apply(this,arguments);if(a&&a instanceof RegExp){delete this._patternInternalMessages[a];var b=!Object.keys(this._patternInternalMessages).length;if(b)return this._catchAllSubscribed=!1,/.*/}return a}function f(a){var b=g.prototype.getInternalMessages.apply(this,arguments);if("string"==typeof a){b=b||[];var c=h.object(b,!0);h.eachKey(this._patternInternalMessages,function(d){var e=d.pattern;e.test(a)&&d.forEach(function(a){c[a]||(b.push(a),c[a]=!0)})})}return b}var g=a("./m_api"),h=a("mol-proto"),i=h.createSubclass(g,"MessengerRegexpAPI");b.exports=i,h.extendProto(i,{init:c,addInternalMessage:d,removeInternalMessage:e,getInternalMessages:f})},{"./m_api":101,"mol-proto":122}],103:[function(a,b){"use strict";function c(a,b,c){this._prepareMessengerAPI(c)}function d(){this.messengerAPI&&this.messengerAPI.destroy()}function e(a){n.defineProperty(this,"messenger",a)}function f(a){o(a,p.Optional(m)),a||(a=new m),n.defineProperty(this,"messengerAPI",a)}function g(a){var b=this.messengerAPI.addInternalMessage(a);"undefined"!=typeof b&&this.addSourceSubscriber(b)}function h(a){var b=this.messengerAPI.removeInternalMessage(a);"undefined"!=typeof b&&this.removeSourceSubscriber(b)}function i(a,b){var c=this.messengerAPI,d=c.getInternalMessages(a);d&&d.forEach(function(d){var e=c.createInternalData(a,d,b),f=c.filterSourceMessage(a,d,e);f&&this.postMessage(d,e)},this)}function j(a,b){this.messenger.postMessage(a,b)}function k(){throw new Error("calling the method of an absctract class")}var l=a("../abstract/mixin"),m=a("./m_api"),n=(a("../util/logger"),a("mol-proto")),o=a("../util/check"),p=o.Match,q=n.createSubclass(l,"MessageSource",!0);b.exports=q,n.extendProto(q,{init:c,destroy:d,setMessenger:e,onSubscriberAdded:g,onSubscriberRemoved:h,dispatchMessage:i,postMessage:j,_prepareMessengerAPI:f,trigger:k,addSourceSubscriber:k,removeSourceSubscriber:k})},{"../abstract/mixin":97,"../util/check":116,"../util/logger":118,"./m_api":101,"mol-proto":122}],104:[function(a,b){"use strict";function c(a,b,c,d){g.prototype.init.apply(this,arguments),this.sourceMessenger=d}function d(a){this.sourceMessenger.onSync(a,{context:this,subscriber:this.dispatchMessage})}function e(a){this.sourceMessenger.off(a,{context:this,subscriber:this.dispatchMessage})}function f(a,b){this.messenger.postMessageSync(a,b)}var g=a("./m_source"),h=a("mol-proto"),i=(a("../util/check"),h.createSubclass(g,"MessengerMessageSource"));b.exports=i,h.extendProto(i,{init:c,addSourceSubscriber:d,removeSourceSubscriber:e,postMessage:f})},{"../util/check":116,"./m_source":103,"mol-proto":122}],105:[function(a,b){"use strict";function c(){e.minder.destroy()}var d=a("mol-proto"),e={minder:a("./minder"),config:a("./config"),util:a("./util"),classes:a("./classes"),Messenger:a("./messenger"),Model:a("./model"),destroy:c,proto:d};"object"==typeof b&&b.exports&&(b.exports=e),"object"==typeof window&&(window.milo=e)},{"./classes":98,"./config":99,"./messenger":100,"./minder":106,"./model":109,"./util":117,"mol-proto":122}],106:[function(a,b){"use strict";function c(a,b,c,e){if(Array.isArray(a)){var f=a,g=f.map(function(a){return new p(a[0],a[1],a[2],a[3])});return g.forEach(d),g}var h=new p(a,b,c,e);return d(h),h}function d(a){a.___minder_id=u.push(a)-1,a.on(/.*/,e),c.postMessage("added",{connector:a}),c.postMessage("turnedon",{connector:a})}function e(a,b){var b=b?r.clone(b):{};r.extend(b,{id:this.___minder_id,connector:this}),c.postMessage(a,b),v.length||w||(r.defer(f),w=!0),v.push({msg:a,data:b})}function f(){v.length?(v.length=0,r.defer(f),c.postMessage("propagationticked")):(w=!1,c.postMessage("propagationcompleted"))}function g(){return w}function h(a){function b(){w?c.once("propagationcompleted",b):a()}w?c.once("propagationcompleted",b):r.defer(b)}function i(a){return"undefined"==typeof a?u:u.filter(function(b){return b.isOn===a})}function j(a){a.destroy();var b=u.indexOf(a);b>=0?delete u[b]:s.warn("minder: connector destroyed that is not registered in minder")}function k(a,b){var d=c.getConnectors(a),e=d.map(function(a){var b={leftSource:l(a.ds1),rightSource:l(a.ds2),mode:a.mode,isOn:a.isOn};return a.options&&(b.options=a.options),b});return b&&(e=e.filter(function(a){return m(a.leftSource,b)||m(a.rightSource,b)})),e}function l(a){var b=[];return"function"==typeof a&&(a._model&&a._accessPath&&(b.unshift(a._accessPath),a=a._model),b.unshift(a),a=a._hostObject),"object"==typeof a&&(b.unshift(a),a.owner&&b.unshift(a.owner)),b}function m(a,b){return a.some(function(a){var c=a.constructor&&a.constructor.name;return n(c,b)||n(a.name,b)||n(a,b)})}function n(a,b){return a&&"string"==typeof a&&a.indexOf(b)>=0}function o(){function a(a){a&&!a._destroyed&&a.destroy()}u.forEach(function(b){a(b.ds1),a(b.ds2),b.destroy()}),t.destroy(),c._destroyed=!0}var p=a("./model/connector"),q=a("./messenger"),r=a("mol-proto"),s=a("./util/logger");b.exports=c;var t=new q(c,q.defaultMethods),u=[],v=[],w=!1;r.extend(c,{getConnectors:i,getExpandedConnections:k,isPropagating:g,whenPropagationCompleted:h,destroyConnector:j,destroy:o})},{"./messenger":100,"./model/connector":108,"./util/logger":118,"mol-proto":122}],107:[function(a,b){"use strict";function c(a,b){r.defineProperty(a,"__inChangeTransaction",b,r.CONF|r.WRIT)}function d(a){var b=a.__inChangeTransaction;return delete a.__inChangeTransaction,b}function e(a,b){var e=d(a);return c(b,e),e}function f(){this.postMessageSync("datachanges",{transaction:!1,changes:[]})}function g(a,b,c){h.call(this,b.changes,c)}function h(a,b){i.call(this,b,!1),l.call(this,k(j(a))),i.call(this,b,!0)}function i(a,b){a&&a(null,b),this.postMessage(b?"changecompleted":"changestarted")}function j(a){var b=a[0].source,c=!0;if(a.length>1)for(var d=1,e=a.length;e>d;d++)a[d].source!=b&&(o.error("changedata: changes from different sources in the same transaction, sources:",a[d].source.name,b.name),c=!1,b=a[d].source);return a}function k(a){function b(a){("splice"==a.type?c:d)(a)}function c(a){var b=q.parseAccessPath(a.path),c=i.some(function(a){return b.length<a.length?void 0:e(a,b)});if(!c){if(g.push(a),!p.debug)throw j;h.push(b),f=!0}}function d(a){var b=q.parseAccessPath(a.path),c=h&&h.some(function(a){return b.length<=a.length||"array"!=b[a.length].syntax?void 0:e(a,b)});if(!c){f&&o.error('changedata: child change is executed after splice; probably data source did not emit message with data.type=="finished"');var d=i.some(function(a){return b.length<=a.length?void 0:e(a,b)});d||(i.push(b),g.push(a))}}function e(a,b){return a.every(function(a,c){return a.property==b[c].property})}var f,g=[],h=[],i=[],j={};try{a.forEach(b)}catch(k){if(k!=j)throw k}return g}function l(a){function b(a){var b=this.path(a.path,"removed"!=a.type&&"deleted"!=a.type);b&&("splice"==a.type?m:n)(b,a)}a.forEach(b,this),f.call(this,!1)}function m(a,b){var d=b.index,e=b.removed.length,f=[d,e];f=f.concat(b.newValue.slice(d,d+b.addedCount)),c(a.splice,!0),a.splice.apply(a,f)}function n(a,b){var d=s[b.type];d?(c(a[d],!0),a[d](b.newValue)):o.error("unknown data change type")}var o=a("../util/logger"),p=a("../config"),q=a("./path_utils"),r=a("mol-proto");b.exports=g,r.extend(g,{setTransactionFlag:c,getTransactionFlag:d,passTransactionFlag:e,postTransactionFinished:f});var s={added:"set",changed:"set",deleted:"del",removed:"del"}},{"../config":99,"../util/logger":118,"./path_utils":114,"mol-proto":122}],108:[function(a,b){"use strict";function c(a,b,c,e){if(d.call(this,b),o.extend(this,{ds1:a,ds2:c,isOn:!1,_changesQueue1:[],_changesQueue2:[],_messenger:new m(this,m.defaultMethods)}),e){this.options=e;var f=e.pathTranslation;if(f){f=o.clone(f);var j=h(f);o.extend(this,{pathTranslation1:g(f),pathTranslation2:f,patternTranslation1:i(j),patternTranslation2:j})}var k=e.dataTranslation;k&&o.extend(this,{dataTranslation1:k["<-"],dataTranslation2:k["->"]});var l=e.dataValidation;l&&o.extend(this,{dataValidation1:l["<-"],dataValidation2:l["->"]})}this.turnOn()}function d(a){function b(){throw new Error("invalid Connector mode: "+a)}var c=a.match(q);c||b();var d=c[1].length,e=c[2].length;d&&e&&d!=e&&b(),d||e||b(),o.extend(this,{mode:a,depth1:d,depth2:e})}function e(a){return this.turnOff(),d.call(this,a),this.turnOn(),this}function f(a){return o.deferMethod(this,"changeMode",a),this}function g(a){var b={};return o.eachKey(a,function(a,c){b[a]=c}),b}function h(a){function b(a,b){throw new Error("Invalid pattern translation: "+a+", "+b)}function c(a){return a.replace(/[\.\[]?\*.*$/,"")}var d=[];return o.eachKey(a,function(e,f){var g=f.indexOf("*"),h=e.indexOf("*");g>=0&&h>=0?(f.slice(g)!=e.slice(h)&&b(f,e),delete a[f],d.push({fromPattern:n.createRegexPath(f),fromStaticPath:c(f,g),toPattern:n.createRegexPath(e),toStaticPath:c(e,h)})):(g>=0||h>=0)&&b(f,e)}),d}function i(a){return a.map(function(a){return{fromPattern:a.toPattern,fromStaticPath:a.toStaticPath,toPattern:a.fromPattern,toStaticPath:a.fromStaticPath}})}function j(){function a(a,b,e,f,g,h,i,j){function k(k,l){function m(a){if(g){var b=g[a];if(b)return b;if(!h.length)return;var d=o.find(h,function(b){return b.fromPattern.test(a)});if(!d)return;var b=a.replace(d.fromStaticPath,d.toStaticPath)}else if(!(c instanceof RegExp&&c.test(a)||c==a))return;return b||a}function n(a,b){if(i){var c=i[a];c&&"function"==typeof c&&(b.oldValue=c(b.oldValue),b.newValue=c(b.newValue))}}function p(a,c){function d(d){d(c.newValue,function(c,d){d.path=a,g||!c&&!d.valid||++f!=e.length?d.valid||(g=!0,b.postMessage("validated",d)):b.postMessage("validated",d)})}if(q(c),j){var e=j[a],f=0,g=!1;e&&e.forEach(d)}}function q(a){u.changes.push(a)}function r(){if(d[a])var b=s;var c=t(f);f.length=0,c.forEach(function(a){e.postMessageSync("changedata",{changes:a},b)})}function s(c,f){if(!c){var g=f?"onSync":"off";e[g]("datachanges",d[a]);var h=f?"changecompleted":"changestarted";d.postMessage(h,{source:b,target:e})}}function t(a){var b,c=[];return a.forEach(function(a){a.transaction||(b=void 0),a.changes.length&&(a.transaction?b?o.appendArray(b,a.changes):(b=o.clone(a.changes),c.push(b)):c.push(a.changes))}),c}var u={changes:[],transaction:l.transaction};l.changes.forEach(function(a){var c=a.path,d=m(c);if("undefined"!=typeof d){var a=o.clone(a);o.extend(a,{source:b,path:d}),n(c,a),p(c,a)}}),f.length||o.defer(r),f.push(u)}return b.onSync("datachanges",k),k}if(this.isOn)return p.warn("data sources are already connected");var b=this._subscriptionPath=new Array(this.depth1||this.depth2).join("*"),c=n.createRegexPath(b),d=this;this.depth1&&(this._link1=a("_link2",this.ds2,this.ds1,this._changesQueue1,this.pathTranslation1,this.patternTranslation1,this.dataTranslation1,this.dataValidation1)),this.depth2&&(this._link2=a("_link1",this.ds1,this.ds2,this._changesQueue2,this.pathTranslation2,this.patternTranslation2,this.dataTranslation2,this.dataValidation2)),this.isOn=!0,this.postMessage("turnedon")}function k(){function a(a,c){b[c]&&(a.off("datachanges",b[c]),delete b[c])}if(!this.isOn)return p.warn("data sources are already disconnected");var b=this;a(this.ds1,"_link2",this.pathTranslation2),a(this.ds2,"_link1",this.pathTranslation1),this.isOn=!1,this.postMessage("turnedoff")}function l(){this.turnOff(),this.postMessage("destroyed"),this._messenger.destroy(),delete this.ds1,delete this.ds2,this._destroyed=!0}var m=a("../messenger"),n=a("./path_utils"),o=a("mol-proto"),p=a("../util/logger");b.exports=c;var q=/^(\<*)\-+(\>*)$/;o.extendProto(c,{turnOn:j,turnOff:k,destroy:l,changeMode:e,deferChangeMode:f})},{"../messenger":100,"../util/logger":118,"./path_utils":114,"mol-proto":122}],109:[function(a,b){"use strict";function c(a,b,d){var f=function(){return e.apply(f,arguments)};return f.__proto__=c.prototype,f._hostObject=b,f._options=d||{},f._options.reactive!==!1&&(f._prepareMessengers(),f.onSync("changedata",p)),a&&(f._data=a),f}function d(){return this._data}function e(a){return a?(u.splice(arguments,0,0,null,this),new(Function.prototype.bind.apply(l,arguments))):this}function f(a){a=a||this._hostObject,t.prototype._createProxyMethods.call(this[w],q.defaultMethods,a)}function g(a,b,d){d=d||x,t.useWith.call(c,a,b,d)}function h(a){a=a||this._hostObject,t.prototype._createProxyMethods.call(this,x,a)}function i(){var a=new q(this,void 0,void 0),b=new r(this,void 0,new s,a),c=new q(this,void 0,b);u.defineProperty(this,w,c),u.defineProperty(this,"_internalMessenger",a)}function j(){return this._hostObject}function k(){this[w].destroy(),this._internalMessenger.destroy(),this._destroyed=!0}{var l=a("./m_path"),m=a("./synthesize"),n=a("./path_utils"),o=a("./model_utils"),p=a("./change_data"),q=a("../messenger"),r=a("../messenger/msngr_source"),s=a("./m_msg_api"),t=a("../abstract/mixin"),u=a("mol-proto"),v=a("../util/check");v.Match,a("../util/logger")}b.exports=c,c.prototype.__proto__=c.__proto__,u.extendProto(c,{path:e,get:d,proxyMessenger:f,proxyMethods:h,_prepareMessengers:i,_getHostObject:j,destroy:k}),u.extendProto(c,m.modelMethods),u.extend(c,{Path:l,useWith:g,_utils:{path:n,model:o,changeDataHandler:p}});var w="_messenger";q.useWith(c,w,q.defaultMethods),["len","push","pop","unshift","shift"].forEach(function(a){var b=l.prototype[a];u.defineProperty(c.prototype,a,b)});var x=["path","get","set","del","splice","len","push","pop","unshift","shift"]},{"../abstract/mixin":97,"../messenger":100,"../messenger/msngr_source":104,"../util/check":116,"../util/logger":118,"./change_data":107,"./m_msg_api":110,"./m_path":111,"./model_utils":112,"./path_utils":114,"./synthesize":115,"mol-proto":122}],110:[function(a,b){"use strict";function c(a){return a instanceof RegExp?a:e.createRegexPath(a)}var d=a("../messenger/m_api_rx"),e=a("./path_utils"),f=a("mol-proto"),g=f.createSubclass(d,"ModelMsgAPI");b.exports=g,f.extendProto(g,{translateToSourceMessage:c})},{"../messenger/m_api_rx":102,"./path_utils":114,"mol-proto":122}],111:[function(a,b){"use strict";function c(a,b){v(b,String);var f=function(){return e.apply(f,arguments)};f.__proto__=c.prototype,u.defineProperties(f,{_model:a,_path:b,_args:u.slice(arguments,1),_options:a._options});var g=p.parseAccessPath(b);u.defineProperty(f,"_accessPath",d(g,f._args)),f._options.reactive!==!1&&(f._prepareMessenger(),f.onSync("changedata",q));var h=o(b,g);return u.defineProperties(f,h),Object.freeze(f),f}function d(a,b){return a.reduce(function(a,c){var d=c.interpolate;return a+(d?"array"==c.syntax?"["+b[d]+"]":"."+b[d]:c.property)},"")}function e(a){if(!a)return this;var b=this._args.length-1;b>0&&(a=a.replace(/\$[1-9][0-9]*/g,function(a){return"$"+(+a.slice(1)+b)}));var d=this._path+a,e=[this._model,d].concat(this._args.slice(1)).concat(u.slice(arguments,1));return u.newApply(c,e)}function f(){return this.path(".length").get()||0}function g(){var a=this.len(),b=a+arguments.length;return u.splice(arguments,0,0,a,0),this.splice.apply(this,arguments),b}function h(){return this.splice(this.len()-1,1)[0]}function i(){var a=this.len();return a+=arguments.length,u.splice(arguments,0,0,0,0),this.splice.apply(this,arguments),a}function j(){return this.splice(0,1)[0]}function k(){var a=new s(this._accessPath),b=new t(this,void 0,a,this._model),c=new r(this,void 0,b);u.defineProperty(this,w,c)}function l(){return{model:this._model,path:this._path,args:this._args}}function m(a){v(a,{model:Function,path:String,args:Array});var b=a.model;return b.apply(b,a.args)}function n(){this[w].destroy()}{var o=a("./synthesize"),p=a("./path_utils"),q=a("./change_data"),r=a("../messenger"),s=a("./path_msg_api"),t=a("../messenger/msngr_source"),u=a("mol-proto"),v=a("../util/check");v.Match}b.exports=c,c.prototype.__proto__=c.__proto__,u.extendProto(c,{path:e,len:f,push:g,pop:h,unshift:i,shift:j,_prepareMessenger:k,_getDefinition:l,destroy:n}),u.extend(c,{_createFromDefinition:m});var w="_messenger";r.useWith(c,w,r.defaultMethods)},{"../messenger":100,"../messenger/msngr_source":104,"../util/check":116,"./change_data":107,"./path_msg_api":113,"./path_utils":114,"./synthesize":115,"mol-proto":122}],112:[function(a,b){"use strict";function c(a,b){return a>b?b:a>=0?a:a+b>0?a+b:0}var d={normalizeSpliceIndex:c};b.exports=d},{}],113:[function(a,b){"use strict";function c(a){g.prototype.init.apply(this,arguments),this.rootPath=a}function d(a){return a instanceof RegExp?a:"datachanges"==a?a:this.rootPath+a}function e(a,b,c){if("datachanges"==b){var d=c.changes.map(f,this).filter(function(a){return a}),e={changes:d,transaction:c.transaction};return e}var e=f.call(this,c);return e}function f(a){var b=a.path,c=h.unPrefix(b,this.rootPath);if("string"==typeof c){var a=h.clone(a);return a.fullPath=b,a.path=c,a}}var g=a("../messenger/m_api"),h=(a("./path_utils"),a("../util/logger"),a("mol-proto")),i=h.createSubclass(g,"ModelPathMsgAPI");b.exports=i,h.extendProto(i,{init:c,translateToSourceMessage:d,createInternalData:e})},{"../messenger/m_api":101,"../util/logger":118,"./path_utils":114,"mol-proto":122}],114:[function(a,b){"use strict";function c(a,b){b=b||t;var c=[];if(!a)return c;var d=a.replace(b,function(a){var b={property:a};return i.extend(b,w[a[0]]),"$"==a[1]&&(b.interpolate=e(b,!0)),c.push(b),""});if(d)throw new Error("incorrect model path: "+a);return c}function d(a){if(g(a,h.OneOf(String,RegExp)),a instanceof RegExp||-1==a.indexOf("*"))return a;var b=j.parseAccessPath(a,v),c="^",d=!1;b.forEach(function(a){var b=a.property,e=x[b];e?(c+="("+e+"|)",d=!0):c+=b.replace(/(\.|\[|\])/g,"\\$1")}),c+="$";try{return new RegExp(c)}catch(e){throw new Error("can't construct regex for path pattern: "+a)}}function e(a,b){var c=a.property,d=b?2:1;return"array"==a.syntax?c.slice(d,c.length-1):c.slice(d)}function f(a){a=a||["on","off"];var b=i.mapToObject(a,function(a){var b=this[a];return function(a,c){var e=d(a);b.call(this,e,c)}},this);i.defineProperties(this,b)}var g=a("../util/check"),h=g.Match,i=a("mol-proto"),j={parseAccessPath:c,createRegexPath:d,getPathNodeKey:e,wrapMessengerMethods:f};b.exports=j; var k="\\.[A-Za-z_-][A-Za-z0-9_-]*",l="\\[[0-9]+\\]",m="\\$[1-9][0-9]*",n="\\."+m,o="\\["+m+"\\]",p="\\.\\*",q="\\[\\*\\]",r="\\*",s=[k,l,n,o].join("|"),t=new RegExp(s,"g"),u=[s,p,q,r].join("|"),v=new RegExp(u,"g"),w={".":{syntax:"object",empty:"{}"},"[":{syntax:"array",empty:"[]"},"*":{syntax:"match",empty:"{}"}},x={".*":k,"[*]":l};x["*"]=x[".*"]+"|"+x["[*]"]},{"../util/check":116,"mol-proto":122}],115:[function(require,module,exports){"use strict";function _synthesizePathMethods(a,b){var c=_.mapKeys(synthesizers,function(c){return _synthesize(c,a,b)});return c}function _synthesize(synthesizer,path,parsedPath){function addChangeMessage(a,b,c){a.push(c),b[c.path]=c}function addTreeChangesMessages(a,b,c,d,e){var f=valueIsTree(d),g=valueIsTree(e);g&&addMessages(a,b,c,e,"added","newValue"),f&&addMessages(a,b,c,d,"removed","oldValue")}function addMessages(a,b,c,d,e,f){function g(a,b){if(Array.isArray(b)){var c=a+"[$$]";b.forEach(function(a,b){h(a,b,c)})}else{var c=a+".$$";_.eachKey(b,function(a,b){h(a,b,c)})}}function h(c,d,h){var i=h.replace("$$",d),j=b[i];if(j)j.type==e?logger.error("setter error: same message type posted on the same path"):(j.type="changed",j[f]=c);else{var k={path:i,type:e};k[f]=c,addChangeMessage(a,b,k)}valueIsTree(c)&&g(i,c)}g(c,d)}function cloneTree(a){return valueIsNormalObject(a)?_.deepClone(a):a}function protectValue(a){return valueIsNormalObject(a)?Array.isArray(a)?a.slice():Object.create(a):a}function valueIsTree(a){return valueIsNormalObject(a)&&Object.keys(a).length}function valueIsNormalObject(a){return!(null==a||"object"!=typeof a||a instanceof Date||a instanceof RegExp)}function addBatchIdsToMessage(a,b,c){_.defineProperties(a,{__batch_id:b,__msg_id:c})}var method,methodCode=synthesizer({parsedPath:parsedPath,getPathNodeKey:pathUtils.getPathNodeKey});try{eval(methodCode)}catch(e){throw ModelError("ModelPath method compilation error; path: "+path+", code: "+methodCode)}return method}var pathUtils=require("../path_utils"),modelUtils=require("../model_utils"),logger=require("../../util/logger"),fs=require("fs"),doT=require("dot"),_=require("mol-proto"),changeDataHandler=require("../change_data"),getTransactionFlag=changeDataHandler.getTransactionFlag,postTransactionFinished=changeDataHandler.postTransactionFinished,templates={get:"'use strict';\n/* Only use this style of comments, not \"//\" */\n\nmethod = function get() {\n var m = {{# def.modelAccessPrefix }};\n return m {{~ it.parsedPath :pathNode }}\n {{? pathNode.interpolate}}\n && (m = m[this._args[ {{= pathNode.interpolate }} ]])\n {{??}}\n && (m = m{{= pathNode.property }})\n {{?}} {{~}};\n};\n",set:"'use strict';\n/* Only use this style of comments, not \"//\" */\n\n{{# def.include_defines }}\n{{# def.include_create_tree }}\n\n\n/**\n * Template that synthesizes setter for Model and for ModelPath\n */\nmethod = function set(value) {\n {{# def.initVars:'set' }}\n\n {{# def.createTree:'set' }}\n\n {{\n currNode = nextNode;\n currProp = currNode && currNode.property;\n }}\n\n {{ /* assign value to the last property */ }}\n {{? currProp }}\n wasDef = {{# def.wasDefined}};\n {{# def.changeAccessPath }}\n\n var old = m{{# def.currProp }};\n\n {{ /* clone value to prevent same reference in linked models */ }}\n m{{# def.currProp }} = cloneTree(value);\n {{?}}\n\n {{ /* add message related to the last property change */ }}\n if (this._options.reactive !== false) {\n if (! wasDef)\n {{# def.addMsg }} accessPath, type: 'added',\n newValue: value });\n else if (old != value)\n {{# def.addMsg }} accessPath, type: 'changed',\n oldValue: old, newValue: value });\n\n {{ /* add message related to changes in (sub)properties inside removed and assigned value */ }}\n if (! wasDef || old != value)\n addTreeChangesMessages(messages, messagesHash,\n accessPath, old, value); /* defined in the function that synthesizes ModelPath setter */\n\n {{ /* post all stored messages */ }}\n {{# def.postMessages }}\n }\n};\n",del:"'use strict';\n/* Only use this style of comments, not \"//\" */\n\n{{# def.include_defines }}\n{{# def.include_traverse_tree }}\n\nmethod = function del() {\n {{# def.initVars:'del' }}\n\n {{? it.parsedPath.length }}\n {{# def.traverseTree }}\n\n {{\n var currNode = it.parsedPath[count];\n var currProp = currNode.property; \n }}\n\n if (! treeDoesNotExist && m && m.hasOwnProperty && {{# def.wasDefined}}) {\n var old = m{{# def.currProp }};\n delete m{{# def.currProp }};\n {{# def.changeAccessPath }}\n var didDelete = true;\n }\n {{??}}\n if (typeof m != 'undefined') {\n var old = m;\n {{# def.modelAccessPrefix }} = undefined;\n var didDelete = true;\n }\n {{?}}\n\n if (didDelete && this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'deleted', oldValue: old });\n\n addTreeChangesMessages(messages, messagesHash,\n accessPath, old, undefined); /* defined in the function that synthesizes ModelPath setter */\n\n {{ /* post all stored messages */ }}\n {{# def.postMessages }}\n }\n};\n",splice:"'use strict';\n/* Only use this style of comments, not \"//\" */\n\n{{# def.include_defines }}\n{{# def.include_create_tree }}\n{{# def.include_traverse_tree }}\n\nmethod = function splice(spliceIndex, spliceHowMany) { /* ,... - extra arguments to splice into array */\n {{# def.initVars:'splice' }}\n\n var argsLen = arguments.length;\n var addItems = argsLen > 2;\n\n if (addItems) {\n {{ /* only create model tree if items are inserted in array */ }}\n\n {{ /* if model is undefined it will be set to an empty array */ }} \n var value = [];\n {{# def.createTree:'splice' }}\n\n {{? nextNode }}\n {{\n var currNode = nextNode;\n var currProp = currNode.property;\n var emptyProp = '[]';\n }}\n\n {{# def.createTreeStep }}\n {{?}}\n\n } else if (spliceHowMany > 0) {\n {{ /* if items are not inserted, only traverse model tree if items are deleted from array */ }}\n {{? it.parsedPath.length }}\n {{# def.traverseTree }}\n\n {{\n var currNode = it.parsedPath[count];\n var currProp = currNode.property; \n }}\n\n {{ /* extra brace closes 'else' in def.traverseTreeStep */ }}\n {{# def.traverseTreeStep }} }\n {{?}}\n }\n\n {{ /* splice items */ }}\n if (addItems || (! treeDoesNotExist && m\n && m.length > spliceIndex ) ) {\n var oldLength = m.length = m.length || 0;\n\n arguments[0] = spliceIndex = normalizeSpliceIndex(spliceIndex, m.length);\n\n {{ /* clone added arguments to prevent same references in linked models */ }}\n if (addItems)\n for (var i = 2; i < argsLen; i++)\n arguments[i] = cloneTree(arguments[i]);\n\n {{ /* actual splice call */ }}\n var removed = Array.prototype.splice.apply(m, arguments);\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'splice',\n index: spliceIndex, removed: removed, addedCount: addItems ? argsLen - 2 : 0,\n newValue: m });\n\n if (removed && removed.length)\n removed.forEach(function(item, index) {\n var itemPath = accessPath + '[' + (spliceIndex + index) + ']';\n {{# def.addMsg }} itemPath, type: 'removed', oldValue: item });\n\n if (valueIsTree(item))\n addMessages(messages, messagesHash, itemPath, item, 'removed', 'oldValue');\n });\n\n if (addItems)\n for (var i = 2; i < argsLen; i++) {\n var item = arguments[i];\n var itemPath = accessPath + '[' + (spliceIndex + i - 2) + ']';\n {{# def.addMsg }} itemPath, type: 'added', newValue: item });\n\n if (valueIsTree(item))\n addMessages(messages, messagesHash, itemPath, item, 'added', 'newValue');\n }\n\n {{ /* post all stored messages */ }}\n {{# def.postMessages }}\n }\n }\n\n return removed || [];\n}\n"},include_defines="'use strict';\n/* Only use this style of comments, not \"//\" */\n\n/**\n * Inserts initialization code\n */\n {{## def.initVars:method:\n var m = {{# def.modelAccessPrefix }};\n var messages = [], messagesHash = {};\n var accessPath = '';\n var treeDoesNotExist;\n /* hack to prevent sending finished events to allow for propagation of batches without splitting them */\n var inChangeTransaction = getTransactionFlag( {{= method }} );\n #}}\n\n/**\n * Inserts the beginning of function call to add message to list\n */\n{{## def.addMsg: addChangeMessage(messages, messagesHash, { path: #}}\n\n/**\n * Inserts current property/index for both normal and interpolated properties/indexes\n */\n{{## def.currProp:{{? currNode.interpolate }}[this._args[ {{= currNode.interpolate }} ]]{{??}}{{= currProp }}{{?}} #}}\n\n/**\n * Inserts condition to test whether normal/interpolated property/index exists\n */\n{{## def.wasDefined: m.hasOwnProperty(\n {{? currNode.interpolate }}\n this._args[ {{= currNode.interpolate }} ]\n {{??}}\n '{{= it.getPathNodeKey(currNode) }}'\n {{?}}\n) #}}\n\n\n/**\n * Inserts code to update access path for current property\n * Because of the possibility of interpolated properties, it can't be calculated in template, it can only be calculated during accessor call.\n */\n{{## def.changeAccessPath:\n accessPath += {{? currNode.interpolate }}\n {{? currNode.syntax == 'array' }}\n '[' + this._args[ {{= currNode.interpolate }} ] + ']';\n {{??}}\n '.' + this._args[ {{= currNode.interpolate }} ];\n {{?}}\n {{??}}\n '{{= currProp }}';\n {{?}}\n#}}\n\n\n/**\n * Inserts code to post stored messages\n */\n{{## def.postMessages:\n if (messages.length) {\n {{# def.modelPostBatchCode }}('datachanges', {\n changes: messages,\n transaction: inChangeTransaction\n });\n\n messages.forEach(function(msg) {\n {{# def.modelPostMessageCode }}(msg.path, msg);\n }, this);\n }\n#}}\n",include_create_tree="'use strict';\n/* Only use this style of comments, not \"//\" */\n\n/**\n * Inserts code to create model tree as neccessary for `set` and `splice` accessors and to add messages to send list if the tree changes.\n */\n{{## def.createTree:method:\n var wasDef = true;\n var old = m;\n\n {{ var emptyProp = it.parsedPath[0] && it.parsedPath[0].empty; }}\n {{? emptyProp }}\n {{ /* create top level model if it was not previously defined */ }}\n if (! m) {\n m = {{# def.modelAccessPrefix }} = {{= emptyProp }};\n wasDef = false;\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} '', type: 'added',\n newValue: m });\n }\n }\n {{??}}\n {{? method == 'splice' }}\n if (! m) {\n {{?}}\n m = {{# def.modelAccessPrefix }} = cloneTree(value);\n wasDef = typeof old != 'undefined';\n {{? method == 'splice' }}\n }\n {{?}} \n {{?}}\n\n\n {{ /* create model tree if it doesn't exist */ }}\n {{ var modelDataProperty = '';\n var nextNode = it.parsedPath[0];\n var count = it.parsedPath.length - 1;\n\n for (var i = 0; i < count; i++) {\n var currNode = nextNode;\n var currProp = currNode.property;\n nextNode = it.parsedPath[i + 1];\n var emptyProp = nextNode && nextNode.empty;\n }}\n\n {{# def.createTreeStep }}\n\n {{ } /* for loop */ }}\n#}}\n\n\n/**\n * Inserts code to create one step in the model tree\n */\n{{## def.createTreeStep:\n {{# def.changeAccessPath }}\n\n if (! {{# def.wasDefined }}) { \n {{ /* property does not exist */ }}\n m = m{{# def.currProp }} = {{= emptyProp }};\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'added', \n newValue: m });\n }\n\n } else if (typeof m{{# def.currProp }} != 'object') {\n {{ /* property is not object */ }}\n var old = m{{# def.currProp }};\n m = m{{# def.currProp }} = {{= emptyProp }};\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'changed', \n oldValue: old, newValue: m });\n }\n\n } else {\n {{ /* property exists, just traverse down the model tree */ }}\n m = m{{# def.currProp }};\n }\n#}}\n",include_traverse_tree="'use strict';\n/* Only use this style of comments, not \"//\" */\n\n/**\n * Inserts code to traverse model tree for `delete` and `splice` accessors.\n */\n{{## def.traverseTree:\n {{ \n var count = it.parsedPath.length-1;\n\n for (var i = 0; i < count; i++) { \n var currNode = it.parsedPath[i];\n var currProp = currNode.property;\n }}\n {{# def.traverseTreeStep }}\n\n {{ } /* for loop */\n\n var i = count;\n while (i--) { /* closing braces for else's above */\n }}\n }\n {{ } /* while loop */ }}\n#}}\n\n\n/**\n * Inserts code to traverse one step in the model tree\n */\n{{## def.traverseTreeStep:\n if (! (m && m.hasOwnProperty && {{# def.wasDefined}} ) )\n treeDoesNotExist = true;\n else {\n m = m{{# def.currProp }};\n {{# def.changeAccessPath }}\n {{ /* brace from else is not closed on purpose - all braces are closed in while loop */ }}\n#}}\n",dotDef={include_defines:include_defines,include_create_tree:include_create_tree,include_traverse_tree:include_traverse_tree,getPathNodeKey:pathUtils.getPathNodeKey,modelAccessPrefix:"this._model._data",modelPostMessageCode:"this._model._internalMessenger.postMessage",modelPostBatchCode:"this._model.postMessageSync",internalMessenger:"this._model._internalMessenger"},modelDotDef=_(dotDef).clone().extend({modelAccessPrefix:"this._data",modelPostMessageCode:"this._internalMessenger.postMessage",modelPostBatchCode:"this.postMessageSync",internalMessenger:"this._internalMessenger"})._(),dotSettings=_.clone(doT.templateSettings);dotSettings.strip=!1;var synthesizers=_.mapKeys(templates,function(a){return doT.template(a,dotSettings,dotDef)}),modelSynthesizers=_.mapToObject(["set","del","splice"],function(a){return doT.template(templates[a],dotSettings,modelDotDef)}),synthesizePathMethods=_.memoize(_synthesizePathMethods,void 0,1e3),normalizeSpliceIndex=modelUtils.normalizeSpliceIndex;module.exports=synthesizePathMethods;var modelMethods=_.mapKeys(modelSynthesizers,function(a){return _synthesize(a,"",[])});synthesizePathMethods.modelMethods=modelMethods},{"../../util/logger":118,"../change_data":107,"../model_utils":112,"../path_utils":114,dot:121,fs:96,"mol-proto":122}],116:[function(a,b){"use strict";function c(a){this.pattern=a}function d(a){if(0==a.length)throw new Error("Must provide at least one choice to Match.OneOf");this.choices=a}function e(a){this.condition=a}function f(a){this.pattern=a}function g(a){this.pattern=a}function h(a,b){this.Superclass=a,this.matchSuperclass=b}function i(a,b){if(b!==n.Any){for(var l=0;l<o.length;++l)if(b===o[l][0]){if(typeof a===o[l][1])return;throw new n.Error("Expected "+o[l][1]+", got "+typeof a)}if(null===b){if(null===a)return;throw new n.Error("Expected null, got "+JSON.stringify(a))}if(b===n.Integer){if("number"==typeof a&&(0|a)===a)return;throw new n.Error("Expected Integer, got "+(a instanceof Object?JSON.stringify(a):a))}if(b===n.IdentifierString){if("string"==typeof a&&n.IdentifierString.test(a)&&-1==p.indexOf(u))return;throw new n.Error("Expected identifier string, got "+(a instanceof Object?JSON.stringify(a):a))}if(b===Object&&(b=n.ObjectIncluding({})),b instanceof Array){if(1!==b.length)throw Error("Bad pattern: arrays must have one type element"+JSON.stringify(b));if(!Array.isArray(a))throw new n.Error("Expected array, got "+JSON.stringify(a));return void a.forEach(function(a,c){try{i(a,b[0])}catch(d){throw d instanceof n.Error&&(d.path=j(c,d.path)),d}})}if(b instanceof e){if(b.condition(a))return;throw new n.Error("Failed Match.Where validation")}if(b instanceof c&&(b=n.OneOf(void 0,b.pattern)),b instanceof d){for(var l=0;l<b.choices.length;++l)try{return void i(a,b.choices[l])}catch(q){if(!(q instanceof n.Error))throw q}throw new n.Error("Failed Match.OneOf or Match.Optional validation")}if(b instanceof Function){if(a instanceof b)return;throw new n.Error("Expected "+b.constructor.name)}var r=!1;if(b instanceof f&&(r=!0,b=b.pattern),b instanceof g){var s=b.pattern,t=!0;for(var u in a)t=!1,m(a[u],s);if(t)throw new n.Error("Expected "+b.constructor.name)}else if(b instanceof h){var v=b.Superclass;if(b.matchSuperclass&&a==v)return;if(!(a.prototype instanceof v))throw new n.Error("Expected "+b.constructor.name+" of "+v.name)}else{if("object"!=typeof b)throw Error("Bad pattern: unknown pattern type");if("object"!=typeof a)throw new n.Error("Expected object, got "+typeof a);if(null===a)throw new n.Error("Expected object, got null");var w={},x={};k.eachKey(b,function(a,d){b[d]instanceof c?x[d]=b[d].pattern:w[d]=b[d]},this,!0),k.eachKey(a,function(b,c){var b=a[c];try{if(w.hasOwnProperty(c))i(b,w[c]),delete w[c];else if(x.hasOwnProperty(c))i(b,x[c]);else if(!r)throw new n.Error("Unknown key")}catch(d){throw d instanceof n.Error&&(d.path=j(c,d.path)),d}},this,!0),k.eachKey(w,function(a,b){throw new n.Error("Missing key '"+b+"'")},this,!0)}}}function j(a,b){return"number"==typeof a||a.match(/^[0-9]+$/)?a="["+a+"]":a.match(n.IdentifierString)&&-1==p.indexOf(a)||(a=JSON.stringify([a])),b&&"["!==b[0]?a+"."+b:a+b}var k=a("mol-proto"),l=a("../config"),m=function(a,b){if(l.check!==!1)try{i(a,b)}catch(c){throw c instanceof n.Error&&c.path&&(c.message+=" in field "+c.path),c}};b.exports=m;var n=m.Match={Optional:function(a){return new c(a)},OneOf:function(){return new d(arguments)},Any:["__any__"],Where:function(a){return new e(a)},ObjectIncluding:function(a){return new f(a)},Integer:["__integer__"],IdentifierString:/^[a-z_$][0-9a-z_$]*$/i,ObjectHash:function(a){return new g(a)},Subclass:function(a,b){return new h(a,b)},Error:TypeError,test:function(a,b){try{return i(a,b),!0}catch(c){if(c instanceof n.Error)return!1;throw c}}},o=[[String,"string"],[Number,"number"],[Boolean,"boolean"],[Function,"function"],[void 0,"undefined"]],p=["do","if","in","for","let","new","try","var","case","else","enum","eval","false","null","this","true","void","with","break","catch","class","const","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof"]},{"../config":99,"mol-proto":122}],117:[function(a,b){"use strict";var c={logger:a("./logger"),check:a("./check"),doT:a("dot")};b.exports=c},{"./check":116,"./logger":118,dot:121}],118:[function(a,b){"use strict";var c=a("./logger_class"),d=new c({level:3});b.exports=d},{"./logger_class":119}],119:[function(a,b){"use strict";function c(a){return a.length<g?a+new Array(g-a.length+1).join(" "):a}function d(a,b){return"["+b+"m"+a+" -"}var e=a("mol-proto"),f=["error","warn","info","debug"],g=Math.max.apply(Math,f.map(function(a){return a.length})),h=[31,33,36,90],i={level:3,throwLevel:-1,enabled:!0,logPrefix:""},j=function(a){e.extend(this,i),e.extend(this,a||{})};j.prototype.log=function(a){var b=f.indexOf(a);if(!this.enabled||b>this.level)return this;var g=e.slice(arguments,1);if(b<=this.throwLevel)throw new Error([this.logPrefix,a+":"].concat(g).join(" "));return console.log.apply(console,[this.logPrefixColor?" "+d(this.logPrefix,this.logPrefixColor):this.logPrefix,(this.colors?" "+d(c(a),h[b]):a)+":"].concat(g)),this},f.forEach(function(a){j.prototype[a]=function(){this.log.apply(this,[a].concat(e.toArray(arguments)))}}),b.exports=j},{"mol-proto":122}],120:[function(a,b){!function(){"use strict";function a(b,c,d){return("string"==typeof c?c:c.toString()).replace(b.define||g,function(a,c,e,f){return 0===c.indexOf("def.")&&(c=c.substring(4)),c in d||(":"===e?(b.defineParams&&f.replace(b.defineParams,function(a,b,e){d[c]={arg:b,text:e}}),c in d||(d[c]=f)):new Function("def","def['"+c+"']="+f)(d)),""}).replace(b.use||g,function(c,e){b.useParams&&(e=e.replace(b.useParams,function(a,b,c,e){if(d[c]&&d[c].arg&&e){var f=(c+":"+e).replace(/'|\\/g,"_");return d.__exp=d.__exp||{},d.__exp[f]=d[c].text.replace(new RegExp("(^|[^\\w$])"+d[c].arg+"([^\\w$])","g"),"$1"+e+"$2"),b+"def.__exp['"+f+"']"}}));var f=new Function("def","return "+e)(d);return f?a(b,f,d):f})}function c(a){return a.replace(/\\('|\\)/g,"$1").replace(/[\r\t\n]/g," ")}var d,e={version:"1.0.3",templateSettings:{evaluate:/\{\{([\s\S]+?(\}?)+)\}\}/g,interpolate:/\{\{=([\s\S]+?)\}\}/g,encode:/\{\{!([\s\S]+?)\}\}/g,use:/\{\{#([\s\S]+?)\}\}/g,useParams:/(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,define:/\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,defineParams:/^\s*([\w$]+):([\s\S]+)/,conditional:/\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,iterate:/\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,varname:"it",strip:!0,append:!0,selfcontained:!1,doNotSkipEncoded:!1},template:void 0,compile:void 0};e.encodeHTMLSource=function(a){var b={"&":"&#38;","<":"&#60;",">":"&#62;",'"':"&#34;","'":"&#39;","/":"&#47;"},c=a?/[&<>"'\/]/g:/&(?!#?\w+;)|<|>|"|'|\//g;return function(a){return a?a.toString().replace(c,function(a){return b[a]||a}):""}},d=function(){return this||(0,eval)("this")}(),"undefined"!=typeof b&&b.exports?b.exports=e:"function"==typeof define&&define.amd?define(function(){return e}):d.doT=e;var f={append:{start:"'+(",end:")+'",startencode:"'+encodeHTML("},split:{start:"';out+=(",end:");out+='",startencode:"';out+=encodeHTML("}},g=/$^/;e.template=function(b,h,i){h=h||e.templateSettings;var j,k,l=h.append?f.append:f.split,m=0,n=h.use||h.define?a(h,b,i||{}):b;n=("var out='"+(h.strip?n.replace(/(^|\r|\n)\t* +| +\t*(\r|\n|$)/g," ").replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g,""):n).replace(/'|\\/g,"\\$&").replace(h.interpolate||g,function(a,b){return l.start+c(b)+l.end}).replace(h.encode||g,function(a,b){return j=!0,l.startencode+c(b)+l.end}).replace(h.conditional||g,function(a,b,d){return b?d?"';}else if("+c(d)+"){out+='":"';}else{out+='":d?"';if("+c(d)+"){out+='":"';}out+='"}).replace(h.iterate||g,function(a,b,d,e){return b?(m+=1,k=e||"i"+m,b=c(b),"';var arr"+m+"="+b+";if(arr"+m+"){var "+d+","+k+"=-1,l"+m+"=arr"+m+".length-1;while("+k+"<l"+m+"){"+d+"=arr"+m+"["+k+"+=1];out+='"):"';} } out+='"}).replace(h.evaluate||g,function(a,b){return"';"+c(b)+"out+='"})+"';return out;").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/(\s|;|\}|^|\{)out\+='';/g,"$1").replace(/\+''/g,""),j&&(h.selfcontained||!d||d._encodeHTML||(d._encodeHTML=e.encodeHTMLSource(h.doNotSkipEncoded)),n="var encodeHTML = typeof _encodeHTML !== 'undefined' ? _encodeHTML : ("+e.encodeHTMLSource.toString()+"("+(h.doNotSkipEncoded||"")+"));"+n);try{return new Function(h.varname,n)}catch(o){throw"undefined"!=typeof console&&console.log("Could not create a template function: "+n),o}},e.compile=function(a,b){return e.template(a,null,b)}}()},{}],121:[function(a,b){function c(a){this.__path=a.path||"./","/"!==this.__path[this.__path.length-1]&&(this.__path+="/"),this.__destination=a.destination||this.__path,"/"!==this.__destination[this.__destination.length-1]&&(this.__destination+="/"),this.__global=a.global||"window.render",this.__rendermodule=a.rendermodule||{},this.__settings=a.templateSettings?e(a.templateSettings,e(h.templateSettings)):void 0,this.__includes={}}function d(a){for(var b="",c=0;c<a.length;c++)b+="itself."+a[c]+"="+a[c]+";";return b}function e(a,b){b=b||{};for(var c in a)b[c]=a[c];return b}function f(a){var b=g.readFileSync(a);return b?b.toString():void console.log("problems with "+a)}var g=a("fs"),h=b.exports=a("./doT");h.process=function(a){return new c(a).compileAll()},c.prototype.compileToFile=function(a,b,c){c=c||{};var f,i=a.substring(a.lastIndexOf("/")+1,a.lastIndexOf(".")),j=e(this.__includes,e(c)),k=this.__settings||h.templateSettings,l=e(k),m=h.template(b,k,j),n=[],o="";for(var p in j)j[p]!==c[p]&&j[p]!==this.__includes[p]&&(f=void 0,"string"==typeof j[p]?f=h.template(j[p],k,j):"function"==typeof j[p]?f=j[p]:j[p].arg&&(l.varname=j[p].arg,f=h.template(j[p].text,l,j)),f&&(o+=f.toString().replace("anonymous",p),n.push(p)));o+=m.toString().replace("anonymous",i),g.writeFileSync(a,"(function(){"+o+"var itself="+i+", _encodeHTML=("+h.encodeHTMLSource.toString()+"("+(k.doNotSkipEncoded||"")+"));"+d(n)+"if(typeof module!=='undefined' && module.exports) module.exports=itself;else if(typeof define==='function')define(function(){return itself;});else {"+this.__global+"="+this.__global+"||{};"+this.__global+"['"+i+"']=itself;}}());")},c.prototype.compilePath=function(a){var b=f(a);return b?h.template(b,this.__settings||h.templateSettings,e(this.__includes)):void 0},c.prototype.compileAll=function(){console.log("Compiling all doT templates...");var a,b,c,d=this.__path,e=g.readdirSync(d);for(a=0,b=e.length;b>a;a++)c=e[a],/\.def(\.dot|\.jst)?$/.test(c)&&(console.log("Loaded def "+c),this.__includes[c.substring(0,c.indexOf("."))]=f(d+c));for(a=0,b=e.length;b>a;a++)c=e[a],/\.dot(\.def|\.jst)?$/.test(c)&&(console.log("Compiling "+c+" to function"),this.__rendermodule[c.substring(0,c.indexOf("."))]=this.compilePath(d+c)),/\.jst(\.dot|\.def)?$/.test(c)&&(console.log("Compiling "+c+" to file"),this.compileToFile(this.__destination+c.substring(0,c.indexOf("."))+".js",f(d+c)));return this.__rendermodule}},{"./doT":120,fs:96}],122:[function(a,b){"use strict";function c(a){var b=Object.create(c.prototype);return b.self=a,b}function d(){return this.self}var e=a("./utils"),f=a("./proto_prototype"),g=a("./proto_object"),h=a("./proto_array"),i=a("./proto_function"),j=a("./proto_string"),k=a("./proto_number"),l=a("./proto_util"),m={};g.extend.call(m,g),m.extend.call(m,f),m.extend.call(m,h),m.extend.call(m,j),m.extend.call(m,k),m.extend.call(m,i),m.extend.call(m,l),m.defineProperty(c,"__",m),m.extendProto.call(c,{_:d}),m.extend.call(c,g._constants);var n=m.mapKeys.call(m,e.makeProtoFunction,!0);m.extend.call(c,n);var o=m.mapKeys.call(m,e.makeProtoInstanceMethod,!0);m.extendProto.call(c,o),"object"==typeof window&&(window._&&(c.underscore=window._),window._=c),"object"==typeof b&&b.exports&&(b.exports=c)},{"./proto_array":123,"./proto_function":124,"./proto_number":125,"./proto_object":126,"./proto_prototype":127,"./proto_string":128,"./proto_util":129,"./utils":130}],123:[function(a,b){"use strict";function c(a){if(!a.length)return this;Array.isArray(a)||(a=f.call(a));var b=[this.length,0].concat(a);return m.splice.apply(this,b),this}function d(a){if(!a.length)return this;Array.isArray(a)||(a=f.call(a));var b=[0,0].concat(a);return m.splice.apply(this,b),this}function e(a){var b=this.indexOf(a);return b>=0&&this.splice(b,1),this}function f(){return m.slice.call(this)}function g(a){var b={},c=Array.isArray(a);return m.forEach.call(this,function(d,e){b[d]=c?a[e]:a}),b}function h(a,b){var c={};return Array.prototype.forEach.call(this,function(d,e){c[d]=a.call(b,d,e,this)},this),c}function i(a){function b(b){return m.findIndex.call(d,function(c){return a(b,c)})}function c(a){return d.indexOf(a)}var d=[];return a||(b=c),this.forEach(function(a){var c=b(a);-1==c&&d.push(a)}),d}function j(a,b){function c(){m.forEach.call(this,function(f){Array.isArray(f)?c.call(f):a.call(b,f,d++,e)})}var d=0,e=this;c.call(this)}var k=a("./proto_object"),l=a("./utils"),m=b.exports={appendArray:c,prependArray:d,toArray:f,object:g,mapToObject:h,unique:i,deepForEach:j,spliceItem:e},n=["join","pop","push","concat","reverse","shift","unshift","slice","splice","sort","filter","forEach","some","every","map","indexOf","lastIndexOf","reduce","reduceRight"],o=h.call(n,function(a){return Array.prototype[a]});k.extend.call(m,o),m.find=Array.prototype.find||l.makeFindMethod(m.forEach,"value"),m.findIndex=Array.prototype.findIndex||l.makeFindMethod(m.forEach,"index")},{"./proto_object":126,"./utils":130}],124:[function(require,module,exports){"use strict";function makeFunction(arg1,arg2,funcBody){for(var name=this,count=arguments.length-1,funcBody=arguments[count],func,code="",i=0;count>i;i++)code+=", "+arguments[i];return code=["func = function ",name,"(",code.slice(2),") {\n",funcBody,"\n}"].join(""),eval(code),func}function partial(){var a=this,b=slice.call(arguments);return function(){return a.apply(this,b.concat(slice.call(arguments)))}}function partialRight(){var a=this,b=slice.call(arguments);return function(){return a.apply(this,slice.call(arguments).concat(b))}}function memoize(a,b){var c=this,d={},e=[];return b=b||1e3,function(){var f=a?a.apply(this,arguments):arguments[0];if(d.hasOwnProperty(f))return d[f];var g=d[f]=c.apply(this,arguments);return e.push(f),e.length>b&&delete d[e.shift()],g}}function delay(a){var b=slice.call(arguments,1);return _delay(this,a,b)}function defer(){return _delay(this,1,arguments)}function _delay(a,b,c,d){return setTimeout(a.apply.bind(a,d||null,c),b)}function deferTicks(a){if(2>a)return defer.apply(this,arguments);var b=repeat.call(deferFunc,a-1);return b=b.concat(this,slice.call(arguments,1)),deferFunc.apply(null,b)}function delayMethod(a,b){var c=slice.call(arguments,2);return _delayMethod(this,a,b,c)}function deferMethod(a){var b=slice.call(arguments,1);return _delayMethod(this,a,1,b)}function _delayMethod(a,b,c,d){return setTimeout(function(){var c="string"==typeof b?a[b]:b;c.apply(a,d)},c)}function delayed(a){var b=this,c=slice.call(arguments,1);return function(){var d=c.concat(slice.call(arguments));return _delay(b,a,d,this)}}function deferred(){var a=this,b=slice.call(arguments);return function(){var c=b.concat(slice.call(arguments));return _delay(a,1,c,this)}}function debounce(a,b){var c,d,e,f,g,h=this;return function(){function i(){var j=Date.now()-f;a>j?c=setTimeout(i,a-j):(c=null,b||(g=h.apply(e,d)))}e=this,d=arguments,f=Date.now();var j=b&&!c;return c||(c=setTimeout(i,a)),j&&(g=h.apply(e,d)),g}}function throttle(a,b){function c(){i=b.leading===!1?0:Date.now(),h=null,f=g.apply(d,e)}var d,e,f,g=this,h=null,i=0;return b||(b={}),function(){var j=Date.now();i||b.leading!==!1||(i=j);var k=a-(j-i);return d=this,e=arguments,0>=k?(clearTimeout(h),h=null,i=j,f=g.apply(d,e)):h||b.trailing===!1||(h=setTimeout(c,k)),f}}function once(){var a,b=this,c=!1;return function(){return c?a:(c=!0,a=b.apply(this,arguments),b=null,a)}}function waitFor(a,b,c,d){function e(){if(g())a();else{if(!(Date.now()-f>=b))return;c&&c()}clearInterval(h)}var f=Date.now(),g=this;d=d||50;var h=setInterval(e,d)}function not(){var a=this;return function(){return!a.apply(this,arguments)}}var makeProtoFunction=require("./utils").makeProtoFunction,repeat=require("./proto_util").repeat,functionMethods=module.exports={makeFunction:makeFunction,partial:partial,partialRight:partialRight,memoize:memoize,delay:delay,defer:defer,delayed:delayed,deferred:deferred,deferTicks:deferTicks,delayMethod:delayMethod,deferMethod:deferMethod,debounce:debounce,throttle:throttle,once:once,waitFor:waitFor,not:not},slice=Array.prototype.slice,deferFunc=makeProtoFunction(defer) },{"./proto_util":129,"./utils":130}],125:[function(a,b){"use strict";function c(){return!isNaN(parseFloat(this))&&isFinite(this)}b.exports={isNumeric:c}},{}],126:[function(a,b){"use strict";function c(a,b){var c={};return p.call(a,function(b,d){c[d]=Object.getOwnPropertyDescriptor(a,d)},this,b),Object.defineProperties(this,c),this}function d(){if(Array.isArray(this))return this.slice();if(this instanceof Date)return new Date(this);if(this instanceof RegExp)return new RegExp(this);var a=Object.create(this.constructor.prototype);return c.call(a,this),a}function e(a,b,c){return Object.defineProperty(this,a,f(b,c)),this}function f(a,b){var d={value:a};return b&&c.call(d,{enumerable:!!(b&B.ENUMERABLE),configurable:!!(b&B.CONFIGURABLE),writable:!!(b&B.WRITABLE)}),d}function g(a,b){var c=q.call(a,function(a){return f(a,b)},!0);return Object.defineProperties(this,c),this}function h(a,b){return i(this,a,b,[])}function i(a,b,c,d){if(!(d.indexOf(b)>=0)){d.push(b);var e=Array.isArray(b)?Array.prototype.forEach:p;return e.call(b,function(e,f){var g=Object.getOwnPropertyDescriptor(b,f);"object"!=typeof e||null==e||e instanceof RegExp||e instanceof Date?Object.defineProperty(a,f,g):(a.hasOwnProperty(f)&&"object"==typeof a[f]&&null!=a[f]||(a[f]=Array.isArray(e)?[]:{}),i(a[f],e,c,d))},this,c),a}}function j(a){if(this instanceof Date)return new Date(this);if(this instanceof RegExp)return new RegExp(this);var b=Array.isArray(this)?[]:{};return h.call(b,this,a),b}function k(){return Object.keys(this)}function l(a){var b=a?Object.keys(this):m.call(this);return b.map(function(a){return this[a]},this)}function m(){return Object.getOwnPropertyNames(this)}function n(a,b){for(var c=b?Object.keys(this):m.call(this),d=0;d<c.length;d++)if(a===this[c[d]])return c[d];return void 0}function o(a,b){var c=b?Object.keys(this):m.call(this),d=c.filter(function(b){return a===this[b]},this);return d}function p(a,b,c){var d=c?Object.keys(this):m.call(this);return d.forEach(function(c){a.call(b,this[c],c,this)},this),this}function q(a,b,c){function d(b,c,d){e[c]=Object.getOwnPropertyDescriptor(d,c),e[c].value=a.call(this,b,c,d)}var e={};return p.call(this,d,b,c),Object.create(this.constructor.prototype,e)}function r(a,b,c,d){var e=d?Object.keys(this):m.call(this),f=b;return e.forEach(function(b){f=a.call(c,f,this[b],b,this)},this),f}function s(a,b,c){function d(b,c,d){a.call(this,b,c,d)&&(e[c]=Object.getOwnPropertyDescriptor(d,c))}var e={};return p.call(this,d,b,c),Object.create(this.constructor.prototype,e)}function t(a,b,c){function d(b,c,d){if(a.call(this,b,c,d))throw C}try{p.call(this,d,b,c)}catch(e){if(e===C)return!0;throw e}return!1}function u(a,b,c){function d(b,c,d){if(!a.call(this,b,c,d))throw D}try{p.call(this,d,b,c)}catch(e){if(e===D)return!1;throw e}return!0}function v(){var a=F.apply(E,arguments),b=Object.create(this.constructor.prototype);return a.forEach(function(a){this.hasOwnProperty(a)&&(b[a]=this[a])},this),b}function w(){var a=F.apply(E,arguments),b=d.call(this);return a.forEach(function(a){delete b[a]},this),b}function x(a){if(this===a)return 0!==this||1/this==1/a;if(null==this||null==a)return!1;var b=this.constructor.name;if(b!=a.constructor.name)return!1;switch(b){case"String":return this==String(a);case"Number":return this!=+this?a!=+a:0==this?1/this==1/a:this==+a;case"Date":case"Boolean":return+this==+a;case"RegExp":return this.source==a.source&&this.global==a.global&&this.multiline==a.multiline&&this.ignoreCase==a.ignoreCase}return"object"!=typeof this||"object"!=typeof a?!1:Array.isArray(this)?this.length==a.length&&this.every(function(b,c){return x.call(b,a[c])}):m.call(this).length==m.call(a).length&&u.call(this,function(b,c){return x.call(b,a[c])})}function y(a){return!x.call(this,a)}var z=a("./utils"),A=b.exports={extend:c,clone:d,defineProperty:e,defineProperties:g,deepExtend:h,deepClone:j,keys:k,allKeys:m,values:l,keyOf:n,allKeysOf:o,eachKey:p,mapKeys:q,reduceKeys:r,filterKeys:s,someKey:t,everyKey:u,pickKeys:v,omitKeys:w,isEqual:x,isNot:y},B={ENUMERABLE:1,ENUM:1,CONFIGURABLE:2,CONF:2,WRITABLE:4,WRIT:4};e.call(A,"_constants",B),A.findValue=z.makeFindMethod(p,"value"),A.findKey=z.makeFindMethod(p,"key");var C={},D={},E=Array.prototype,F=E.concat},{"./utils":130}],127:[function(require,module,exports){"use strict";function extendProto(a){var b={};return __.eachKey.call(a,function(a,c){b[c]={enumerable:!1,configurable:!1,writable:!1,value:a}}),Object.defineProperties(this.prototype,b),this}function createSubclass(name,applyConstructor){var thisClass=this,subclass;name=name||"";var constructorCode=applyConstructor===!1?"":"thisClass.apply(this, arguments);";return eval("subclass = function "+name+"(){ "+constructorCode+" }"),makeSubclass.call(subclass,thisClass),__.deepExtend.call(subclass,thisClass,!0),subclass}function makeSubclass(a){return this.prototype=Object.create(a.prototype),extendProto.call(this,{constructor:this}),this}function newApply(a){Array.isArray(a)||(a=Array.prototype.slice.call(a));var a=[null].concat(a);return new(Function.prototype.bind.apply(this,a))}var prototypeMethods=module.exports={extendProto:extendProto,createSubclass:createSubclass,makeSubclass:makeSubclass,newApply:newApply},__=require("./proto_object");__.extend.call(__,require("./proto_function"))},{"./proto_function":124,"./proto_object":126}],128:[function(require,module,exports){"use strict";function firstUpperCase(){return this?this[0].toUpperCase()+this.slice(1):this}function firstLowerCase(){return this?this[0].toLowerCase()+this.slice(1):this}function toRegExp(){var a=this.match(regexpStringPattern);return a?new RegExp(a[1],a[2]):void 0}function toFunction(){var func,code="func = "+this+";";try{return eval(code),func}catch(e){return}}function toDate(){if(this){try{var a=new Date(this)}catch(b){}return a&&a.getTime&&!isNaN(a.getTime())?a:void 0}}function toQueryString(a){var b="",c=this||{},a=a||encodeURIComponent;return __.eachKey.call(c,function(c,d){b+=d+"="+a(c)+"&"}),b.slice(0,-1)}function fromQueryString(a){var b=this.split("&"),c={},a=a||decodeURIComponent;return b.forEach(function(b){var d=b.split("=");if(!(d.length<2)){var e=d[0],f=a(d[1]||"");e&&(c[e]=f)}}),c}function jsonParse(){try{return JSON.parse(this)}catch(a){}}function hashCode(){for(var a=5381,b=this,c=b.length,d=0;c>d;d++){var e=b.charCodeAt(d);a=(a<<5)+a+e}return a}function unPrefix(a){return 0==this.indexOf(a)?this.replace(a,""):void 0}var __=require("./proto_object"),stringMethods=module.exports={firstUpperCase:firstUpperCase,firstLowerCase:firstLowerCase,toRegExp:toRegExp,toFunction:toFunction,toDate:toDate,toQueryString:toQueryString,fromQueryString:fromQueryString,jsonParse:jsonParse,hashCode:hashCode,unPrefix:unPrefix},regexpStringPattern=/^\/(.*)\/([gimy]*)$/},{"./proto_object":126}],129:[function(a,b){"use strict";function c(a,b){for(var c=Array(Math.max(0,this)),d=0;this>d;d++)c[d]=a.call(b,d);return c}function d(a){for(var b=Array(Math.max(0,a)),c=0;a>c;c++)b[c]=this;return b}function e(a){return a.call(this,this),this}function f(a){var b=Array.prototype.slice.call(arguments,1);return"function"==typeof this?this.apply(a,b):this}function g(){return this}function h(){var a=this;return function(b){return b[a]}}function i(){var a=this;return function(b,c){return b[a]<c[a]?-1:b[a]>c[a]?1:0}}function j(){}b.exports={times:c,repeat:d,tap:e,result:f,identity:g,property:h,compareProperty:i,noop:j}},{}],130:[function(a,b){"use strict";function c(a){return function(){return this.self=a.apply(this.self,arguments),this}}function d(a){return function(){return a.call.apply(a,arguments)}}function e(a,b){var c="value"==b?0:1;return function(b,d,e){function g(a,d,e){var g;try{g=b.call(this,a,d,e)}catch(i){throw h=i,f}if(g)throw arguments[c]}var h;try{a.call(this,g,d,e)}catch(i){if(i===f)throw h;return i}return c&&a==Array.prototype.forEach?-1:void 0}}var f=(b.exports={makeProtoInstanceMethod:c,makeProtoFunction:d,makeFindMethod:e},new Error)},{}]},{},[66]); //# sourceMappingURL=milo.min.js.map
src/components/ShareExperience/InterviewStepsForm/index.js
goodjoblife/GoodJobShare
import React from 'react'; import R from 'ramda'; import { Switch } from 'react-router-dom'; import { scroller } from 'react-scroll'; import ReactGA from 'react-ga'; import ReactPixel from 'react-facebook-pixel'; import qs from 'qs'; import StepControl from './StepControl'; import Step1 from './Step1'; import Step2 from './Step2'; import Step3 from './Step3'; import styles from './InterviewForm.module.css'; import { interviewFormCheck } from './formCheck'; import { handleBlocks, getInterviewForm, portInterviewFormToRequestFormat, idGenerator, } from '../utils'; import StaticHelmet from 'common/StaticHelmet'; import { EnterFormTracker, SubmitFormTracker } from 'utils/eventBasedTracking'; import { calcInterviewExperienceValue } from 'utils/uploadSuccessValueCalc'; import { INVALID, INTERVIEW_FORM_ORDER, INTERVIEW_FORM_STEPS, } from '../../../constants/formElements'; import { GA_CATEGORY, GA_ACTION } from '../../../constants/gaConstants'; import PIXEL_CONTENT_CATEGORY from '../../../constants/pixelConstants'; import { LS_INTERVIEW_STEPS_FORM_KEY } from '../../../constants/localStorageKey'; import SuccessFeedback from '../common/SuccessFeedback'; import FailFeedback from '../common/FailFeedback'; import RouteWithSubRoutes from '../../route'; function isExpired(ts) { return Date.now() - ts > 1000 * 60 * 60 * 24 * 3; // 3 days } const createSection = id => ( subtitle, placeholder = '', titlePlaceholder = '段落標題,例:面試方式', content = '', ) => { const section = { id, subtitle, placeholder, titlePlaceholder, content, isSubtitleEditable: false, }; if (subtitle === '自訂段落' || !subtitle) { return { ...section, subtitle: '', isSubtitleEditable: true, placeholder, titlePlaceholder, }; } return section; }; const createInterviewQa = id => (question = '') => ({ id, question, answer: '', }); const createBlock = { sections: createSection, interviewQas: createInterviewQa, }; let idCounter = idGenerator(); const experienceSectionId = idCounter(); const suggestionSectionId = idCounter(); const defaultForm = { companyQuery: '', companyId: '', region: '', jobTitle: '', experienceInYear: null, education: null, interviewTimeYear: null, interviewTimeMonth: null, interviewResult: null, salaryType: 'month', salaryAmount: '', overallRating: 0, title: '面試經驗分享', sections: { [experienceSectionId]: createBlock.sections(experienceSectionId)( '面試過程', undefined, undefined, '第一次面試:\n第二次面試:\n工作環境:', ), [suggestionSectionId]: createBlock.sections(suggestionSectionId)( '給其他面試者的中肯建議', undefined, undefined, '如何準備面試:\n是否推薦此份工作:\n其他注意事項:', ), }, interviewQas: {}, interviewSensitiveQuestions: [], }; const getDefaultFormFromDraft = () => { try { const { __updatedAt, __idCounterCurrent, ...storedDraft } = JSON.parse( localStorage.getItem(LS_INTERVIEW_STEPS_FORM_KEY), ); if (isExpired(__updatedAt)) { console.warn(`Stored draft expired at ${new Date(__updatedAt)}`); localStorage.removeItem(LS_INTERVIEW_STEPS_FORM_KEY); return null; } else { idCounter = idGenerator( __idCounterCurrent !== undefined ? __idCounterCurrent : getMaxId(storedDraft), ); return storedDraft; } } catch (error) { return null; } }; const getDefaultFormFromLocation = location => { const companyName = qs.parse(location.search, { ignoreQueryPrefix: true }) .companyName; if (companyName) { return { ...defaultForm, companyQuery: companyName, }; } return null; }; const getMaxId = state => { const ids = [...R.keys(state.sections), ...R.keys(state.interviewQas)]; const maxId = R.reduce(R.max, -Infinity, ids); if (maxId === undefined) return -1; return maxId; }; const isStepTabActive = step => (match, location) => { const matched = location.pathname.match(/step(\d+)$/); if (!matched) return false; const currentStep = parseInt(matched[1], 10); return currentStep >= step; }; class InterviewForm extends React.Component { constructor(props) { super(props); this.handleState = this.handleState.bind(this); this.appendBlock = this.appendBlock.bind(this); this.removeBlock = this.removeBlock.bind(this); this.editBlock = this.editBlock.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { ...defaultForm, submitted: false, }; this.elementValidationStatus = {}; } componentDidMount() { const defaultState = getDefaultFormFromLocation(this.props.location) || getDefaultFormFromDraft() || defaultForm; this.setState({ // eslint-disable-line react/no-did-mount-set-state ...defaultState, }); ReactPixel.track('InitiateCheckout', { content_category: PIXEL_CONTENT_CATEGORY.VISIT_INTERVIEW_FORM, }); } componentDidUpdate(prevProps, prevState) { if (!R.equals(this.state, prevState)) { localStorage.setItem( LS_INTERVIEW_STEPS_FORM_KEY, JSON.stringify({ ...this.state, __idCounterCurrent: idCounter.getCurrent(), __updatedAt: Date.now(), }), ); } /** Send EnterForm event to Amplitude */ const { pathname } = this.props.location; const { pathname: prevPathname } = prevProps.location; if (pathname !== prevPathname) { const pathnameStepMap = { '/share/interview/step1': 1, '/share/interview/step2': 2, '/share/interview/step3': 3, }; if (pathnameStepMap[pathname]) { EnterFormTracker.sendEvent({ step: pathnameStepMap[pathname], type: EnterFormTracker.types.interview3Steps, }); } } } async onSubmit() { const valid = interviewFormCheck(getInterviewForm(this.state)); let goalValue; if (valid) { localStorage.removeItem(LS_INTERVIEW_STEPS_FORM_KEY); const body = portInterviewFormToRequestFormat( getInterviewForm(this.state), ); // section 的標題與預設文字 = 4 + 11 + 19 + 25 個字 goalValue = calcInterviewExperienceValue(body, 59); const p = this.props.createInterviewExperience({ body, }); return p.then( response => { const experienceId = response.createInterviewExperience.experience.id; ReactGA.event({ category: GA_CATEGORY.SHARE_INTERVIEW, action: GA_ACTION.UPLOAD_SUCCESS, value: goalValue, }); ReactPixel.track('Purchase', { value: 1, currency: 'TWD', content_category: PIXEL_CONTENT_CATEGORY.UPLOAD_INTERVIEW_EXPERIENCE, }); // send SubmitForm event to Amplitude SubmitFormTracker.sendEvent({ type: SubmitFormTracker.types.interview3Steps, result: SubmitFormTracker.results.success, }); return () => ( <SuccessFeedback buttonClick={() => window.location.replace(`/experiences/${experienceId}`) } /> ); }, error => { ReactGA.event({ category: GA_CATEGORY.SHARE_INTERVIEW, action: GA_ACTION.UPLOAD_FAIL, }); // send SubmitForm event to Amplitude SubmitFormTracker.sendEvent({ type: SubmitFormTracker.types.interview3Steps, result: SubmitFormTracker.results.error, }); return ({ buttonClick }) => ( <FailFeedback info={error.message} buttonClick={buttonClick} /> ); }, ); } this.handleState('submitted')(true); const topInvalidElement = this.getTopInvalidElement(); if (topInvalidElement !== null) { console.info('topInvalidElement', topInvalidElement); for (let i = 0; i < INTERVIEW_FORM_STEPS.length; i++) { for (let elementName of INTERVIEW_FORM_STEPS[i]) { if ( typeof elementName === 'function' ? elementName(topInvalidElement) : elementName === topInvalidElement ) { const targetPath = `/share/interview/step${i + 1}`; if (this.props.location.pathname !== targetPath) { await this.props.history.push(targetPath); } } } } scroller.scrollTo(topInvalidElement, { duration: 1000, delay: 100, offset: -100, smooth: true, }); } return Promise.reject(); } getTopInvalidElement = () => { const order = [ ...INTERVIEW_FORM_ORDER, ...R.keys(this.state.sections).map(id => `section-${id}`), ]; console.info(order, this.elementValidationStatus); for (let i = 0; i <= order.length; i += 1) { if ( this.elementValidationStatus[order[i]] && this.elementValidationStatus[order[i]] === INVALID ) { return order[i]; } } return null; }; changeValidationStatus = (elementId, status) => { this.elementValidationStatus[elementId] = status; }; handleState(key) { return value => { const updateState = { [key]: value, }; this.setState(updateState); }; } appendBlock(blockKey) { return (subtitle, placeholder, titlePlaceholder) => { const id = idCounter(); return this.setState(state => ({ [blockKey]: { ...state[blockKey], [id]: createBlock[blockKey](id)( subtitle, placeholder, titlePlaceholder, ), }, })); }; } removeBlock(blockKey) { return id => this.setState(state => { return { [blockKey]: R.filter(block => block.id !== id)(state[blockKey]), }; }); } editBlock(blockKey) { return id => key => value => this.setState(state => ({ [blockKey]: { ...state[blockKey], [id]: { ...state[blockKey][id], [key]: value, }, }, })); } render() { const { location: { pathname }, routes, } = this.props; return ( <div> <StaticHelmet.ShareInterview /> <div className={styles.header}> <div className={styles.title}>面試心得分享</div> <div className={styles.stepsWrapper}> <StepControl.Group> {R.range(1, 4).map(i => ( <StepControl key={i} isActive={isStepTabActive(i)}> {i} </StepControl> ))} </StepControl.Group> </div> </div> {this.state.submitted && ( <div style={{ marginTop: '20px', marginBottom: '20px', }} className={styles.warning__wording} > oops! 請檢查底下紅框內的內容是否正確 </div> )} {/* * Here we need to render all steps rather than use <Route /> * Because rendering all steps allows us to register the handlers * when the input is not validated on submit */} <div style={{ display: pathname === '/share/interview/step1' ? 'block' : 'none', }} > <Step1 handleState={this.handleState} state={this.state} changeValidationStatus={this.changeValidationStatus} /> </div> <div style={{ display: pathname === '/share/interview/step2' ? 'block' : 'none', }} > <Step2 handleState={this.handleState} state={this.state} changeValidationStatus={this.changeValidationStatus} /> </div> <div style={{ display: pathname === '/share/interview/step3' ? 'block' : 'none', }} > <Step3 handleState={this.handleState} state={this.state} sections={handleBlocks(this.state.sections)} appendSection={this.appendBlock('sections')} removeSection={this.removeBlock('sections')} editSection={this.editBlock('sections')} interviewQas={handleBlocks(this.state.interviewQas)} appendQa={this.appendBlock('interviewQas')} removeQa={this.removeBlock('interviewQas')} editQa={this.editBlock('interviewQas')} changeValidationStatus={this.changeValidationStatus} onSubmit={this.onSubmit} /> </div> <Switch> {routes.map((route, i) => ( <RouteWithSubRoutes key={i} {...route} /> ))} </Switch> </div> ); } } InterviewForm.propTypes = {}; export default InterviewForm;
ajax/libs/yui/3.11.0pr1/scrollview-base/scrollview-base-debug.js
dc-js/cdnjs
YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ // Local vars var getClassName = Y.ClassNameManager.getClassName, DOCUMENT = Y.config.doc, IE = Y.UA.ie, NATIVE_TRANSITIONS = Y.Transition.useNative, vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated SCROLLVIEW = 'scrollview', CLASS_NAMES = { vertical: getClassName(SCROLLVIEW, 'vert'), horizontal: getClassName(SCROLLVIEW, 'horiz') }, EV_SCROLL_END = 'scrollEnd', FLICK = 'flick', DRAG = 'drag', MOUSEWHEEL = 'mousewheel', UI = 'ui', TOP = 'top', LEFT = 'left', PX = 'px', AXIS = 'axis', SCROLL_Y = 'scrollY', SCROLL_X = 'scrollX', BOUNCE = 'bounce', DISABLED = 'disabled', DECELERATION = 'deceleration', DIM_X = 'x', DIM_Y = 'y', BOUNDING_BOX = 'boundingBox', CONTENT_BOX = 'contentBox', GESTURE_MOVE = 'gesturemove', START = 'start', END = 'end', EMPTY = '', ZERO = '0s', SNAP_DURATION = 'snapDuration', SNAP_EASING = 'snapEasing', EASING = 'easing', FRAME_DURATION = 'frameDuration', BOUNCE_RANGE = 'bounceRange', _constrain = function (val, min, max) { return Math.min(Math.max(val, min), max); }; /** * ScrollView provides a scrollable widget, supporting flick gestures, * across both touch and mouse based devices. * * @class ScrollView * @param config {Object} Object literal with initial attribute values * @extends Widget * @constructor */ function ScrollView() { ScrollView.superclass.constructor.apply(this, arguments); } Y.ScrollView = Y.extend(ScrollView, Y.Widget, { // *** Y.ScrollView prototype /** * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit. * Used by the _transform method. * * @property _forceHWTransforms * @type boolean * @protected */ _forceHWTransforms: Y.UA.webkit ? true : false, /** * <p>Used to control whether or not ScrollView's internal * gesturemovestart, gesturemove and gesturemoveend * event listeners should preventDefault. The value is an * object, with "start", "move" and "end" properties used to * specify which events should preventDefault and which shouldn't:</p> * * <pre> * { * start: false, * move: true, * end: false * } * </pre> * * <p>The default values are set up in order to prevent panning, * on touch devices, while allowing click listeners on elements inside * the ScrollView to be notified as expected.</p> * * @property _prevent * @type Object * @protected */ _prevent: { start: false, move: true, end: false }, /** * Contains the distance (postive or negative) in pixels by which * the scrollview was last scrolled. This is useful when setting up * click listeners on the scrollview content, which on mouse based * devices are always fired, even after a drag/flick. * * <p>Touch based devices don't currently fire a click event, * if the finger has been moved (beyond a threshold) so this * check isn't required, if working in a purely touch based environment</p> * * @property lastScrolledAmt * @type Number * @public * @default 0 */ lastScrolledAmt: 0, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ _minScrollX: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ _maxScrollX: null, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ _minScrollY: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ _maxScrollY: null, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { var sv = this; // Cache these values, since they aren't going to change. sv._bb = sv.get(BOUNDING_BOX); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes sv._cAxis = sv.get(AXIS); sv._cBounce = sv.get(BOUNCE); sv._cBounceRange = sv.get(BOUNCE_RANGE); sv._cDeceleration = sv.get(DECELERATION); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { var sv = this; // Bind interaction listers sv._bindFlick(sv.get(FLICK)); sv._bindDrag(sv.get(DRAG)); sv._bindMousewheel(true); // Bind change events sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. if (IE) { sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties if (ScrollView.SNAP_DURATION) { sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } if (ScrollView.SNAP_EASING) { sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } if (ScrollView.EASING) { sv.set(EASING, ScrollView.EASING); } if (ScrollView.FRAME_STEP) { sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } if (ScrollView.BOUNCE_RANGE) { sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE); } // Recalculate dimension properties // TODO: This should be throttled. // Y.one(WINDOW).after('resize', sv._afterDimChange, sv); }, /** * Bind event listeners * * @method _bindAttrs * @private */ _bindAttrs: function () { var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners sv.after({ 'scrollEnd': sv._afterScrollEnd, 'disabledChange': sv._afterDisabledChange, 'flickChange': sv._afterFlickChange, 'dragChange': sv._afterDragChange, 'axisChange': sv._afterAxisChange, 'scrollYChange': scrollChangeHandler, 'scrollXChange': scrollChangeHandler, 'heightChange': dimChangeHandler, 'widthChange': dimChangeHandler }); }, /** * Bind (or unbind) gesture move listeners required for drag support * * @method _bindDrag * @param drag {boolean} If true, the method binds listener to enable * drag (gesturemovestart). If false, the method unbinds gesturemove * listeners for drag support. * @private */ _bindDrag: function (drag) { var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners bb.detach(DRAG + '|*'); if (drag) { bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv)); } }, /** * Bind (or unbind) flick listeners. * * @method _bindFlick * @param flick {Object|boolean} If truthy, the method binds listeners for * flick support. If false, the method unbinds flick listeners. * @private */ _bindFlick: function (flick) { var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners bb.detach(FLICK + '|*'); if (flick) { bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick sv._bindDrag(sv.get(DRAG)); } }, /** * Bind (or unbind) mousewheel listeners. * * @method _bindMousewheel * @param mousewheel {Object|boolean} If truthy, the method binds listeners for * mousewheel support. If false, the method unbinds mousewheel listeners. * @private */ _bindMousewheel: function (mousewheel) { var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv)); } }, /** * syncUI implementation. * * Update the scroll position, based on the current value of scrollX/scrollY. * * @method syncUI */ syncUI: function () { var sv = this, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight; // If the axis is undefined, auto-calculate it if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value sv._cDisabled = sv.get(DISABLED); // Run this to set initial values sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. if (sv._isOutOfBounds()) { sv._snapBack(); } }, /** * Utility method to obtain widget dimensions * * @method _getScrollDims * @return {Object} The offsetWidth, offsetHeight, scrollWidth and * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth, * scrollHeight] * @private */ _getScrollDims: function () { var sv = this, cb = sv._cb, bb = sv._bb, TRANS = ScrollView._TRANSITION, // Ideally using CSSMatrix - don't think we have it normalized yet though. // origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e, // origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f, origX = sv.get(SCROLL_X), origY = sv.get(SCROLL_Y), origHWTransform, dims; // TODO: Is this OK? Just in case it's called 'during' a transition. if (NATIVE_TRANSITIONS) { cb.setStyle(TRANS.DURATION, ZERO); cb.setStyle(TRANS.PROPERTY, EMPTY); } origHWTransform = sv._forceHWTransforms; sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. sv._moveTo(cb, 0, 0); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; sv._moveTo(cb, -(origX), -(origY)); sv._forceHWTransforms = origHWTransform; return dims; }, /** * This method gets invoked whenever the height or width attributes change, * allowing us to determine which scrolling axes need to be enabled. * * @method _uiDimensionsChange * @protected */ _uiDimensionsChange: function () { var sv = this, bb = sv._bb, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight, rtl = sv.rtl, svAxis = sv._cAxis, minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0), maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)), minScrollY = 0, maxScrollY = Math.max(0, scrollHeight - height); if (svAxis && svAxis.x) { bb.addClass(CLASS_NAMES.horizontal); } if (svAxis && svAxis.y) { bb.addClass(CLASS_NAMES.vertical); } sv._setBounds({ minScrollX: minScrollX, maxScrollX: maxScrollX, minScrollY: minScrollY, maxScrollY: maxScrollY }); }, /** * Set the bounding dimensions of the ScrollView * * @method _setBounds * @protected * @param bounds {Object} [duration] ms of the scroll animation. (default is 0) * @param {Number} [bounds.minScrollX] The minimum scroll X value * @param {Number} [bounds.maxScrollX] The maximum scroll X value * @param {Number} [bounds.minScrollY] The minimum scroll Y value * @param {Number} [bounds.maxScrollY] The maximum scroll Y value */ _setBounds: function (bounds) { var sv = this; // TODO: Do a check to log if the bounds are invalid sv._minScrollX = bounds.minScrollX; sv._maxScrollX = bounds.maxScrollX; sv._minScrollY = bounds.minScrollY; sv._maxScrollY = bounds.maxScrollY; }, /** * Get the bounding dimensions of the ScrollView * * @method _getBounds * @protected */ _getBounds: function () { var sv = this; return { minScrollX: sv._minScrollX, maxScrollX: sv._maxScrollX, minScrollY: sv._minScrollY, maxScrollY: sv._maxScrollY }; }, /** * Scroll the element to a given xy coordinate * * @method scrollTo * @param x {Number} The x-position to scroll to. (null for no movement) * @param y {Number} The y-position to scroll to. (null for no movement) * @param {Number} [duration] ms of the scroll animation. (default is 0) * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute) * @param {String} [node] The node to transform. Setting this can be useful in * dual-axis paginated instances. (default is the instance's contentBox) */ scrollTo: function (x, y, duration, easing, node) { // Check to see if widget is disabled if (this._cDisabled) { return; } var sv = this, cb = sv._cb, TRANS = ScrollView._TRANSITION, callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this newX = 0, newY = 0, transition = {}, transform; // default the optional arguments duration = duration || 0; easing = easing || sv.get(EASING); // @TODO: Cache this node = node || cb; if (x !== null) { sv.set(SCROLL_X, x, {src:UI}); newX = -(x); } if (y !== null) { sv.set(SCROLL_Y, y, {src:UI}); newY = -(y); } transform = sv._transform(newX, newY); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move if (duration === 0) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', transform); } else { // TODO: If both set, batch them in the same update // Update: Nope, setStyles() just loops through each property and applies it. if (x !== null) { node.setStyle(LEFT, newX + PX); } if (y !== null) { node.setStyle(TOP, newY + PX); } } } // Animate else { transition.easing = easing; transition.duration = duration / 1000; if (NATIVE_TRANSITIONS) { transition.transform = transform; } else { transition.left = newX + PX; transition.top = newY + PX; } node.transition(transition, callback); } }, /** * Utility method, to create the translate transform string with the * x, y translation amounts provided. * * @method _transform * @param {Number} x Number of pixels to translate along the x axis * @param {Number} y Number of pixels to translate along the y axis * @private */ _transform: function (x, y) { // TODO: Would we be better off using a Matrix for this? var prop = 'translate(' + x + 'px, ' + y + 'px)'; if (this._forceHWTransforms) { prop += ' translateZ(0)'; } return prop; }, /** * Utility method, to move the given element to the given xy position * * @method _moveTo * @param node {Node} The node to move * @param x {Number} The x-position to move to * @param y {Number} The y-position to move to * @private */ _moveTo : function(node, x, y) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', this._transform(x, y)); } else { node.setStyle(LEFT, x + PX); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { var sv = this; // If for some reason we're OOB, snapback if (sv._isOutOfBounds()) { sv._snapBack(); } else { /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ sv.fire(EV_SCROLL_END); } }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { if (this._cDisabled) { return false; } var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; if (sv._prevent.start) { e.preventDefault(); } // if a flick animation is in progress, cancel it if (sv._flickAnim) { sv._cancelFlick(); sv._onTransEnd(); } // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later sv._gesture = { // Will hold the axis value axis: null, // The current attribute values startX: currentX, startY: currentY, // The X/Y coordinates where the event began startClientX: clientX, startClientY: clientY, // The X/Y coordinates where the event will end endClientX: null, endClientY: null, // The current delta of the event deltaX: null, deltaY: null, // Will be populated for flicks flick: null, // Create some listeners for the rest of the gesture cycle onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)), // @TODO: Don't bind gestureMoveEnd if it's a Flick? onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv)) }; }, /** * gesturemove event handler * * @method _onGestureMove * @param e {Event.Facade} The gesturemove event facade * @private */ _onGestureMove: function (e) { var sv = this, gesture = sv._gesture, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, startX = gesture.startX, startY = gesture.startY, startClientX = gesture.startClientX, startClientY = gesture.startClientY, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.move) { e.preventDefault(); } gesture.deltaX = startClientX - clientX; gesture.deltaY = startClientY - clientY; // Determine if this is a vertical or horizontal movement // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent if (gesture.axis === null) { gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. if (gesture.axis === DIM_X && svAxisX) { sv.set(SCROLL_X, startX + gesture.deltaX); } else if (gesture.axis === DIM_Y && svAxisY) { sv.set(SCROLL_Y, startY + gesture.deltaY); } }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY, isOOB; if (sv._prevent.end) { e.preventDefault(); } // Store the end X/Y coordinates gesture.endClientX = clientX; gesture.endClientY = clientY; // Cleanup the event handlers gesture.onGestureMove.detach(); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle if (!flick) { // @TODO: Be more intelligent about this. Look at the Flick attribute to see // if it is safe to assume _flick did or didn't fire. // Then, the order _flick and _onGestureMoveEnd fire doesn't matter? // If there was movement (_onGestureMove fired) if (gesture.deltaX !== null && gesture.deltaY !== null) { isOOB = sv._isOutOfBounds(); // If we're out-out-bounds, then snapback if (isOOB) { sv._snapBack(); } // Inbounds else { // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) { sv._onTransEnd(); } } } } }, /** * Execute a flick at the end of a scroll action * * @method _flick * @param e {Event.Facade} The Flick event facade * @private */ _flick: function (e) { if (this._cDisabled) { return false; } var sv = this, svAxis = sv._cAxis, flick = e.flick, flickAxis = flick.axis, flickVelocity = flick.velocity, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, startPosition = sv.get(axisAttr); // Sometimes flick is enabled, but drag is disabled if (sv._gesture) { sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis if (svAxis[flickAxis]) { sv._flickFrame(flickVelocity, flickAxis, startPosition); } }, /** * Execute a single frame in the flick animation * * @method _flickFrame * @param velocity {Number} The velocity of this animated frame * @param flickAxis {String} The axis on which to animate * @param startPosition {Number} The starting X/Y point to flick from * @protected */ _flickFrame: function (velocity, flickAxis, startPosition) { var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, bounds = sv._getBounds(), // Localize cached values bounce = sv._cBounce, bounceRange = sv._cBounceRange, deceleration = sv._cDeceleration, frameDuration = sv._cFrameDuration, // Calculate newVelocity = velocity * deceleration, newPosition = startPosition - (frameDuration * newVelocity), // Some convinience conditions min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY, max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY, belowMin = (newPosition < min), belowMax = (newPosition < max), aboveMin = (newPosition > min), aboveMax = (newPosition > max), belowMinRange = (newPosition < (min - bounceRange)), withinMinRange = (belowMin && (newPosition > (min - bounceRange))), withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))), aboveMaxRange = (newPosition > (max + bounceRange)), tooSlow; // If we're within the range but outside min/max, dampen the velocity if (withinMinRange || withinMaxRange) { newVelocity *= bounce; } // Is the velocity too slow to bother? tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim if (sv._flickAnim) { sv._cancelFlick(); } // If we're inside the scroll area, just end if (aboveMin && belowMax) { sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); sv.set(axisAttr, newPosition); } }, _cancelFlick: function () { var sv = this; if (sv._flickAnim) { // Cancel the flick (if it exists) sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking delete sv._flickAnim; } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { var sv = this, scrollY = sv.get(SCROLL_Y), bounds = sv._getBounds(), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY); // Because Mousewheel events fire off 'document', every ScrollView widget will react // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis, // becuase otherwise the 'prevent' will block page scrolling. if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Jump to the new offset sv.set(SCROLL_Y, scrollToY); // if we have scrollbars plugin, update & set the flash timer on the scrollbar // @TODO: This probably shouldn't be in this module if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves sv.scrollbars._update(); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event sv._onTransEnd(); // prevent browser default behavior on mouse scroll e.preventDefault(); } }, /** * Checks to see the current scrollX/scrollY position beyond the min/max boundary * * @method _isOutOfBounds * @param x {Number} [optional] The X position to check * @param y {Number} [optional] The Y position to check * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false) * @private */ _isOutOfBounds: function (x, y) { var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY; return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY)); }, /** * Bounces back * @TODO: Should be more generalized and support both X and Y detection * * @method _snapBack * @private */ _snapBack: function () { var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); if (newX !== currentX) { sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else if (newY !== currentY) { sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { sv._onTransEnd(); } }, /** * After listener for changes to the scrollX or scrollY attribute * * @method _afterScrollChange * @param e {Event.Facade} The event facade * @protected */ _afterScrollChange: function (e) { if (e.src === ScrollView.UI_SRC) { return false; } var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() if (e.attrName === SCROLL_X) { scrollToArgs.push(val); scrollToArgs.push(sv.get(SCROLL_Y)); } else { scrollToArgs.push(sv.get(SCROLL_X)); scrollToArgs.push(val); } scrollToArgs.push(duration); scrollToArgs.push(easing); sv.scrollTo.apply(sv, scrollToArgs); }, /** * After listener for changes to the flick attribute * * @method _afterFlickChange * @param e {Event.Facade} The event facade * @protected */ _afterFlickChange: function (e) { this._bindFlick(e.newVal); }, /** * After listener for changes to the disabled attribute * * @method _afterDisabledChange * @param e {Event.Facade} The event facade * @protected */ _afterDisabledChange: function (e) { // Cache for performance - we check during move this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { this._cAxis = e.newVal; }, /** * After listener for changes to the drag attribute * * @method _afterDragChange * @param e {Event.Facade} The event facade * @protected */ _afterDragChange: function (e) { this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { var sv = this; if (sv._flickAnim) { sv._cancelFlick(); } // Ideally this should be removed, but doing so causing some JS errors with fast swiping // because _gesture is being deleted after the previous one has been overwritten // delete sv._gesture; // TODO: Move to sv.prevGesture? }, /** * Setter for 'axis' attribute * * @method _axisSetter * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on * @param name {String} The attribute name * @return {Object} An object to specify scrollability on the x & y axes * * @protected */ _axisSetter: function (val) { // Turn a string into an axis object if (Y.Lang.isString(val)) { return { x: val.match(/x/i) ? true : false, y: val.match(/y/i) ? true : false }; } }, /** * The scrollX, scrollY setter implementation * * @method _setScroll * @private * @param {Number} val * @param {String} dim * * @return {Number} The value */ _setScroll : function(val) { // Just ensure the widget is not disabled if (this._cDisabled) { val = Y.Attribute.INVALID_VALUE; } return val; }, /** * Setter for the scrollX attribute * * @method _setScrollX * @param val {Number} The new scrollX value * @return {Number} The normalized value * @protected */ _setScrollX: function(val) { return this._setScroll(val, DIM_X); }, /** * Setter for the scrollY ATTR * * @method _setScrollY * @param val {Number} The new scrollY value * @return {Number} The normalized value * @protected */ _setScrollY: function(val) { return this._setScroll(val, DIM_Y); } // End prototype properties }, { // Static properties /** * The identity of the widget. * * @property NAME * @type String * @default 'scrollview' * @readOnly * @protected * @static */ NAME: 'scrollview', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Specifies ability to scroll on x, y, or x and y axis/axes. * * @attribute axis * @type String */ axis: { setter: '_axisSetter', writeOnce: 'initOnly' }, /** * The current scroll position in the x-axis * * @attribute scrollX * @type Number * @default 0 */ scrollX: { value: 0, setter: '_setScrollX' }, /** * The current scroll position in the y-axis * * @attribute scrollY * @type Number * @default 0 */ scrollY: { value: 0, setter: '_setScrollY' }, /** * Drag coefficent for inertial scrolling. The closer to 1 this * value is, the less friction during scrolling. * * @attribute deceleration * @default 0.93 */ deceleration: { value: 0.93 }, /** * Drag coefficient for intertial scrolling at the upper * and lower boundaries of the scrollview. Set to 0 to * disable "rubber-banding". * * @attribute bounce * @type Number * @default 0.1 */ bounce: { value: 0.1 }, /** * The minimum distance and/or velocity which define a flick. Can be set to false, * to disable flick support (note: drag support is enabled/disabled separately) * * @attribute flick * @type Object * @default Object with properties minDistance = 10, minVelocity = 0.3. */ flick: { value: { minDistance: 10, minVelocity: 0.3 } }, /** * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately) * @attribute drag * @type boolean * @default true */ drag: { value: true }, /** * The default duration to use when animating the bounce snap back. * * @attribute snapDuration * @type Number * @default 400 */ snapDuration: { value: 400 }, /** * The default easing to use when animating the bounce snap back. * * @attribute snapEasing * @type String * @default 'ease-out' */ snapEasing: { value: 'ease-out' }, /** * The default easing used when animating the flick * * @attribute easing * @type String * @default 'cubic-bezier(0, 0.1, 0, 1.0)' */ easing: { value: 'cubic-bezier(0, 0.1, 0, 1.0)' }, /** * The interval (ms) used when animating the flick for JS-timer animations * * @attribute frameDuration * @type Number * @default 15 */ frameDuration: { value: 15 }, /** * The default bounce distance in pixels * * @attribute bounceRange * @type Number * @default 150 */ bounceRange: { value: 150 } }, /** * List of class names used in the scrollview's DOM * * @property CLASS_NAMES * @type Object * @static */ CLASS_NAMES: CLASS_NAMES, /** * Flag used to source property changes initiated from the DOM * * @property UI_SRC * @type String * @static * @default 'ui' */ UI_SRC: UI, /** * Object map of style property names used to set transition properties. * Defaults to the vendor prefix established by the Transition module. * The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and * `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty"). * * @property _TRANSITION * @private */ _TRANSITION: { DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'), PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty') }, /** * The default bounce distance in pixels * * @property BOUNCE_RANGE * @type Number * @static * @default false * @deprecated (in 3.7.0) */ BOUNCE_RANGE: false, /** * The interval (ms) used when animating the flick * * @property FRAME_STEP * @type Number * @static * @default false * @deprecated (in 3.7.0) */ FRAME_STEP: false, /** * The default easing used when animating the flick * * @property EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ EASING: false, /** * The default easing to use when animating the bounce snap back. * * @property SNAP_EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ SNAP_EASING: false, /** * The default duration to use when animating the bounce snap back. * * @property SNAP_DURATION * @type Number * @static * @default false * @deprecated (in 3.7.0) */ SNAP_DURATION: false // End static properties }); }, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
views/src/src/routes/Counter/components/Counter.js
Halooo/halooo.me
import React from 'react' export const Counter = (props) => ( <div style={{ margin: '0 auto' }} > <h2>Counter: {props.counter}</h2> <button className='btn btn-default' onClick={props.increment}> Increment </button> {' '} <button className='btn btn-default' onClick={props.doubleAsync}> Double (Async) </button> </div> ) Counter.propTypes = { counter : React.PropTypes.number.isRequired, doubleAsync : React.PropTypes.func.isRequired, increment : React.PropTypes.func.isRequired } export default Counter
src/svg-icons/maps/local-post-office.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPostOffice = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/> </SvgIcon> ); MapsLocalPostOffice = pure(MapsLocalPostOffice); MapsLocalPostOffice.displayName = 'MapsLocalPostOffice'; MapsLocalPostOffice.muiName = 'SvgIcon'; export default MapsLocalPostOffice;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Promises.js
cr101/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load() { return Promise.resolve([ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]); } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } componentDidMount() { load().then(users => { this.setState({ users }); }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-promises"> {this.state.users.map(user => <div key={user.id}> {user.name} </div> )} </div> ); } }